<?php
include 'config/connexion.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = intval($_POST['id']);
    $status = intval($_POST['status']); // New desired status

    // Fetch current role & status
    $stmtInfo = $conn->prepare("SELECT user_role, status FROM users_table WHERE id=? LIMIT 1");
    $stmtInfo->bind_param("i", $id);
    $stmtInfo->execute();
    $resInfo = $stmtInfo->get_result();
    $rowInfo = $resInfo->fetch_assoc();
    $stmtInfo->close();
    if(!$rowInfo){ echo 'error'; exit; }

    $role = $rowInfo['user_role'];
    $currentStatus = (int)$rowInfo['status'];

    // Prevent deactivation of the last Super admin
    if(strcasecmp($role,'Super admin')===0 && $status === 0){
        $cnt = $conn->query("SELECT COUNT(*) AS c FROM users_table WHERE user_role='Super admin' AND status=1");
        $rowCnt = $cnt? $cnt->fetch_assoc():null;
        $activeSuperAdmins = $rowCnt? (int)$rowCnt['c']:0;
        // If this is the only active Super admin, block
        if($activeSuperAdmins <= 1){
            echo 'forbidden';
            exit;
        }
    }

    // Proceed with update
    $stmt = $conn->prepare("UPDATE users_table SET status = ? WHERE id = ?");
    $stmt->bind_param("ii", $status, $id);
    if ($stmt->execute()) {
        echo 'success';
    } else {
        echo 'error';
    }
    $stmt->close();
}
?>
