<?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 que le validateur existe dans CollaborateurAD
    $stmt = $conn->prepare("SELECT Id, prenom, nom FROM CollaborateurAD WHERE Id = ?");
    $stmt->bind_param("i", $validatorId);
    $stmt->execute();
    $validator = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if (!$validator) {
        throw new Exception("Validateur introuvable dans CollaborateurAD");
    }

    // Récupération de la demande
    $queryCheck = "
        SELECT dc.Id, dc.CollaborateurADId, dc.TypeCongeId, dc.DateDebut, dc.DateFin, dc.NombreJours,
               ca.prenom as CADPrenom, ca.nom as CADNom,
               tc.Nom as TypeNom
        FROM DemandeConge dc
        JOIN TypeConge tc ON dc.TypeCongeId = tc.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();
    $requestRow = $stmtCheck->get_result()->fetch_assoc();
    $stmtCheck->close();

    if (!$requestRow) {
        throw new Exception("Demande non trouvée ou déjà traitée");
    }

    $collaborateurId = $requestRow['CollaborateurADId'];
    $typeCongeId     = $requestRow['TypeCongeId'];
    $nombreJours     = $requestRow['NombreJours'];
    $employeeName    = $requestRow['CADPrenom']." ".$requestRow['CADNom'];
    $typeNom         = $requestRow['TypeNom'];

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

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

    // 🔹 Déduction solde (pas maladie)
    if ($action === 'approve' && $typeNom !== 'Congé maladie' && $collaborateurId) {
        $year = date("Y");
        $queryDeduct = "
            UPDATE CompteurConges
            SET Solde = GREATEST(0, Solde - ?)
            WHERE CollaborateurADId = ? AND TypeCongeId = ? AND Annee = ?
        ";
        $stmtDeduct = $conn->prepare($queryDeduct);
        $stmtDeduct->bind_param("diii", $nombreJours, $collaborateurId, $typeCongeId, $year);
        $stmtDeduct->execute();
        $stmtDeduct->close();
    }

    // 🔹 Notification
    $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';

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

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

    $queryHistory = "
        INSERT INTO HistoriqueActions (CollaborateurADId, Action, Details, DemandeCongeId)
        VALUES (?, ?, ?, ?)
    ";
    $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();
