<?php
require '../db.php';
require '../auth.php';
require_login();
require_admin();

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = (int)($_POST['id'] ?? 0);
    
    if ($id <= 0) {
        echo json_encode(['success' => false, 'message' => 'ID tidak valid']);
        exit;
    }
    
    // Check if user exists
    $check = $db->prepare('SELECT id FROM users WHERE id = ?');
    $check->execute([$id]);
    if (!$check->fetch()) {
        echo json_encode(['success' => false, 'message' => 'User tidak ditemukan']);
        exit;
    }
    
    // Prevent self-deletion
    if ($id == current_user()['id']) {
        echo json_encode(['success' => false, 'message' => 'Tidak bisa menghapus akun sendiri']);
        exit;
    }
    
    try {
        $stmt = $db->prepare('DELETE FROM users WHERE id = ?');
        $result = $stmt->execute([$id]);
        
        if ($result && $stmt->rowCount() > 0) {
            echo json_encode(['success' => true, 'message' => 'Akun berhasil dihapus']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Gagal menghapus akun']);
        }
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Method tidak diizinkan']);
}
exit;
?>
