<?php
// File: delete_admin.php  →  HARD DELETE (permanent removal)

header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

include_once __DIR__ . "/config.php";

$data = json_decode(file_get_contents("php://input"), true);

if (!$data || !isset($data['admin_id'])) {
    echo json_encode(["success" => false, "message" => "admin_id is required"]);
    exit;
}

$admin_id = (int)$data['admin_id'];

if ($admin_id <= 0) {
    echo json_encode(["success" => false, "message" => "Invalid admin_id"]);
    exit;
}

try {
    $conn->begin_transaction();

    // 1. Prevent deleting the very first admin (super admin protection)
    $first = $conn->query("SELECT client_index FROM adminlogins ORDER BY client_index ASC LIMIT 1")->fetch_assoc();
    if ($first && $admin_id == $first['client_index']) {
        $conn->rollback();
        echo json_encode([
            "success" => false,
            "message" => "Cannot delete the primary super admin account"
        ]);
        exit;
    }

    // 2. Get username before deleting (for response message)
    $get = $conn->prepare("SELECT username FROM adminlogins WHERE client_index = ?");
    $get->bind_param("i", $admin_id);
    $get->execute();
    $result = $get->get_result();

    if ($result->num_rows === 0) {
        $conn->rollback();
        echo json_encode(["success" => false, "message" => "Admin not found"]);
        exit;
    }

    $admin = $result->fetch_assoc();
    $username = $admin['username'];

    // 3. HARD DELETE → completely remove from database
    $delete = $conn->prepare("DELETE FROM adminlogins WHERE client_index = ?");
    $delete->bind_param("i", $admin_id);

    if (!$delete->execute() || $delete->affected_rows === 0) {
        $conn->rollback();
        echo json_encode(["success" => false, "message" => "Failed to delete admin"]);
        exit;
    }

    $conn->commit();

    echo json_encode([
        "success" => true,
        "message" => "Admin '$username' has been permanently deleted",
        "admin_id" => $admin_id
    ]);

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