<?php
// Validation/Refus d'une demande de congé par un manager
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

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

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

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

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

if (!isset($data['request_id'], $data['action'], $data['validator_id'])) {
    echo json_encode(["success" => false, "message" => "Données manquantes"]);
    exit();
}

$requestId   = (int)$data['request_id'];
$action      = $data['action']; // "approve" | "reject"
$validatorId = (int)$data['validator_id'];
$comment     = $data['comment'] ?? '';

try {
    $conn->begin_transaction();

    // Vérifier si validateur est Users ou CollaborateurAD
    $isUserValidator = false;
    $stmt = $conn->prepare("SELECT ID FROM Users WHERE ID = ?");
    $stmt->bind_param("i", $validatorId);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($res->fetch_assoc()) {
        $isUserValidator = true;
    } else {
        $stmt = $conn->prepare("SELECT Id FROM CollaborateurAD WHERE Id = ?");
        $stmt->bind_param("i", $validatorId);
        $stmt->execute();
        $res = $stmt->get_result();
        if (!$res->fetch_assoc()) {
            throw new Exception("Validateur introuvable dans Users ou CollaborateurAD");
        }
    }
    $stmt->close();

    // Récupération demande
    $queryCheck = "
        SELECT dc.Id, dc.EmployeeId, dc.CollaborateurADId, dc.TypeCongeId, dc.DateDebut, dc.DateFin, dc.NombreJours,
               u.Nom as UserNom, u.Prenom as UserPrenom,
               ca.nom as CADNom, ca.prenom as CADPrenom,
               tc.Nom as TypeNom
        FROM DemandeConge dc
        JOIN TypeConge tc ON dc.TypeCongeId = tc.Id
        LEFT JOIN Users u ON dc.EmployeeId = u.ID
        LEFT JOIN CollaborateurAD ca ON dc.CollaborateurADId = ca.Id
        WHERE dc.Id = ? AND dc.Statut = 'En attente'
    ";
    $stmtCheck = $conn->prepare($queryCheck);
    $stmtCheck->bind_param("i", $requestId);
    $stmtCheck->execute();
    $resultCheck = $stmtCheck->get_result();

    if (!($requestRow = $resultCheck->fetch_assoc())) {
        throw new Exception("Demande non trouvée ou déjà traitée");
    }
    $stmtCheck->close();

    $employeeId      = $requestRow['EmployeeId'];
    $collaborateurId = $requestRow['CollaborateurADId'];
    $typeCongeId     = $requestRow['TypeCongeId'];
    $nombreJours     = $requestRow['NombreJours'];
    $employeeName    = $employeeId
                        ? $requestRow['UserPrenom']." ".$requestRow['UserNom']
                        : $requestRow['CADPrenom']." ".$requestRow['CADNom'];
    $typeNom         = $requestRow['TypeNom'];

    $newStatus = ($action === 'approve') ? 'Validée' : 'Refusée';

    // 🔹 Mise à jour DemandeConge
    if ($isUserValidator) {
        $queryUpdate = "
            UPDATE DemandeConge
            SET Statut = ?, 
                ValidateurId = ?, 
                ValidateurADId = NULL,
                DateValidation = NOW(),
                CommentaireValidation = ?
            WHERE Id = ?
        ";
    } else {
        $queryUpdate = "
            UPDATE DemandeConge
            SET Statut = ?, 
                ValidateurId = NULL, 
                ValidateurADId = ?,
                DateValidation = NOW(),
                CommentaireValidation = ?
            WHERE Id = ?
        ";
    }
    $stmtUpdate = $conn->prepare($queryUpdate);
    $stmtUpdate->bind_param("sisi", $newStatus, $validatorId, $comment, $requestId);
    $stmtUpdate->execute();
    $stmtUpdate->close();

    // 🔹 Déduction solde (seulement Users, pas AD, hors maladie)
    if ($action === 'approve' && $typeNom !== 'Congé maladie' && $employeeId) {
        $currentDate = new DateTime();
        $year = ($typeNom === 'Congé payé' && (int)$currentDate->format('m') < 6)
            ? $currentDate->format('Y') - 1
            : $currentDate->format('Y');

        $queryDeduct = "
            UPDATE CompteurConges
            SET Solde = GREATEST(0, Solde - ?)
            WHERE EmployeeId = ? AND TypeCongeId = ? AND Annee = ?
        ";
        $stmtDeduct = $conn->prepare($queryDeduct);
        $stmtDeduct->bind_param("diii", $nombreJours, $employeeId, $typeCongeId, $year);
        $stmtDeduct->execute();
        $stmtDeduct->close();
    }

    // 🔹 Notification (User ou CollaborateurAD)
    $notificationTitle = ($action === 'approve') ? 'Demande approuvée' : 'Demande refusée';
    $notificationMessage = "Votre demande de $typeNom a été " . (($action === 'approve') ? "approuvée" : "refusée");
    if ($comment) $notificationMessage .= " (Commentaire: $comment)";
    $notifType = ($action === 'approve') ? 'Success' : 'Error';

    if ($employeeId) {
        $queryNotif = "
            INSERT INTO Notifications (UserId, CollaborateurADId, Titre, Message, Type, DemandeCongeId)
            VALUES (?, NULL, ?, ?, ?, ?)
        ";
        $stmtNotif = $conn->prepare($queryNotif);
        $stmtNotif->bind_param("isssi", $employeeId, $notificationTitle, $notificationMessage, $notifType, $requestId);
        $stmtNotif->execute();
        $stmtNotif->close();
    } elseif ($collaborateurId) {
        $queryNotif = "
            INSERT INTO Notifications (UserId, CollaborateurADId, Titre, Message, Type, DemandeCongeId)
            VALUES (NULL, ?, ?, ?, ?, ?)
        ";
        $stmtNotif = $conn->prepare($queryNotif);
        $stmtNotif->bind_param("isssi", $collaborateurId, $notificationTitle, $notificationMessage, $notifType, $requestId);
        $stmtNotif->execute();
        $stmtNotif->close();
    }

    // 🔹 Historique (User ou CollaborateurAD)
    $actionText = ($action === 'approve') ? 'Validation congé' : 'Refus congé';
    $actionDetails = "$actionText $employeeName ($typeNom)";
    if ($comment) $actionDetails .= " - $comment";

    if ($isUserValidator) {
        $queryHistory = "
            INSERT INTO HistoriqueActions (UserId, CollaborateurADId, Action, Details, DemandeCongeId)
            VALUES (?, NULL, ?, ?, ?)
        ";
        $stmtHistory = $conn->prepare($queryHistory);
        $stmtHistory->bind_param("issi", $validatorId, $actionText, $actionDetails, $requestId);
    } else {
        $queryHistory = "
            INSERT INTO HistoriqueActions (UserId, CollaborateurADId, Action, Details, DemandeCongeId)
            VALUES (NULL, ?, ?, ?, ?)
        ";
        $stmtHistory = $conn->prepare($queryHistory);
        $stmtHistory->bind_param("issi", $validatorId, $actionText, $actionDetails, $requestId);
    }
    $stmtHistory->execute();
    $stmtHistory->close();

    $conn->commit();

    echo json_encode([
        "success" => true,
        "message" => "Demande " . (($action === 'approve') ? 'approuvée' : 'refusée'),
        "new_status" => $newStatus
    ]);

} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(["success" => false, "message" => $e->getMessage()]);
}

$conn->close();
?>
