<?php
include('session_handler.php');

if (!checkRole('superadmin')) {
    header('Location: unauthorized.php');
    exit;
}

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

    // 🔒 Semak role user yang nak dipadam
    $check = $conn->prepare("SELECT role FROM users WHERE id = ?");
    $check->bind_param("s", $id);
    $check->execute();
    $result = $check->get_result();

    if ($result && $row = $result->fetch_assoc()) {
        if ($row['role'] === 'superadmin') {
            // Jika user tersebut ialah superadmin, jangan padam
            echo "<script>alert('Tidak dibenarkan memadam Superadmin!'); window.location.href='view_user.php';</script>";
            exit;
        }
    } else {
        echo "<script>alert('Pengguna tidak ditemui.'); window.location.href='view_user.php';</script>";
        exit;
    }

    // ✅ Teruskan padam jika bukan superadmin
    $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
    $stmt->bind_param("s", $id);

    if ($stmt->execute()) {
        echo "<script>alert('Pengguna berjaya dipadam.'); window.location.href='view_user.php';</script>";
    } else {
        echo "<script>alert('Gagal memadam pengguna.'); window.location.href='view_user.php';</script>";
    }

    $stmt->close();
    $check->close();
} else {
    echo "<script>alert('ID tidak sah.'); window.location.href='view_user.php';</script>";
}
?>