<?php
header('Content-Type: application/json');
$response = ['success' => false, 'message' => 'Gagal menghapus pengguna.'];

require_once __DIR__ . '/../../../config/config.php';
require_once __DIR__ . '/../../../includes/session.php';
require_once __DIR__ . '/../../../lib/Auth.php';
require_once __DIR__ . '/../../../includes/functions.php';

if (!Auth::isLoggedIn() || $_SESSION['user_role'] !== 'admin') {
    http_response_code(403);
    $response['message'] = 'Akses ditolak.';
    echo json_encode($response);
    exit;
}

if (!isset($pdo) || !$pdo instanceof PDO) {
    http_response_code(500);
    error_log("PDO object not available in admin/delete_user.php");
    $response['message'] = 'Koneksi database gagal.';
    echo json_encode($response);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    $response['message'] = 'Metode request tidak valid.';
    echo json_encode($response);
    exit;
}

$requestData = json_decode(file_get_contents('php://input'), true);
$userIdToDelete = filter_var($requestData['user_id'] ?? null, FILTER_VALIDATE_INT);

if (!$userIdToDelete) {
    http_response_code(400);
    $response['message'] = 'ID pengguna tidak valid.';
    echo json_encode($response);
    exit;
}

if ($userIdToDelete === $_SESSION['user_id']) {
    http_response_code(400);
    $response['message'] = 'Anda tidak dapat menghapus akun Anda sendiri.';
    echo json_encode($response);
    exit;
}

try {
    $auth = new Auth($pdo);
    $userToDelete = $auth->getUserById($userIdToDelete);
    $usernameToDelete = $userToDelete ? $userToDelete['username'] : 'Pengguna'; // Fallback

    if ($auth->deleteUser($userIdToDelete)) {
        $response['success'] = true;
        $response['message'] = "Pengguna '{$usernameToDelete}' (ID: {$userIdToDelete}) berhasil dihapus.";
    } else {
        http_response_code(500);
        $response['message'] = 'Gagal menghapus pengguna dari database.';
    }
} catch (\PDOException $e) {
    error_log("Admin Delete User DB Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan database.";
    http_response_code(500);
} catch (\Throwable $e) {
    error_log("Admin Delete User General Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan internal server.";
    if (defined('DEBUG_MODE') && DEBUG_MODE === true) { $response['debug_php'] = $e->getMessage(); }
    http_response_code(500);
}

echo json_encode($response);
exit;
?>
