<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit();
}

header("Content-Type: application/json");

$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]));
}

$data = json_decode(file_get_contents('php://input'), true);
$email = $data['email'] ?? '';
$mot_de_passe = $data['mot_de_passe'] ?? '';
$entraUserId = $data['entraUserId'] ?? '';
$userPrincipalName = $data['userPrincipalName'] ?? '';

$headers = getallheaders();
$accessToken = isset($headers['Authorization']) ? str_replace('Bearer ', '', $headers['Authorization']) : '';

// ======================================================
// 1️⃣ Mode Azure AD (avec token + Entra)
// ======================================================
if ($accessToken && $entraUserId) {
    // Vérifier si utilisateur existe déjà dans CollaborateurAD
    $stmt = $conn->prepare("SELECT * FROM CollaborateurAD WHERE entraUserId=? OR email=? LIMIT 1");
    $stmt->bind_param("ss", $entraUserId, $email);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        echo json_encode(["success" => false, "message" => "Utilisateur non autorisé (pas dans l'annuaire)"]);
        exit();
    }
    $user = $result->fetch_assoc();

    // Récupérer groupes de l’utilisateur via Graph
    $ch = curl_init("https://graph.microsoft.com/v1.0/users/$userPrincipalName/memberOf?\$select=id");
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Bearer $accessToken"]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);

    $dataGraph = json_decode($response, true);
    $userGroups = [];
    if (isset($dataGraph['value'])) {
        foreach ($dataGraph['value'] as $g) {
            if (isset($g['id'])) {
                $userGroups[] = $g['id'];
            }
        }
    }

    // Vérifier si au moins un groupe est autorisé
    $res = $conn->query("SELECT Id FROM EntraGroups WHERE IsActive=1");
    $allowedGroups = [];
    while ($row = $res->fetch_assoc()) {
        $allowedGroups[] = $row['Id'];
    }

    $authorized = count(array_intersect($userGroups, $allowedGroups)) > 0;

    if ($authorized) {
        echo json_encode([
            "success" => true,
            "message" => "Connexion réussie via Azure AD",
            "user" => [
                "id" => $user['id'],
                "prenom" => $user['prenom'],
                "nom" => $user['nom'],
                "email" => $user['email'],
                "role" => $user['role'],
                "service" => $user['service']
            ]
        ]);
    } else {
        echo json_encode(["success" => false, "message" => "Utilisateur non autorisé - pas dans un groupe actif"]);
    }

    $conn->close();
    exit();
}

// ======================================================
// 2️⃣ Mode local (login/password → Users)
// ======================================================
if ($email && $mot_de_passe) {
    $query = "
        SELECT 
            u.ID, 
            u.Prenom, 
            u.Nom, 
            u.Email, 
            u.Role, 
            u.ServiceId,
            s.Nom AS ServiceNom
        FROM Users u
        LEFT JOIN Services s ON u.ServiceId = s.Id
        WHERE u.Email = ? AND u.MDP = ?
    ";

    $stmt = $conn->prepare($query);

    if ($stmt === false) {
        die(json_encode(["success" => false, "message" => "Erreur de préparation : " . $conn->error]));
    }

    $stmt->bind_param("ss", $email, $mot_de_passe);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 1) {
        $user = $result->fetch_assoc();

        echo json_encode([
            "success" => true,
            "message" => "Connexion réussie (mode local)",
            "user" => [ 
                "id" => $user['ID'],      
                "prenom" => $user['Prenom'], 
                "nom" => $user['Nom'],      
                "email" => $user['Email'],
                "role" => $user['Role'],
                "service" => $user['ServiceNom'] ?? 'Non défini'
            ]
        ]);
    } else {
        echo json_encode(["success" => false, "message" => "Identifiants incorrects (mode local)"]);
    }

    $stmt->close();
    $conn->close();
    exit();
}

// ======================================================
// 3️⃣ Aucun mode ne correspond
// ======================================================
echo json_encode(["success" => false, "message" => "Aucune méthode de connexion fournie"]);
$conn->close();
?>
