<?php
// En-têtes CORS et JSON
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit();
}

header("Content-Type: application/json; charset=utf-8");

// Affichage des erreurs PHP (utile en dev)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Connexion BDD
$host = "192.168.0.4";
$dbname = "DemandeConge";
$username = "wpuser";
$password = "-2b/)ru5/Bi8P[7_";

$conn = new mysqli($host, $username, $password, $dbname);
if ($conn->connect_error) {
    echo json_encode(["success" => false, "message" => "Erreur connexion DB: " . $conn->connect_error]);
    exit();
}

// Récup paramètre
$userId = $_GET['user_id'] ?? null;
if (!$userId) {
    echo json_encode(["success" => false, "message" => "ID utilisateur manquant"]);
    exit();
}

// Fonction jours ouvrés
function getWorkingDays($startDate, $endDate) {
    $workingDays = 0;
    $current = new DateTime($startDate);
    $end = new DateTime($endDate);
    while ($current <= $end) {
        $dayOfWeek = (int)$current->format('N');
        if ($dayOfWeek < 6) {
            $workingDays++;
        }
        $current->modify('+1 day');
    }
    return $workingDays;
}

try {
    // Requête multi-types
    $query = "
        SELECT 
            dc.Id,
            dc.DateDebut,
            dc.DateFin,
            dc.Statut,
            dc.DateDemande,
            dc.Commentaire,
            dc.Validateur,
            dc.DocumentJoint,
            GROUP_CONCAT(tc.Nom ORDER BY tc.Nom SEPARATOR ', ') AS TypeConges
        FROM DemandeConge dc
        JOIN TypeConge tc ON FIND_IN_SET(tc.Id, dc.TypeCongeId)
        WHERE dc.EmployeeId = ?
        GROUP BY 
            dc.Id, dc.DateDebut, dc.DateFin, dc.Statut, dc.DateDemande, 
            dc.Commentaire, dc.Validateur, dc.DocumentJoint
        ORDER BY dc.DateDemande DESC
    ";

    $stmt = $conn->prepare($query);
    if (!$stmt) {
        throw new Exception("Erreur préparation SQL : " . $conn->error);
    }

    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $result = $stmt->get_result();

    $requests = [];
    while ($row = $result->fetch_assoc()) {
        $workingDays = getWorkingDays($row['DateDebut'], $row['DateFin']);

        // Format dates
        $startDate = new DateTime($row['DateDebut']);
        $endDate = new DateTime($row['DateFin']);
        $submittedDate = new DateTime($row['DateDemande']);

        $dateDisplay = ($row['DateDebut'] === $row['DateFin'])
            ? $startDate->format('d/m/Y')
            : $startDate->format('d/m/Y') . ' - ' . $endDate->format('d/m/Y');

        // Lien fichier si congé maladie
        $fileUrl = null;
        if (strpos($row['TypeConges'], 'Congé maladie') !== false && !empty($row['DocumentJoint'])) {
            $fileUrl = 'http://localhost/GTA/project/uploads/' . basename($row['DocumentJoint']);
        }

        $requests[] = [
            'id' => (int)$row['Id'],
            'type' => $row['TypeConges'], // ex: "Congé payé, RTT"
            'startDate' => $row['DateDebut'],
            'endDate' => $row['DateFin'],
            'dateDisplay' => $dateDisplay,
            'days' => $workingDays,
            'status' => $row['Statut'],
            'reason' => $row['Commentaire'] ?: 'Aucun commentaire',
            'submittedAt' => $row['DateDemande'],
            'submittedDisplay' => $submittedDate->format('d/m/Y'),
            'validator' => $row['Validateur'] ?: null,
            'fileUrl' => $fileUrl
        ];
    }

    echo json_encode([
        "success" => true,
        "message" => "Demandes récupérées avec succès",
        "requests" => $requests,
        "total" => count($requests)
    ]);

} catch (Exception $e) {
    echo json_encode([
        "success" => false,
        "message" => "Erreur: " . $e->getMessage()
    ]);
}

$conn->close();
