<?php
// Récupération des membres de l'équipe 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 getTeamMembers: " . $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("getTeamMembers - Manager ID: $managerId");

try {
    // D'abord, 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("getTeamMembers - Service ID du manager: $serviceId");
        
        // Récupérer tous les membres du même service (sauf le manager lui-même)
        $queryTeam = "
            SELECT 
                u.ID as id,
                u.Nom as nom,
                u.Prenom as prenom,
                u.Email as email,
                u.Role as role,
                u.DateEmbauche as date_embauche,
                s.Nom as service_name
            FROM Users u
            JOIN Services s ON u.ServiceId = s.Id
            WHERE u.ServiceId = ? AND u.ID != ? AND u.Actif = 1
            ORDER BY u.Prenom, u.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'],
                'date_embauche' => $row['date_embauche'],
                'service_name' => $row['service_name']
            ];
        }
        
        error_log("getTeamMembers - 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("getTeamMembers - Manager non trouvé: $managerId");
        echo json_encode([
            "success" => false,
            "message" => "Manager non trouvé"
        ]);
    }
    
    $stmtManager->close();
    
} catch (Exception $e) {
    error_log("Erreur getTeamMembers: " . $e->getMessage());
    echo json_encode([
        "success" => false,
        "message" => "Erreur lors de la récupération de l'équipe: " . $e->getMessage()
    ]);
}

$conn->close();
?>