<?php
header("Content-Type: application/json");
require_once '../config/db.php';

$response = ["success" => false, "message" => "Critical error: Process failed."];

if (isset($_GET['id'])) {
    $id = intval($_GET['id']);

    // 1. Security Check: Prevent deleting the last Admin
    $role_check = $conn->query("SELECT role FROM team_grovia WHERE id = $id")->fetch_assoc();
    
    if ($role_check['role'] === 'Admin') {
        $admin_count = $conn->query("SELECT COUNT(*) as total FROM team_grovia WHERE role = 'Admin'")->fetch_assoc()['total'];
        if ($admin_count <= 1) {
            echo json_encode(["success" => false, "message" => "Security Alert: You cannot delete the only remaining Admin account."]);
            exit();
        }
    }

    // 2. Perform Deletion
    $delete = $conn->query("DELETE FROM team_grovia WHERE id = $id");

    if ($delete) {
        $response = [
            "success" => true, 
            "message" => "Staff member removed successfully."
        ];
    } else {
        $response = ["success" => false, "message" => "Database Error: " . $conn->error];
    }
} else {
    $response = ["success" => false, "message" => "Invalid request: No ID provided."];
}

echo json_encode($response);