<?php
// Récupération des demandes en attente pour un manager
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 getPendingRequests: " . $conn->connect_error);
    echo json_encode(["success" => false, "message" => "Erreur de connexion à la base de données"]);
    exit();
}

$managerId = $_GET['manager_id'] ?? null;

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

error_log("getPendingRequests - Manager ID: $managerId");

// Fonction pour calculer les 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 {
    // Récupérer le service du manager
    $queryManagerService = "SELECT ServiceId FROM Users WHERE ID = ?";
    $stmtManager = $conn->prepare($queryManagerService);
    $stmtManager->bind_param("i", $managerId);
    $stmtManager->execute();
    $resultManager = $stmtManager->get_result();
    
    if ($managerRow = $resultManager->fetch_assoc()) {
        $serviceId = $managerRow['ServiceId'];
        error_log("getPendingRequests - Service ID du manager: $serviceId");
        
        // Récupérer les demandes en attente (multi-types)
        $queryRequests = "
            SELECT 
                dc.Id,
                dc.DateDebut,
                dc.DateFin,
                dc.Statut,
                dc.DateDemande,
                dc.Commentaire,
                dc.EmployeeId,
                CONCAT(u.Prenom, ' ', u.Nom) as employee_name,
                u.Email as employee_email,
                GROUP_CONCAT(tc.Nom ORDER BY tc.Nom SEPARATOR ', ') as types
            FROM DemandeConge dc
            JOIN Users u ON dc.EmployeeId = u.ID
            JOIN TypeConge tc ON FIND_IN_SET(tc.Id, dc.TypeCongeId)
            WHERE u.ServiceId = ? 
            AND dc.Statut = 'En attente'
            AND u.ID != ?
            GROUP BY 
                dc.Id, dc.DateDebut, dc.DateFin, dc.Statut, dc.DateDemande, 
                dc.Commentaire, dc.EmployeeId, u.Prenom, u.Nom, u.Email
            ORDER BY dc.DateDemande ASC
        ";
        
        $stmtRequests = $conn->prepare($queryRequests);
        $stmtRequests->bind_param("ii", $serviceId, $managerId);
        $stmtRequests->execute();
        $resultRequests = $stmtRequests->get_result();
        
        $requests = [];
        while ($row = $resultRequests->fetch_assoc()) {
            $workingDays = getWorkingDays($row['DateDebut'], $row['DateFin']);
            
            $startDate = new DateTime($row['DateDebut']);
            $endDate = new DateTime($row['DateFin']);
            $submittedDate = new DateTime($row['DateDemande']);
            
            if ($row['DateDebut'] === $row['DateFin']) {
                $dateDisplay = $startDate->format('d/m/Y');
            } else {
                $dateDisplay = $startDate->format('d/m/Y') . ' - ' . $endDate->format('d/m/Y');
            }
            
            $requests[] = [
                'id' => (int)$row['Id'],
                'employee_id' => (int)$row['EmployeeId'],
                'employee_name' => $row['employee_name'],
                'employee_email' => $row['employee_email'],
                'type' => $row['types'], // ex: "Congé payé, RTT"
                'start_date' => $row['DateDebut'],
                'end_date' => $row['DateFin'],
                'date_display' => $dateDisplay,
                'days' => $workingDays,
                'status' => $row['Statut'],
                'reason' => $row['Commentaire'] ?: '',
                'submitted_at' => $row['DateDemande'],
                'submitted_display' => $submittedDate->format('d/m/Y')
            ];
        }
        
        error_log("getPendingRequests - Demandes en attente trouvées: " . count($requests));
        
        echo json_encode([
            "success" => true,
            "message" => "Demandes en attente récupérées avec succès",
            "requests" => $requests,
            "service_id" => $serviceId
        ]);
        
        $stmtRequests->close();
    } else {
        error_log("getPendingRequests - Manager non trouvé: $managerId");
        echo json_encode([
            "success" => false,
            "message" => "Manager non trouvé"
        ]);
    }
    
    $stmtManager->close();
    
} catch (Exception $e) {
    error_log("Erreur getPendingRequests: " . $e->getMessage());
    echo json_encode([
        "success" => false,
        "message" => "Erreur lors de la récupération des demandes: " . $e->getMessage()
    ]);
}

$conn->close();
?>
