<?php
ob_clean();
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: http://localhost:5173");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

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

// Debug
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Connexion DB
$host = "192.168.0.4"; 
$dbname = "DemandeConge"; 
$username = "wpuser"; 
$password = "-2b/)ru5/Bi8P[7_";

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo json_encode(["success"=>false,"message"=>"Erreur DB: ".$e->getMessage()]);
    exit;
}

// Lecture JSON brut
$input = file_get_contents('php://input');
$data = json_decode($input, true);

// 🔎 Debug pour vérifier ce qui arrive
error_log("📥 Payload reçu : " . print_r($data, true));

if (!$data) {
    echo json_encode(["success"=>false,"message"=>"JSON invalide","raw"=>$input]);
    exit;
}

// Vérification des champs obligatoires
$required = ['DateDebut','DateFin','Repartition','NombreJours','Email','Nom'];
foreach ($required as $f) {
    if (!array_key_exists($f, $data)) {
        echo json_encode([
            "success"=>false,
            "message"=>"Donnée manquante : $f",
            "debug"=>$data
        ]);
        exit;
    }
}

$dateDebut   = $data['DateDebut'];
$dateFin     = $data['DateFin'];
$commentaire = $data['Commentaire'] ?? '';
$numDays     = (float)$data['NombreJours'];
$userEmail   = $data['Email'];
$userName    = $data['Nom'];
$statut      = 'En attente';
$currentDate = date('Y-m-d H:i:s');

// 🔎 Identifier si c'est un CollaborateurAD ou un User
$stmt = $pdo->prepare("SELECT id FROM CollaborateurAD WHERE email = :email LIMIT 1");
$stmt->execute([':email'=>$userEmail]);
$collabAD = $stmt->fetch(PDO::FETCH_ASSOC);

$isAD = false;
$employeeId = null;
$collaborateurId = null;

if ($collabAD) {
    $isAD = true;
    $collaborateurId = (int)$collabAD['id'];
} else {
    $stmt = $pdo->prepare("SELECT ID FROM Users WHERE Email = :email LIMIT 1");
    $stmt->execute([':email'=>$userEmail]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        echo json_encode(["success"=>false,"message"=>"Aucun collaborateur trouvé pour $userEmail"]);
        exit;
    }
    $employeeId = (int)$user['ID'];
}

// 🔎 Résoudre les IDs des types de congés
$typeIds = [];
foreach ($data['Repartition'] as $rep) {
    $code = $rep['TypeConge'];
    switch ($code) {
        case 'CP': $name = 'Congé payé'; break;
        case 'RTT': $name = 'RTT'; break;
        case 'ABS': $name = 'Congé maladie'; break;
        default:   $name = $code; break;
    }
    $s = $pdo->prepare("SELECT Id FROM TypeConge WHERE Nom = :nom LIMIT 1");
    $s->execute([':nom'=>$name]);
    if ($r = $s->fetch(PDO::FETCH_ASSOC)) {
        $typeIds[] = $r['Id'];
    }
}
if (empty($typeIds)) {
    echo json_encode(["success"=>false,"message"=>"Aucun type de congé valide"]);
    exit;
}
$typeCongeIdCsv = implode(',', $typeIds);

// ✅ Insertion DemandeConge
$sql = "INSERT INTO DemandeConge 
    (EmployeeId, CollaborateurADId, DateDebut, DateFin, TypeCongeId, Statut, DateDemande, Commentaire, Validateur, NombreJours) 
    VALUES (:eid, :cid, :dd, :df, :tc, :st, :cd, :com, :val, :nj)";

$stmt = $pdo->prepare($sql);
$stmt->execute([
    ':eid'=> $isAD ? 0 : $employeeId,
    ':cid'=> $isAD ? $collaborateurId : null,
    ':dd'=>$dateDebut,
    ':df'=>$dateFin,
    ':tc'=>$typeCongeIdCsv,
    ':st'=>$statut,
    ':cd'=>$currentDate,
    ':com'=>$commentaire,
    ':val'=>'',
    ':nj'=>$numDays
]);

$demandeId = $pdo->lastInsertId();

// ✅ Insertion DemandeCongeType
$sql = "INSERT INTO DemandeCongeType (DemandeCongeId, TypeCongeId, NombreJours) VALUES (:did, :tid, :nj)";
$stmt = $pdo->prepare($sql);

