<?php
require_once __DIR__ . '/../../config/session.php';
requireAdmin();
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../functions/helper.php';
require_once __DIR__ . '/../../functions/csrf.php';

$db = getDB();

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$token = $_GET['token'] ?? '';

if ($id <= 0 || !verifyCSRFToken($token)) {
    setFlash('error', 'Token tidak valid atau permintaan tidak sah.');
    header('Location: ' . BASE_URL . '/admin/users/');
    exit;
}

// Prevent self-delete
if ($id == ($_SESSION['user_id'] ?? 0)) {
    setFlash('error', 'Anda tidak dapat menghapus akun sendiri.');
    header('Location: ' . BASE_URL . '/admin/users/');
    exit;
}

try {
    $stmt = $db->prepare("DELETE FROM users WHERE id = ?");
    $stmt->execute([$id]);
    if ($stmt->rowCount() > 0) {
        setFlash('success', 'User berhasil dihapus.');
    } else {
        setFlash('error', 'User tidak ditemukan.');
    }
} catch (PDOException $e) {
    setFlash('error', 'Gagal menghapus user: ' . $e->getMessage());
}

header('Location: ' . BASE_URL . '/admin/users/');
exit;
