<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

// --- Connexion DB ---
$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) {
    die(json_encode(["success" => false, "message" => "Erreur DB: " . $conn->connect_error]));
}

$tenantId = "9840a2a0-6ae1-4688-b03d-d2ec291be0f9"; 
$clientId = "4bb4cc24-bac3-427c-b02c-5d14fc67b561"; 
$clientSecret = "ViC8Q~n4F5YweE18wjS0kfhp3kHh6LB2gZ76_b4R"; 
$scope = "https://graph.microsoft.com/.default"; 

$url = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token";
$data = [
    "grant_type" => "client_credentials",
    "client_id" => $clientId,
    "client_secret" => $clientSecret,
    "scope" => $scope
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);

$tokenData = json_decode($result, true);
$accessToken = $tokenData["access_token"] ?? "";
if (!$accessToken) {
    die(json_encode(["success" => false, "message" => "Impossible d'obtenir un token Microsoft", "details" => $tokenData]));
}

// --- ID du groupe cible (Ensup-Groupe) ---
$groupId = "c1ea877c-6bca-4f47-bfad-f223640813a0"; 

// --- Récupérer infos du groupe ---
$urlGroup = "https://graph.microsoft.com/v1.0/groups/$groupId?\$select=id,displayName,description,mail,createdDateTime";
$ch = curl_init($urlGroup);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Bearer $accessToken"]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$respGroup = curl_exec($ch);
curl_close($ch);

$group = json_decode($respGroup, true);
if (!isset($group["id"])) {
    die(json_encode(["success" => false, "message" => "Impossible de récupérer le groupe Ensup-Groupe"]));
}

$displayName = $group["displayName"] ?? "";

// --- Récupérer les membres du groupe ---
$urlMembers = "https://graph.microsoft.com/v1.0/groups/$groupId/members?\$select=id,givenName,surname,mail,department,jobTitle";
$ch = curl_init($urlMembers);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Bearer $accessToken"]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$respMembers = curl_exec($ch);
curl_close($ch);

$members = json_decode($respMembers, true)["value"] ?? [];

$usersInserted = 0;
foreach ($members as $m) {
    $entraUserId = $m["id"];
    $prenom = $m["givenName"] ?? "";
    $nom = $m["surname"] ?? "";
    $email = $m["mail"] ?? "";
    $service = $m["department"] ?? "";

    if (!$email) continue;

    // Insertion ou mise à jour de l’utilisateur
    $stmt = $conn->prepare("INSERT INTO CollaborateurAD (entraUserId, prenom, nom, email, service, role) 
                            VALUES (?, ?, ?, ?, ?, ?)
                            ON DUPLICATE KEY UPDATE prenom=?, nom=?, email=?, service=?");
    if ($stmt) {
        $role = "Collaborateur"; // attribué uniquement si nouvel utilisateur
        $stmt->bind_param("ssssssssss", 
            $entraUserId, $prenom, $nom, $email, $service, $role,
            $prenom, $nom, $email, $service
        );
        $stmt->execute();
        $usersInserted++;
    }
}

// --- Réponse finale ---
echo json_encode([
    "success" => true,
    "message" => "Synchronisation terminée",
    "groupe_sync" => $displayName,
    "users_sync" => $usersInserted
]);

$conn->close();
?>
