<?php
require_once 'config.php';
requireRole('admin');

header('Content-Type: application/json');
$response = array('success' => false, 'message' => '');

try {
    $conn = connectDB();
    
    // Ambil parameter
    $cabang_lomba = isset($_POST['cabang_lomba']) ? sanitizeInput($_POST['cabang_lomba']) : '';
    $domisili = isset($_POST['domisili']) ? sanitizeInput($_POST['domisili']) : '';
    
    if (empty($domisili)) {
        throw new Exception("Parameter domisili diperlukan");
    }
    
    // Buat query base
    $query = "DELETE FROM penilaian WHERE domisili = ?";
    $params = array($domisili);
    $types = "s";
    
    // Tambahkan filter cabang lomba jika ada
    if (!empty($cabang_lomba)) {
        $query .= " AND id_cabang_lomba = ?";
        $params[] = $cabang_lomba;
        $types .= "i";
    }
    
    // Eksekusi query
    $stmt = $conn->prepare($query);
    if ($stmt) {
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        
        $affectedRows = $stmt->affected_rows;
        $stmt->close();
        
        $response['success'] = true;
        $response['message'] = "Berhasil menghapus " . $affectedRows . " data penilaian.";
    } else {
        throw new Exception("Gagal menyiapkan query: " . $conn->error);
    }
    
} catch (Exception $e) {
    $response['message'] = "Error: " . $e->getMessage();
}

echo json_encode($response);
?>