<?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(["authorized" => false, "message" => "Erreur DB: " . $conn->connect_error]));
}

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

// Récupération des données POST
$data = json_decode(file_get_contents("php://input"), true);
$userPrincipalName = $data["userPrincipalName"] ?? "";

// Récupération du token dans les headers
$headers = getallheaders();
$accessToken = isset($headers['Authorization'])
    ? str_replace("Bearer ", "", $headers['Authorization'])
    : "";

if (!$userPrincipalName || !$accessToken) {
    echo json_encode(["authorized" => false, "message" => "Email ou token manquant"]);
    exit;
}

/**
 * Fonction générique pour appeler Graph API
 */
function callGraph($url, $accessToken, $method = "GET", $body = null) {
    $ch = curl_init($url);
    $headers = ["Authorization: Bearer $accessToken"];
    if ($method === "POST") {
        $headers[] = "Content-Type: application/json";
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
    }
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode !== 200) {
        return null;
    }
    return json_decode($response, true);
}

/**
 * Vérifier si utilisateur appartient à un groupe
 */
function isUserInGroup($userId, $groupId, $accessToken) {
    $url = "https://graph.microsoft.com/v1.0/users/$userId/checkMemberGroups";
    $data = json_encode(["groupIds" => [$groupId]]);
    $result = callGraph($url, $accessToken, "POST", $data);

    return $result && isset($result["value"]) && in_array($groupId, $result["value"]);
}

// 🔹 1. Vérifier si utilisateur existe déjà en DB
$stmt = $conn->prepare("SELECT id, entraUserId, prenom, nom, email, service, role FROM CollaborateurAD WHERE email = ? LIMIT 1");
$stmt->bind_param("s", $userPrincipalName);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
$stmt->close();

if ($user) {
    echo json_encode([
        "authorized" => true,
        "role" => $user["role"],
        "groups" => [$user["role"]],
        "localUserId" => (int)$user["id"], // 🔹 ajout important
        "user" => $user
    ]);
    $conn->close();
    exit;
}


// 🔹 2. Sinon → chercher l’utilisateur dans Microsoft Graph
$userGraph = callGraph("https://graph.microsoft.com/v1.0/users/$userPrincipalName?\$select=id,displayName,givenName,surname,mail,department,jobTitle", $accessToken);

if (!$userGraph) {
    echo json_encode([
        "authorized" => false,
        "message" => "Utilisateur introuvable dans Entra ou token invalide"
    ]);
    $conn->close();
    exit;
}

// 🔹 3. Vérifier appartenance au groupe Ensup-Groupe
$isInTargetGroup = isUserInGroup($userGraph["id"], $groupId, $accessToken);

if (!$isInTargetGroup) {
    echo json_encode([
        "authorized" => false,
        "message" => "Utilisateur non autorisé : il n'appartient pas au groupe requis"
    ]);
    $conn->close();
    exit;
}

// 🔹 4. Insérer dans la base si nouveau
$entraUserId = $userGraph["id"];
$prenom = $userGraph["givenName"] ?? "";
$nom = $userGraph["surname"] ?? "";
$email = $userGraph["mail"] ?? $userPrincipalName;
$service = $userGraph["department"] ?? "";
$role = "Collaborateur"; // rôle par défaut

$stmt = $conn->prepare("INSERT INTO CollaborateurAD (entraUserId, prenom, nom, email, service, role) 
                        VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssssss", $entraUserId, $prenom, $nom, $email, $service, $role);
$stmt->execute();
$newUserId = $stmt->insert_id;
$stmt->close();

// 🔹 5. Réponse finale
echo json_encode([
    "authorized" => true,
    "role" => $role,
    "groups" => [$role],
    "localUserId" => (int)$newUserId, // 🔹 ajout important
    "user" => [
        "id" => $newUserId,
        "entraUserId" => $entraUserId,
        "prenom" => $prenom,
        "nom" => $nom,
        "email" => $email,
        "service" => $service,
        "role" => $role
    ]
]);


$conn->close();
?>
