<?php
// Include database connection
include 'config/connexion.php';

// Check if the request method is POST and the ID is provided
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id'])) {
    $userId = intval($_POST['id']);

    // Check role of target user
    $stmtRole = $conn->prepare("SELECT user_role FROM users_table WHERE id=? LIMIT 1");
    $stmtRole->bind_param("i", $userId);
    $stmtRole->execute();
    $resRole = $stmtRole->get_result();
    $roleRow = $resRole->fetch_assoc();
    $stmtRole->close();
    if(!$roleRow){ echo 'error'; exit; }
    $targetRole = $roleRow['user_role'];
    if(strcasecmp($targetRole,'Super admin')===0){
        // Count super admins
        $cnt = $conn->query("SELECT COUNT(*) AS c FROM users_table WHERE user_role='Super admin'");
        $rowCnt = $cnt? $cnt->fetch_assoc():null;
        $totalSupers = $rowCnt? (int)$rowCnt['c']:0;
        if($totalSupers <= 1){ echo 'forbidden'; exit; }
    }
    // Retrieve email & compagnie_ref before deletion for central sync
    $userEmail = null; $compagnieRef = $_SESSION['compagnie_ref'] ?? null;
    try {
        $stmtInfo = $conn->prepare("SELECT user_email FROM users_table WHERE id=? LIMIT 1");
        $stmtInfo->bind_param("i", $userId);
        $stmtInfo->execute();
        $resInfo = $stmtInfo->get_result();
        if($rowI=$resInfo->fetch_assoc()) $userEmail = $rowI['user_email'];
        $stmtInfo->close();
    } catch(Throwable $e) { }

    $stmt = $conn->prepare("DELETE FROM users_table WHERE id = ?");
    $stmt->bind_param("i", $userId);
    $okLocal = $stmt->execute();
    $stmt->close();

    if($okLocal){
        // Attempt central deletion
        if($compagnieRef && $userEmail){
            try {
                if(!isset($gc_pdo)) { @require_once __DIR__.'/gestion_compagnies/config/connexion.php'; }
                if(isset($gc_pdo)){
                    $delC = $gc_pdo->prepare('DELETE FROM users_compagnie WHERE compagnie_ref=? AND user_email=? LIMIT 1');
                    $delC->execute([$compagnieRef,$userEmail]);
                }
            } catch(Throwable $eC) { /* silencieux */ }
        }
        echo 'success';
    } else {
        echo 'error';
    }
    // Connection is managed globally; do not close it here.
} else {
    echo 'invalid';
}
?>
