<?php
ini_set('display_errors', 0);
error_reporting(E_ALL);
header('Content-Type: application/json');

try {
    require_once '../db.php';

    if (!isset($_SESSION['user_id'])) {
        http_response_code(401);
        echo json_encode(['success' => false, 'message' => 'Non autorisé.']);
        exit;
    }

    $userId = $_SESSION['user_id'];
    $method = $_SERVER['REQUEST_METHOD'];

    if ($method === 'GET') {
        $stmt = $pdo->prepare("SELECT * FROM absences WHERE user_id = :user_id ORDER BY date DESC");
        $stmt->execute(['user_id' => $userId]);
        $list = $stmt->fetchAll() ?: [];

        // Calcul des métriques récapitulatives
        $totalAbsences = 0;
        $totalRetards = 0;
        $justified = 0;
        $unjustified = 0;

        foreach ($list as $item) {
            if ($item['type'] === 'absence') $totalAbsences++;
            if ($item['type'] === 'retard') $totalRetards++;
            if (!empty($item['is_justified']) && $item['is_justified'] == 1) {
                $justified++;
            } else {
                $unjustified++;
            }
        }

        echo json_encode([
            'success' => true,
            'list' => $list,
            'stats' => [
                'total_absences' => $totalAbsences,
                'total_retards' => $totalRetards,
                'justified' => $justified,
                'unjustified' => $unjustified
            ]
        ]);
        exit;
    }

    if ($method === 'POST') {
        $data = json_decode(file_get_contents('php://input'), true);
        $type = $data['type'] ?? 'absence';
        $duration = $data['duration'] ?? 'half_day';
        $date = $data['date'] ?? date('Y-m-d');
        $reason = trim($data['reason'] ?? '');
        $isJustified = !empty($data['is_justified']) ? 1 : 0;

        $stmt = $pdo->prepare("INSERT INTO absences (user_id, type, duration, date, reason, is_justified, created_at) VALUES (:user_id, :type, :duration, :date, :reason, :justified, NOW())");
        $stmt->execute([
            'user_id' => $userId,
            'type' => $type,
            'duration' => $duration,
            'date' => $date,
            'reason' => $reason,
            'justified' => $isJustified
        ]);

        echo json_encode(['success' => true, 'message' => 'Déclaration enregistrée !']);
        exit;
    }

    if ($method === 'DELETE') {
        $data = json_decode(file_get_contents('php://input'), true);
        $id = intval($data['id'] ?? 0);
        if ($id) {
            $stmt = $pdo->prepare("DELETE FROM absences WHERE id = :id AND user_id = :user_id");
            $stmt->execute(['id' => $id, 'user_id' => $userId]);
            echo json_encode(['success' => true, 'message' => 'Supprimé !']);
            exit;
        }
    }
} catch (Throwable $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>