foreach ($data['Repartition'] as $rep) {
    $jours = (float)$rep['NombreJours'];
    $code  = $rep['TypeConge'];
    switch ($code) {
        case 'CP': $name = 'Congé payé'; break;
        case 'RTT': $name = 'RTT'; break;
        case 'ABS': $name = 'Congé maladie'; break;
        default:   $name = $code; break;
    }
    $s = $pdo->prepare("SELECT Id FROM TypeConge WHERE Nom = :nom LIMIT 1");
    $s->execute([':nom'=>$name]);
    if ($r = $s->fetch(PDO::FETCH_ASSOC)) {
        $stmt->execute([
            ':did'=>$demandeId,
            ':tid'=>$r['Id'],
            ':nj'=>$jours
        ]);
    }
}

// ✅ Récupérer les validateurs selon hiérarchie
if ($isAD) {
    $stmt = $pdo->prepare("
        SELECT c.email 
        FROM HierarchieValidationAD hv
        JOIN CollaborateurAD c ON hv.SuperieurId = c.id
        WHERE hv.CollaborateurId = :id
    ");
    $stmt->execute([':id'=>$collaborateurId]);
} else {
    $stmt = $pdo->prepare("
        SELECT u.Email 
        FROM HierarchieValidation hv
        JOIN Users u ON hv.SuperieurId = u.ID
        WHERE hv.EmployeId = :id
    ");
    $stmt->execute([':id'=>$employeeId]);
}
$managers = $stmt->fetchAll(PDO::FETCH_COLUMN);

# =============================================================
# 📧 AUTH Microsoft Graph (client_credentials)
# =============================================================
$tenantId = "9840a2a0-6ae1-4688-b03d-d2ec291be0f9"; 
$clientId = "4bb4cc24-bac3-427c-b02c-5d14fc67b561";
$clientSecret = "gvf8Q~545Bafn8yYsgjW~QG_P1lpzaRe6gJNgb2t"; 

$url = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token";

$data = [
    "client_id" => $clientId,
    "scope" => "https://graph.microsoft.com/.default",
    "client_secret" => $clientSecret,
    "grant_type" => "client_credentials"
];

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: application/x-www-form-urlencoded"
]);
$response = curl_exec($ch);
curl_close($ch);

$tokenData = json_decode($response, true);
if (!isset($tokenData['access_token'])) {
    echo json_encode(["success" => false, "message" => "Impossible de générer un token Graph", "debug"=>$tokenData]);
    exit;
}
$accessToken = $tokenData['access_token'];

# =============================================================
# 📧 Fonction envoi mail
# =============================================================
function sendMailGraph($accessToken, $fromEmail, $toEmail, $subject, $bodyHtml) {
    $url = "https://graph.microsoft.com/v1.0/users/$fromEmail/sendMail";

    $mailData = [
        "message" => [
            "subject" => $subject,
            "body" => [
                "contentType" => "HTML",
                "content" => $bodyHtml
            ],
            "toRecipients" => [
                ["emailAddress" => ["address" => $toEmail]]
            ]
        ],
        "saveToSentItems" => "false"
    ];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer $accessToken",
        "Content-Type: application/json"
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($mailData));

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode >= 200 && $httpCode < 300) {
        return true;
    } else {
        error_log("❌ Erreur envoi mail: $response");
        return false;
    }
}

# =============================================================
# 📧 Envoi automatique des emails
# =============================================================
$fromEmail = "noreply@ensup.eu";

# Mail au collaborateur
sendMailGraph(
    $accessToken,
    $fromEmail,
    $userEmail,
    "Confirmation de votre demande de congés",
    "
        Bonjour {$userName},<br/><br/>
        Votre demande du <b>{$dateDebut}</b> au <b>{$dateFin}</b>
        ({$numDays} jour(s)) a bien été enregistrée.<br/>
        Elle est en attente de validation par votre manager.<br/><br/>
        Merci.
    "
);

# Mail aux managers
foreach ($managers as $managerEmail) {
    sendMailGraph(
        $accessToken,
        $fromEmail,
        $managerEmail,
        "Nouvelle demande de congé - {$userName}",
        "
            Bonjour,<br/><br/>
            {$userName} a soumis une demande de congé :<br/>
            - Du <b>{$dateDebut}</b> au <b>{$dateFin}</b> ({$numDays} jour(s))<br/>
            - Commentaire : " . (!empty($commentaire) ? $commentaire : "Aucun") . "<br/><br/>
            Merci de valider cette demande.
        "
    );
}

# ✅ Réponse finale
echo json_encode([
    "success"=>true,
    "message"=>"Demande soumise",
    "request_id"=>$demandeId,
    "managers"=>$managers
]);
