<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

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

header("Content-Type: application/json");

$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) {
    die(json_encode(["success" => false, "message" => "Erreur DB : " . $conn->connect_error]));
}

// Récupérer l'ID
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id <= 0) {
    echo json_encode(["success" => false, "message" => "ID employé invalide"]);
    exit;
}

try {
    $sql = "SELECT Id, TypeCongeId, NombreJours, DateDebut, DateFin, Statut
            FROM DemandeConge
            WHERE EmployeeId = ?
            ORDER BY DateDemande DESC";

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

    // Mapping des types de congés
    $typeNames = [
        1 => "Congé payé",
        2 => "RTT",
        3 => "Maladie"
    ];

    $requests = [];
    while ($row = $result->fetch_assoc()) {
        $row['type'] = $typeNames[$row['TypeCongeId']] ?? "Autre"; 
        $row['days'] = (float)$row['NombreJours'];
        // Formater jours : 2j ou 1.5j
        $row['days_display'] = ((int)$row['days'] == $row['days'] ? (int)$row['days'] : $row['days']) . "j";
        $row['date_display'] = date("d/m/Y", strtotime($row['DateDebut'])) 
                               . " - " 
                               . date("d/m/Y", strtotime($row['DateFin']));
        $requests[] = $row;
    }

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

$conn->close();
?>
