<?php
// delete_all_nilai.php
require_once '../includes/auth.php';
require_once '../includes/functions.php';
require_once '../includes/config.php';

if (!isAdmin()) {
    redirect('../login.php');
}

$success = '';
$error = '';

// Cek apakah request POST dan ada konfirmasi
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['confirm_delete'])) {
    
    // Validasi konfirmasi teks
    if (empty($_POST['confirm_text']) || strtoupper($_POST['confirm_text']) !== 'HAPUS') {
        $_SESSION['error'] = 'Konfirmasi teks tidak valid. Harap ketik "HAPUS" untuk melanjutkan.';
        redirect('nilai.php');
    }
    
    // Ambil parameter filter
    $ujian_id = $_POST['ujian_id'] ?? '';
    $peserta_id = $_POST['peserta_id'] ?? '';
    $station_id = $_POST['station_id'] ?? '';
    
    try {
        $pdo->beginTransaction();
        
        // Buat kondisi WHERE berdasarkan filter
        $where_conditions = [];
        $params = [];
        
        if (!empty($ujian_id)) {
            $where_conditions[] = "ujian_id = ?";
            $params[] = $ujian_id;
        }
        
        if (!empty($peserta_id)) {
            $where_conditions[] = "peserta_id = ?";
            $params[] = $peserta_id;
        }
        
        if (!empty($station_id)) {
            $where_conditions[] = "station_id = ?";
            $params[] = $station_id;
        }
        
        $where_sql = '';
        if (!empty($where_conditions)) {
            $where_sql = "WHERE " . implode(" AND ", $where_conditions);
        }
        
        // Hapus data penilaian_global terlebih dahulu (karena ada foreign key constraint)
        $delete_global_query = "DELETE FROM penilaian_global $where_sql";
        if (!empty($where_conditions)) {
            $stmt = $pdo->prepare($delete_global_query);
            $stmt->execute($params);
        } else {
            $stmt = $pdo->query("DELETE FROM penilaian_global");
        }
        
        // Hapus data penilaian
        $delete_penilaian_query = "DELETE FROM penilaian $where_sql";
        if (!empty($where_conditions)) {
            $stmt = $pdo->prepare($delete_penilaian_query);
            $stmt->execute($params);
        } else {
            $stmt = $pdo->query("DELETE FROM penilaian");
        }
        
        $pdo->commit();
        
        // Hitung jumlah data yang dihapus
        $deleted_count = $stmt->rowCount();
        
        // Set pesan sukses
        $message = "Berhasil menghapus $deleted_count data penilaian.";
        if (!empty($where_conditions)) {
            $message .= " (Dengan filter yang aktif)";
        }
        
        $_SESSION['success'] = $message;
        
    } catch (PDOException $e) {
        $pdo->rollBack();
        $_SESSION['error'] = "Gagal menghapus data: " . $e->getMessage();
    }
    
    // Redirect kembali ke halaman nilai
    redirect('nilai.php');
} else {
    redirect('nilai.php');
}
?>