<?php
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");

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Connexion DB
$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) {
    error_log("Erreur connexion DB: " . $conn->connect_error);
    echo json_encode(["success" => false, "message" => "Erreur de connexion DB"]);
    exit();
}


// Récupération ID manager
$managerId = $_GET['SuperieurId'] ?? null;
if (!$managerId) {
    echo json_encode(["success" => false, "message" => "Paramètre SuperieurId manquant"]);
    exit();
}

$sql = "
    SELECT 
        dc.Id,
        dc.DateDebut,
        dc.DateFin,
        dc.Statut,
        dc.DateDemande,
        dc.Commentaire,
        dc.DocumentJoint,
        dc.EmployeeId,
        CONCAT(u.Prenom, ' ', u.Nom) as employee_name,
        u.Email as employee_email,
        tc.Nom as type
    FROM DemandeConge dc
    JOIN Users u ON dc.EmployeeId = u.ID
    JOIN TypeConge tc ON dc.TypeCongeId = tc.Id
    JOIN HierarchieValidation hv ON hv.EmployeId = u.ID
    WHERE hv.SuperieurId = ?
    ORDER BY dc.DateDemande DESC
";

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $managerId);
$stmt->execute();

// Manquant dans ton code
$result = $stmt->get_result();

$requests = [];
while ($row = $result->fetch_assoc()) {
    $startDate = new DateTime($row['DateDebut']);
    $endDate = new DateTime($row['DateFin']);
    $submittedDate = new DateTime($row['DateDemande']);
    $days = 0;

    $tmp = clone $startDate;
    while ($tmp <= $endDate) {
        if ((int)$tmp->format('N') < 6) $days++;
        $tmp->modify('+1 day');
    }

    $requests[] = [
        "id" => (int)$row['Id'],
        "employee_id" => (int)$row['EmployeeId'],
        "employee_name" => $row['employee_name'],
        "employee_email" => $row['employee_email'],
        "type" => $row['type'],
        "start_date" => $row['DateDebut'],
        "end_date" => $row['DateFin'],
        "date_display" => $row['DateDebut'] === $row['DateFin']
            ? $startDate->format('d/m/Y')
            : $startDate->format('d/m/Y') . ' - ' . $endDate->format('d/m/Y'),
        "days" => $days,
        "status" => $row['Statut'],
        "reason" => $row['Commentaire'] ?: '',
        "file" => $row['DocumentJoint'] ?: null,
        "submitted_at" => $row['DateDemande'],
        "submitted_display" => $submittedDate->format('d/m/Y')
    ];
}

echo json_encode([
    "success" => true,
    "requests" => $requests
]);

$stmt->close();
$conn->close();
?>
