<?php
// Récupération des membres de l'équipe pour un manager AD
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");

// Debug erreurs
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 getTeamMembersAD: " . $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("getTeamMembersAD - Manager ID: $managerId");

try {
    // 🔹 1. Récupérer le ServiceId du manager
    $queryManagerService = "SELECT ServiceId FROM CollaborateurAD 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("getTeamMembersAD - ServiceId du manager: $serviceId");
        
        // 🔹 2. Récupérer tous les collaborateurs du même service (sauf le manager)
        $queryTeam = "
            SELECT 
                c.id,
                c.nom,
                c.prenom,
                c.email,
                c.role,
             
                s.Nom as service_name
            FROM CollaborateurAD c
            JOIN Services s ON c.ServiceId = s.Id
            WHERE c.ServiceId = ? AND c.id != ? 
            ORDER BY c.prenom, c.nom
        ";
        
        $stmtTeam = $conn->prepare($queryTeam);
        $stmtTeam->bind_param("ii", $serviceId, $managerId);
        $stmtTeam->execute();
        $resultTeam = $stmtTeam->get_result();
        
        $teamMembers = [];
        while ($row = $resultTeam->fetch_assoc()) {
            $teamMembers[] = [
                'id' => (int)$row['id'],
                'nom' => $row['nom'],
                'prenom' => $row['prenom'],
                'email' => $row['email'],
                'role' => $row['role'],
            
                'service_name' => $row['service_name']
            ];
        }
        
        error_log("getTeamMembersAD - Membres trouvés: " . count($teamMembers));
        
        echo json_encode([
            "success" => true,
            "message" => "Équipe récupérée avec succès",
            "team_members" => $teamMembers,
            "service_id" => $serviceId
        ]);
        
        $stmtTeam->close();
    } else {
        error_log("getTeamMembersAD - Manager non trouvé: $managerId");
        echo json_encode([
            "success" => false,
            "message" => "Manager non trouvé"
        ]);
    }
    
    $stmtManager->close();
    
} catch (Exception $e) {
    error_log("Erreur getTeamMembersAD: " . $e->getMessage());
    echo json_encode([
        "success" => false,
        "message" => "Erreur lors de la récupération de l'équipe: " . $e->getMessage()
    ]);
}

$conn->close();
?>
