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

$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 de connexion à la base de données"]);
    exit();
}

// On récupère le rôle directement depuis la requête GET pour la logique PHP
$userId = $_GET['user_id'] ?? null;
$role   = strtolower($_GET['role'] ?? 'collaborateur'); 

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

try {
    // 🔹 Infos utilisateur
    $queryUser = "
        SELECT ca.ServiceId, sa.CampusId, sa.SocieteId,
               s.Nom as service_nom, c.Nom as campus_nom, so.Nom as societe_nom
        FROM CollaborateurAD ca
        JOIN ServiceAffectation sa ON sa.ServiceId = ca.ServiceId
        JOIN Services s ON ca.ServiceId = s.Id
        JOIN Campus c ON sa.CampusId = c.Id
        JOIN Societe so ON sa.SocieteId = so.Id
        WHERE ca.id = ?
        LIMIT 1
    ";
    $stmtUser = $conn->prepare($queryUser);
    $stmtUser->bind_param("i", $userId);
    $stmtUser->execute();
    $resultUser = $stmtUser->get_result();

    if (!$userRow = $resultUser->fetch_assoc()) {
        echo json_encode(["success" => false, "message" => "Collaborateur non trouvé"]);
        exit();
    }

    $serviceId  = $userRow['ServiceId'];
    $campusId   = $userRow['CampusId'];
    $societeId  = $userRow['SocieteId'];

    // -------------------------
    // 🔹 Construire la requête selon le rôle
    // -------------------------
    switch ($role) {
        case 'president':
        case 'rh':
            $queryLeaves = "
                SELECT 
                    DATE_FORMAT(dc.DateDebut, '%Y-%m-%d') as start_date,
                    DATE_FORMAT(dc.DateFin, '%Y-%m-%d') as end_date,
                    CONCAT(ca.prenom, ' ', ca.nom) as employee_name,
                    tc.Nom as type,
                    tc.CouleurHex as color,
                    s.Nom as service_nom,
                    c.Nom as campus_nom,
                    so.Nom as societe_nom
                FROM DemandeConge dc
                JOIN CollaborateurAD ca ON dc.CollaborateurADId = ca.id
                JOIN TypeConge tc ON dc.TypeCongeId = tc.Id
                JOIN ServiceAffectation sa ON sa.ServiceId = ca.ServiceId
                JOIN Services s ON sa.ServiceId = s.Id
                JOIN Campus c ON sa.CampusId = c.Id
                JOIN Societe so ON sa.SocieteId = so.Id -- CORRIGÉ ICI
                WHERE dc.Statut = 'Validée'
                ORDER BY c.Nom, so.Nom, s.Nom, dc.DateDebut ASC
            ";
            $stmtLeaves = $conn->prepare($queryLeaves);
            break;

        case 'directeur de campus':
            $queryLeaves = "
                SELECT 
                    DATE_FORMAT(dc.DateDebut, '%Y-%m-%d') as start_date,
                    DATE_FORMAT(dc.DateFin, '%Y-%m-%d') as end_date,
                    CONCAT(ca.prenom, ' ', ca.nom) as employee_name,
                    tc.Nom as type,
                    tc.CouleurHex as color,
                    s.Nom as service_nom,
                    so.Nom as societe_nom,
                    c.Nom as campus_nom
                FROM DemandeConge dc
                JOIN CollaborateurAD ca ON dc.CollaborateurADId = ca.id
                JOIN TypeConge tc ON dc.TypeCongeId = tc.Id
                JOIN ServiceAffectation sa ON sa.ServiceId = ca.ServiceId
                JOIN Services s ON sa.ServiceId = s.Id
                JOIN Societe so ON sa.SocieteId = so.Id -- CORRIGÉ ICI
                JOIN Campus c ON sa.CampusId = c.Id
                WHERE sa.CampusId = ?
                  AND dc.Statut = 'Validée'
                ORDER BY so.Nom, s.Nom, dc.DateDebut ASC
            ";
            $stmtLeaves = $conn->prepare($queryLeaves);
            $stmtLeaves->bind_param("i", $campusId);
            break;

        case 'validateur':
        case 'collaborateur':
        default:
            $queryLeaves = "
                SELECT 
                    DATE_FORMAT(dc.DateDebut, '%Y-%m-%d') as start_date,
                    DATE_FORMAT(dc.DateFin, '%Y-%m-%d') as end_date,
                    CONCAT(ca.prenom, ' ', ca.nom) as employee_name,
                    tc.Nom as type,
                    tc.CouleurHex as color,
                    s.Nom as service_nom,
                    c.Nom as campus_nom,
                    so.Nom as societe_nom
                FROM DemandeConge dc
                JOIN CollaborateurAD ca ON dc.CollaborateurADId = ca.id
                JOIN TypeConge tc ON dc.TypeCongeId = tc.Id
                JOIN ServiceAffectation sa ON sa.ServiceId = ca.ServiceId
                JOIN Services s ON sa.ServiceId = s.Id
                JOIN Campus c ON sa.CampusId = c.Id
                JOIN Societe so ON sa.SocieteId = so.Id -- CORRIGÉ ICI
                WHERE ca.ServiceId = ?
                  AND sa.CampusId = ?
                  AND dc.Statut = 'Validée'
                  AND dc.DateFin >= CURDATE() - INTERVAL 30 DAY
                ORDER BY dc.DateDebut ASC
            ";
            $stmtLeaves = $conn->prepare($queryLeaves);
            $stmtLeaves->bind_param("ii", $serviceId, $campusId);
    }

    $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',
            'service_nom'   => $row['service_nom'],
            'campus_nom'    => $row['campus_nom'] ?? null,
            'societe_nom'   => $row['societe_nom'] ?? null
        ];
    }

    // -------------------------
    // 🔹 Construire les filtres dynamiques
    // -------------------------
    $filters = [];

    if (in_array($role, ['collaborateur', 'validateur'])) {
        $queryEmployees = "
            SELECT CONCAT(ca.prenom, ' ', ca.nom) as employee_name
            FROM CollaborateurAD ca
            JOIN ServiceAffectation sa ON sa.ServiceId = ca.ServiceId
            WHERE ca.ServiceId = ?
              AND sa.CampusId = ?
            ORDER BY ca.prenom, ca.nom
        ";
        $stmtEmployees = $conn->prepare($queryEmployees);
        $stmtEmployees->bind_param("ii", $serviceId, $campusId);
        $stmtEmployees->execute();
        $resultEmployees = $stmtEmployees->get_result();

        $employees = [];
        while ($row = $resultEmployees->fetch_assoc()) {
            $employees[] = $row['employee_name'];
        }
        $filters['employees'] = $employees;
        $stmtEmployees->close();

    } elseif ($role === 'directeur de campus') {
           
    $filters['societes'] = [];
    $filters['services'] = [];
        $result = $conn->query("SELECT DISTINCT Nom as societe_nom FROM Societe ORDER BY societe_nom");
    while($row = $result->fetch_assoc()) $filters['societes'][] = $row['societe_nom'];

    $result = $conn->query("SELECT DISTINCT Nom as service_nom FROM Services ORDER BY service_nom");
    while($row = $result->fetch_assoc()) $filters['services'][] = $row['service_nom'];


    }  elseif (in_array($role, ['president', 'rh'])) {
    // 🔹 Récupérer tous les campus, sociétés, services de manière unique
    $filters['campus'] = [];
    $filters['societes'] = [];
    $filters['services'] = [];

    $result = $conn->query("SELECT DISTINCT Nom as campus_nom FROM Campus ORDER BY campus_nom");
    while($row = $result->fetch_assoc()) $filters['campus'][] = $row['campus_nom'];

    $result = $conn->query("SELECT DISTINCT Nom as societe_nom FROM Societe ORDER BY societe_nom");
    while($row = $result->fetch_assoc()) $filters['societes'][] = $row['societe_nom'];

    $result = $conn->query("SELECT DISTINCT Nom as service_nom FROM Services ORDER BY service_nom");
    while($row = $result->fetch_assoc()) $filters['services'][] = $row['service_nom'];
}

    echo json_encode([
        "success" => true,
        "role"    => $role,
        "leaves"  => $leaves,
        "filters" => $filters
    ]);

    $stmtLeaves->close();
    $stmtUser->close();

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

$conn->close();
?>