<?php
// Récupération des congés de l'équipe pour affichage dans le calendrier
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");

// Log des erreurs pour debug
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$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 getTeamLeaves: " . $conn->connect_error);
    echo json_encode(["success" => false, "message" => "Erreur de connexion à la base de données"]);
    exit();
}

$userId = $_GET['user_id'] ?? null;

if ($userId === null) {
    echo json_encode(["success" => false, "message" => "ID utilisateur manquant"]);
    exit();
}

error_log("getTeamLeaves - User ID: $userId");

try {
    // Récupérer le service de l'utilisateur
    $queryUserService = "SELECT ServiceId FROM Users WHERE ID = ?";
    $stmtUser = $conn->prepare($queryUserService);
    $stmtUser->bind_param("i", $userId);
    $stmtUser->execute();
    $resultUser = $stmtUser->get_result();
    
    if ($userRow = $resultUser->fetch_assoc()) {
        $serviceId = $userRow['ServiceId'];
        error_log("getTeamLeaves - Service ID: $serviceId");
        
        // Récupérer les congés validés de l'équipe (même service)
        $queryLeaves = "
            SELECT 
                dc.DateDebut as start_date,
                dc.DateFin as end_date,
                CONCAT(u.Prenom, ' ', u.Nom) as employee_name,
                tc.Nom as type,
                tc.CouleurHex as color
            FROM DemandeConge dc
            JOIN Users u ON dc.EmployeeId = u.ID
            JOIN TypeConge tc ON dc.TypeCongeId = tc.Id
            WHERE u.ServiceId = ? 
            AND dc.Statut = 'Validée'
            AND dc.DateFin >= CURDATE() - INTERVAL 30 DAY
            ORDER BY dc.DateDebut ASC
        ";
        
        $stmtLeaves = $conn->prepare($queryLeaves);
        $stmtLeaves->bind_param("i", $serviceId);
        $stmtLeaves->execute();
        $resultLeaves = $stmtLeaves->get_result();
        
        $leaves = [];
        while ($row = $resultLeaves->fetch_assoc()) {
            $leaves[] = [
                'start_date' => $row['start_date'],
                'end_date' => $row['end_date'],
                'employee_name' => $row['employee_name'],
                'type' => $row['type'],
                'color' => $row['color'] ?? '#3B82F6'
            ];
        }
        
        error_log("getTeamLeaves - Congés trouvés: " . count($leaves));
        
        echo json_encode([
            "success" => true,
            "message" => "Congés de l'équipe récupérés avec succès",
            "leaves" => $leaves,
            "service_id" => $serviceId
        ]);
        
        $stmtLeaves->close();
    } else {
        error_log("getTeamLeaves - Utilisateur non trouvé: $userId");
        echo json_encode([
            "success" => false,
            "message" => "Utilisateur non trouvé"
        ]);
    }
    
    $stmtUser->close();
    
} catch (Exception $e) {
    error_log("Erreur getTeamLeaves: " . $e->getMessage());
    echo json_encode([
        "success" => false,
        "message" => "Erreur lors de la récupération des congés: " . $e->getMessage()
    ]);
}

$conn->close();
?>