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

$conn = connectDB();
$error = '';
$success = '';

// Proses hapus semua data jika tombol diklik
if (isset($_POST['hapus_semua_data']) && $_POST['confirm_delete'] === 'confirm') {
    // Mulai transaksi
    $conn->begin_transaction();
    
    try {
        // Hapus semua data penilaian
        $delete_sql = "DELETE FROM penilaian";
        $conn->query($delete_sql);
        
        // Commit transaksi jika semua query berhasil
        $conn->commit();
        
        $success = "Semua data penilaian berhasil dihapus.";
    } catch (Exception $e) {
        // Rollback transaksi jika terjadi error
        $conn->rollback();
        $error = "Gagal menghapus data: " . $e->getMessage();
    }
}

// Filter cabang lomba
$id_cabang_lomba = isset($_GET['cabang']) ? (int)$_GET['cabang'] : '';
$domisili = isset($_GET['domisili']) ? sanitizeInput($_GET['domisili']) : 'kota';

// Get current visibility status
$status_sql = "SELECT setting_value FROM settings WHERE setting_name = 'show_results'";
$status_result = $conn->query($status_sql);
if ($status_result && $status_result->num_rows > 0) {
    $show_results = $status_result->fetch_assoc()['setting_value'];
} else {
    // Set default if not exists
    $show_results = '0';
    $insert_sql = "INSERT INTO settings (setting_name, setting_value, description) 
                  VALUES ('show_results', '0', 'Controls visibility of competition results')";
    $conn->query($insert_sql);
}

// Query untuk mendapatkan data penilaian
$sql_base = "SELECT 
                p.nisn_peserta,
                COALESCE(dk.Nama_Peserta, dkb.Nama_Peserta, dkb2.Nama_Peserta) as nama_peserta,
                COALESCE(dk.Nama_Sekolah, dkb.Nama_Sekolah, dkb2.Nama_Sekolah) as nama_sekolah,
                cl.Bidang_Lomba,
                cl.ID as id_cabang_lomba,
                SUM(p.nilai_total) as total_nilai,
                COUNT(p.id) as jumlah_juri,
                p.domisili,
                CASE 
                    WHEN dk.NISN IS NOT NULL THEN 'kota_salatiga'
                    WHEN dkb2.NISN IS NOT NULL THEN 'kabupaten_demak'
                    ELSE 'kabupaten_semarang'
                END as region
            FROM 
                penilaian p
                LEFT JOIN domisilikota dk ON p.nisn_peserta = dk.NISN AND p.domisili = 'kota_salatiga'
                LEFT JOIN domisilikabupaten dkb ON p.nisn_peserta = dkb.NISN AND p.domisili = 'kabupaten_semarang'
                LEFT JOIN domisilikabupaten2 dkb2 ON p.nisn_peserta = dkb2.NISN AND p.domisili = 'kabupaten_demak'
                LEFT JOIN cabang_lomba cl ON p.id_cabang_lomba = cl.ID
            WHERE 
                1=1";

// Tambahkan filter cabang lomba jika dipilih
if (!empty($id_cabang_lomba)) {
    $sql_base .= " AND p.id_cabang_lomba = $id_cabang_lomba";
}

// Kelompokkan berdasarkan peserta
$sql_base .= " GROUP BY p.nisn_peserta, p.domisili, cl.ID
              ORDER BY cl.ID, region, total_nilai DESC";

$result = $conn->query($sql_base);

// Array untuk menyimpan peserta per cabang lomba dan per region
$pesertaPerCabangLomba = [];

// Memasukkan data ke array berdasarkan cabang lomba dan region
if ($result && $result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $cabangLombaId = $row['id_cabang_lomba'];
        $region = $row['region'];
        
        // Membuat array cabang lomba jika belum ada
        if (!isset($pesertaPerCabangLomba[$cabangLombaId])) {
            $pesertaPerCabangLomba[$cabangLombaId] = [
                'nama_cabang' => $row['Bidang_Lomba'],
                'regions' => [
                    'kota_salatiga' => [],
                    'kabupaten_semarang' => [],
                    'kabupaten_demak' => []
                ]
            ];
        }
        // Menambahkan peserta ke array berdasarkan regionnya
        $pesertaPerCabangLomba[$cabangLombaId]['regions'][$region][] = $row;
    }
}

// Query untuk mendapatkan data ringkasan penilaian per cabang lomba dan juri
$sql_ringkasan = "SELECT 
                    cl.ID as id_cabang_lomba,
                    cl.Bidang_Lomba as nama_cabang,
                    u.id as id_juri,
                    u.nama_lengkap as nama_juri,
                    COUNT(p.nisn_peserta) as jumlah_peserta_dinilai,
                    SUM(p.nilai_total) as total_nilai, -- Menggunakan SUM()
                    AVG(p.nilai_total) as rata_nilai,
                    MAX(p.nilai_total) as nilai_tertinggi,
                    MIN(p.nilai_total) as nilai_terendah
                FROM 
                    penilaian p
                    JOIN cabang_lomba cl ON p.id_cabang_lomba = cl.ID
                    JOIN users u ON p.id_juri = u.id
                WHERE 
                    1+1";

// Tambahkan filter cabang lomba jika dipilih
if (!empty($id_cabang_lomba)) {
    $sql_ringkasan .= " AND p.id_cabang_lomba = $id_cabang_lomba";
}

$sql_ringkasan .= " GROUP BY cl.ID, u.id
                    ORDER BY cl.ID, u.nama_lengkap";

$result_ringkasan = $conn->query($sql_ringkasan);

// Array untuk menyimpan ringkasan per cabang lomba
$ringkasanPerCabangLomba = [];

// Memasukkan data ke array berdasarkan cabang lomba
if ($result_ringkasan && $result_ringkasan->num_rows > 0) {
    while($row = $result_ringkasan->fetch_assoc()) {
        $cabangLombaId = $row['id_cabang_lomba'];
        // Membuat array cabang lomba jika belum ada
        if (!isset($ringkasanPerCabangLomba[$cabangLombaId])) {
            $ringkasanPerCabangLomba[$cabangLombaId] = [
                'nama_cabang' => $row['nama_cabang'],
                'juri' => [],
                'total_peserta' => 0,
                'total_nilai_keseluruhan' => 0,
                'rata_nilai_keseluruhan' => 0
            ];
        }
        // Menambahkan data juri ke array cabang lomba
        $ringkasanPerCabangLomba[$cabangLombaId]['juri'][] = $row;
        
        // Update total peserta dan total nilai keseluruhan
        $ringkasanPerCabangLomba[$cabangLombaId]['total_peserta'] += $row['jumlah_peserta_dinilai'];
        $ringkasanPerCabangLomba[$cabangLombaId]['total_nilai_keseluruhan'] += $row['total_nilai'];
    }
    
    // Hitung rata-rata nilai keseluruhan per cabang lomba
    foreach ($ringkasanPerCabangLomba as $cabangLombaId => $data) {
        if ($data['total_peserta'] > 0) {
            $ringkasanPerCabangLomba[$cabangLombaId]['rata_nilai_keseluruhan'] = 
                $data['total_nilai_keseluruhan'] / $data['total_peserta'];
        }
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="shortcut icon" href="../../../assets/logofls3n.png" type="image/x-icon">
    <title>Hasil Penilaian - Sistem Penilaian Karya Siswa</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .content {
            padding: 20px;
        }
        .medal-gold {
            color: #FFD700;
        }
        .medal-silver {
            color: #C0C0C0;
        }
        .medal-bronze {
            color: #CD7F32;
        }
        @media print {
            .sidebar, .no-print, .modal {
                display: none !important;
            }
            .content {
                width: 100% !important;
                margin: 0 !important;
                padding: 0 !important;
            }
            .print-only {
                display: block !important;
            }
            .container-fluid {
                padding: 0 !important;
            }
            body {
                padding: 1cm;
            }
            h1 {
                font-size: 18pt !important;
            }
            h2 {
                font-size: 16pt !important;
            }
            p, td, th {
                font-size: 12pt !important;
            }
            .table {
                border-collapse: collapse !important;
            }
            .table td, .table th {
                background-color: white !important;
                border: 1px solid #ddd !important;
            }
        }
        .print-only {
            display: none;
        }
        .peringkat-1 {
            font-weight: bold;
            background-color: rgba(255, 215, 0, 0.2) !important;
        }
        .peringkat-2 {
            font-weight: bold;
            background-color: rgba(192, 192, 192, 0.2) !important;
        }
        .peringkat-3 {
            font-weight: bold;
            background-color: rgba(205, 127, 50, 0.2) !important;
        }
        /* New styles for the visibility toggle card */
        .visibility-card {
            border-left: 5px solid;
        }
        .visibility-card.visible {
            border-left-color: #198754;
        }
        .visibility-card.hidden {
            border-left-color: #dc3545;
        }
        /* Delete button styles */
        .btn-delete-all {
            background-color: #dc3545;
            color: white;
            font-weight: bold;
            transition: all 0.3s;
        }
        .btn-delete-all:hover {
            background-color: #bb2d3b;
            color: white;
        }
        /* Ringkasan card styles */
        .ringkasan-card {
            border-left: 5px solid #0d6efd;
            margin-bottom: 20px;
        }
        .ringkasan-card .card-header {
            background-color: rgba(13, 110, 253, 0.1);
            font-weight: bold;
        }
        .juri-badge {
            background-color: #6c757d;
            color: white;
            padding: 5px 10px;
            border-radius: 50px;
            margin-right: 5px;
            margin-bottom: 5px;
            display: inline-block;
        }
        .stats-box {
            background-color: #f8f9fa;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 15px;
            border-left: 4px solid #0d6efd;
        }
        .stats-box .stats-title {
            font-size: 0.9rem;
            color: #6c757d;
            margin-bottom: 5px;
        }
        .stats-box .stats-value {
            font-size: 1.5rem;
            font-weight: bold;
            color: #212529;
        }
        .nav-tabs .nav-link {
            color: #495057;
        }
        .nav-tabs .nav-link.active {
            font-weight: bold;
            color: #0d6efd;
        }
    </style>
</head>
<body>
    <?php include '../sidebar.php'; ?>
                <div class="d-flex flex-column p-3">
                    <a href="../../admin_dashboard" class="d-flex align-items-center mb-3 mb-md-0 me-md-auto text-white text-decoration-none">
                        <span class="fs-4">Admin Panel</span>
                    </a>
                    <hr>
                    <ul class="nav nav-pills flex-column mb-auto">
                        <li class="nav-item">
                            <a href="../../admin_dashboard" class="nav-link">
                                <i class="fas fa-home me-2"></i> Dashboard
                            </a>
                        </li>
                        <li class="nav-item">
                            <a href="../admin_cabang_lomba" class="nav-link">
                                <i class="fas fa-trophy me-2"></i> Cabang Lomba
                            </a>
                        </li>
                        <li class="nav-item">
                            <a href="../admin_kelola_peserta" class="nav-link">
                                <i class="fas fa-user-tie me-2"></i> Kelola Peserta
                            </a>
                        </li>
                        <li class="nav-item">
                            <a href="../admin_peserta_kota" class="nav-link">
                                <i class="fas fa-users me-2"></i> Peserta Kota
                            </a>
                        </li>
                        <li class="nav-item">
                            <a href="../admin_peserta_kabupaten" class="nav-link">
                                <i class="fas fa-users me-2"></i> Peserta Kabupaten
                            </a>
                        </li>
                        <li class="nav-item">                            <a href="../admin_admin" class="nav-link">
                                <i class="fas fa-user-shield me-2"></i> Kelola Admin
                            </a>
                        </li>
                        <li class="nav-item">                            <a href="../admin_juri" class="nav-link">
                                <i class="fas fa-user-tie me-2"></i> Kelola Juri
                            </a>
                        </li>
                        <li class="nav-item">
                            <a href="../admin_penilaian" class="nav-link active">
                                <i class="fas fa-star me-2"></i> Hasil Penilaian
                            </a>
                        </li>
                        <li class="nav-item">
                            <a href="../admin_status_lomba" class="nav-link">
                                <i class="fas fa-toggle-on me-2"></i> Status Lomba
                            </a>
                        </li>
                    </ul>
                    <hr>
                    <div class="dropdown">
                        <a href="#" class="d-flex align-items-center text-white text-decoration-none dropdown-toggle" id="dropdownUser1" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="fas fa-user-circle me-2 fs-5"></i>
                            <strong><?php echo $_SESSION['nama']; ?></strong>
                        </a>
                        <ul class="dropdown-menu dropdown-menu-dark text-small shadow" aria-labelledby="dropdownUser1">
                            
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="../../logout.php">Logout</a></li>
                        </ul>
                    </div>
                </div>
            </div>
            
            <!-- Content -->
            <div class="col-md-9 col-lg-10 content">
                <!-- Header untuk cetak -->
                <div class="print-only">
                    <div class="text-center mb-4">
                        <h1>HASIL PENILAIAN LOMBA KARYA SISWA</h1>
                        <h2>SEMUA DOMISILI</h2>
                        <p>Tanggal: <?php echo date('d F Y'); ?></p>
                    </div>
                </div>
                
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom no-print">
                    <h1 class="h2">Hasil Penilaian</h1>
                    <div>
                        <button class="btn btn-outline-primary me-2" onclick="printWinners()">
                            <i class="fas fa-print me-1"></i> Cetak 10 Pemenang
                        </button>
                        <button class="btn btn-outline-secondary me-2" onclick="window.print()">
                            <i class="fas fa-print me-1"></i> Cetak Semua
                        </button>
                        <a href="generate_berita_acara.php?cabang=<?php echo urlencode($id_cabang_lomba); ?>" class="btn btn-primary" target="_blank">
                            <i class="fas fa-download"></i> Download Berita Acara
                        </a>
                        <button class="btn btn-delete-all" data-bs-toggle="modal" data-bs-target="#deleteAllModal">
                            <i class="fas fa-trash-alt me-1"></i> Hapus Semua Data
                        </button>
                    </div>
                </div>
                
                <div id="alertContainer">
                    <?php if ($success): ?>
                    <div class="alert alert-success alert-dismissible fade show no-print" role="alert">
                        <?php echo $success; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    <?php endif; ?>
                    
                    <?php if ($error): ?>
                    <div class="alert alert-danger alert-dismissible fade show no-print" role="alert">
                        <?php echo $error; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    <?php endif; ?>
                </div>
                
                <!-- Card visibilitas dengan data-status -->
                <div class="card mb-4 no-print visibility-card <?php echo $show_results == '1' ? 'visible' : 'hidden'; ?>" id="visibilityCard" data-status="<?php echo $show_results; ?>">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h5 class="mb-1">Status Pengumuman Pemenang</h5>
                                <p class="mb-0" id="statusText">
                                    <?php if ($show_results == '1'): ?>
                                        <span class="text-success"><i class="fas fa-eye me-1"></i> Pengumuman pemenang saat ini <strong>DITAMPILKAN</strong> ke publik</span>
                                    <?php else: ?>
                                        <span class="text-danger"><i class="fas fa-eye-slash me-1"></i> Pengumuman pemenang saat ini <strong>DISEMBUNYIKAN</strong> dari publik</span>
                                    <?php endif; ?>
                                </p>
                            </div>
                            <button type="button" id="toggleButton" class="btn <?php echo $show_results == '1' ? 'btn-danger' : 'btn-success'; ?>">
                                <?php if ($show_results == '1'): ?>
                                    <i class="fas fa-eye-slash me-1"></i> Sembunyikan Pengumuman
                                <?php else: ?>
                                    <i class="fas fa-eye me-1"></i> Tampilkan Pengumuman
                                <?php endif; ?>
                            </button>
                        </div>
                    </div>
                </div>
                
                <div class="card mb-4 no-print">
                    <div class="card-body">
                        <form action="" method="get" class="row g-3" id="filterForm">
                            <div class="col-md-5">
                                <label for="cabang" class="form-label">Cabang Lomba</label>
                                <select class="form-select" id="cabang" name="cabang" onchange="document.getElementById('filterForm').submit()">
                                    <option value="">Semua Cabang Lomba</option>
                                    <?php
                                    $sql = "SELECT ID, Bidang_Lomba FROM cabang_lomba ORDER BY Bidang_Lomba";
                                    $result_cabang = $conn->query($sql);
                                    
                                    if ($result_cabang->num_rows > 0) {
                                        while($row = $result_cabang->fetch_assoc()) {
                                            $selected = ($id_cabang_lomba == $row["ID"]) ? "selected" : "";
                                            echo "<option value='" . $row["ID"] . "' $selected>" . $row["Bidang_Lomba"] . "</option>";
                                        }
                                    }
                                    ?>
                                </select>
                            </div>
                            
                            <div class="col-md-2 d-flex align-items-end">
                                <button type="submit" class="btn btn-primary w-100">Filter</button>
                            </div>
                        </form>
                    </div>
                </div>
                
                <!-- Tabs untuk navigasi antar tampilan -->
                <ul class="nav nav-tabs mb-4 no-print" id="viewTabs" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active" id="peringkat-tab" data-bs-toggle="tab" data-bs-target="#peringkat-content" type="button" role="tab" aria-controls="peringkat-content" aria-selected="true">
                            <i class="fas fa-medal me-1"></i> Peringkat Peserta
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="ringkasan-tab" data-bs-toggle="tab" data-bs-target="#ringkasan-content" type="button" role="tab" aria-controls="ringkasan-content" aria-selected="false">
                            <i class="fas fa-chart-bar me-1"></i> Ringkasan Penilaian
                        </button>
                    </li>
                </ul>
                
                <!-- Tab content -->
                <div class="tab-content" id="viewTabsContent">
                    <!-- Tab Peringkat Peserta -->
                    <div class="tab-pane fade show active" id="peringkat-content" role="tabpanel" aria-labelledby="peringkat-tab">
                        <div class="mb-4 no-print">
                            <div class="input-group">
                                <input type="text" class="form-control" id="searchInput" placeholder="Cari peserta...">
                                <button class="btn btn-outline-secondary" type="button">
                                    <i class="fas fa-search"></i>
                                </button>
                            </div>
                        </div>
                        
                        <?php foreach ($pesertaPerCabangLomba as $cabangId => $cabangData): ?>
                            <div class="card mb-4 cabang-section" id="cabang-<?php echo $cabangId; ?>">
                                <div class="card-header bg-primary text-white">
                                    <h3><?php echo $cabangData['nama_cabang']; ?></h3>
                                </div>
                                
                                <!-- Tabel Kota Salatiga -->
                                <div class="card-body">
                                    <h5 class="mb-3">
                                        <i class="fas fa-city me-2" style="color: #3b82f6;"></i> <strong style="color: #3b82f6;">Kota Salatiga</strong>
                                    </h5>
                                    <div class="table-responsive">
                                        <table class="table table-striped table-hover">
                                            <thead>
                                                <tr>
                                                    <th>Peringkat</th>
                                                    <th>NISN</th>
                                                    <th>Nama Peserta</th>
                                                    <th>Asal Sekolah</th>
                                                    <th>Nilai Keseluruhan</th>
                                                    <th>Jumlah Juri</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php 
                                                $rank = 1;
                                                if (!empty($cabangData['regions']['kota_salatiga'])) {
                                                    foreach ($cabangData['regions']['kota_salatiga'] as $index => $row): 
                                                        $rowClass = '';
                                                        if ($rank <= 3) {
                                                            $rowClass = 'peringkat-'.$rank;
                                                        }
                                                ?>
                                                        <tr class="peserta-row <?php echo $rowClass; ?>" data-nama="<?php echo $row['nama_peserta']; ?>" data-rank="<?php echo $rank; ?>">
                                                            <td>
                                                                <?php 
                                                                if ($rank == 1) {
                                                                    echo "<i class='fas fa-medal medal-gold me-1'></i> " . $rank;
                                                                } elseif ($rank == 2) {
                                                                    echo "<i class='fas fa-medal medal-silver me-1'></i> " . $rank;
                                                                } elseif ($rank == 3) {
                                                                    echo "<i class='fas fa-medal medal-bronze me-1'></i> " . $rank;
                                                                } else {
                                                                    echo $rank;
                                                                }
                                                                $rank++;
                                                                ?>
                                                            </td>
                                                            <td><?php echo $row["nisn_peserta"]; ?></td>
                                                            <td><?php echo $row["nama_peserta"]; ?></td>
                                                            <td><?php echo $row["nama_sekolah"]; ?></td>
                                                            <td><strong><?php echo number_format($row["total_nilai"], 2); ?></strong></td>
                                                            <td><?php echo $row["jumlah_juri"]; ?></td>
                                                        </tr>
                                                    <?php endforeach;
                                                } else {
                                                    echo '<tr><td colspan="6" class="text-center text-muted">Tidak ada peserta dari Kota Salatiga</td></tr>';
                                                }
                                                ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                                
                                <!-- Tabel Kabupaten Semarang -->
                                <div class="card-body border-top">
                                    <h5 class="mb-3">
                                        <i class="fas fa-tree me-2" style="color: #f59e0b;"></i> <strong style="color: #f59e0b;">Kabupaten Semarang</strong>
                                    </h5>
                                    <div class="table-responsive">
                                        <table class="table table-striped table-hover">
                                            <thead>
                                                <tr>
                                                    <th>Peringkat</th>
                                                    <th>NISN</th>
                                                    <th>Nama Peserta</th>
                                                    <th>Asal Sekolah</th>
                                                    <th>Nilai Keseluruhan</th>
                                                    <th>Jumlah Juri</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php 
                                                $rank = 1;
                                                if (!empty($cabangData['regions']['kabupaten_semarang'])) {
                                                    foreach ($cabangData['regions']['kabupaten_semarang'] as $index => $row): 
                                                        $rowClass = '';
                                                        if ($rank <= 3) {
                                                            $rowClass = 'peringkat-'.$rank;
                                                        }
                                                ?>
                                                        <tr class="peserta-row <?php echo $rowClass; ?>" data-nama="<?php echo $row['nama_peserta']; ?>" data-rank="<?php echo $rank; ?>">
                                                            <td>
                                                                <?php 
                                                                if ($rank == 1) {
                                                                    echo "<i class='fas fa-medal medal-gold me-1'></i> " . $rank;
                                                                } elseif ($rank == 2) {
                                                                    echo "<i class='fas fa-medal medal-silver me-1'></i> " . $rank;
                                                                } elseif ($rank == 3) {
                                                                    echo "<i class='fas fa-medal medal-bronze me-1'></i> " . $rank;
                                                                } else {
                                                                    echo $rank;
                                                                }
                                                                $rank++;
                                                                ?>
                                                            </td>
                                                            <td><?php echo $row["nisn_peserta"]; ?></td>
                                                            <td><?php echo $row["nama_peserta"]; ?></td>
                                                            <td><?php echo $row["nama_sekolah"]; ?></td>
                                                            <td><strong><?php echo number_format($row["total_nilai"], 2); ?></strong></td>
                                                            <td><?php echo $row["jumlah_juri"]; ?></td>
                                                        </tr>
                                                    <?php endforeach;
                                                } else {
                                                    echo '<tr><td colspan="6" class="text-center text-muted">Tidak ada peserta dari Kabupaten Semarang</td></tr>';
                                                }
                                                ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                                
                                <!-- Tabel Kabupaten Demak -->
                                <div class="card-body border-top">
                                    <h5 class="mb-3">
                                        <i class="fas fa-leaf me-2" style="color: #10b981;"></i> <strong style="color: #10b981;">Kabupaten Demak</strong>
                                    </h5>
                                    <div class="table-responsive">
                                        <table class="table table-striped table-hover">
                                            <thead>
                                                <tr>
                                                    <th>Peringkat</th>
                                                    <th>NISN</th>
                                                    <th>Nama Peserta</th>
                                                    <th>Asal Sekolah</th>
                                                    <th>Nilai Keseluruhan</th>
                                                    <th>Jumlah Juri</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php 
                                                $rank = 1;
                                                if (!empty($cabangData['regions']['kabupaten_demak'])) {
                                                    foreach ($cabangData['regions']['kabupaten_demak'] as $index => $row): 
                                                        $rowClass = '';
                                                        if ($rank <= 3) {
                                                            $rowClass = 'peringkat-'.$rank;
                                                        }
                                                ?>
                                                        <tr class="peserta-row <?php echo $rowClass; ?>" data-nama="<?php echo $row['nama_peserta']; ?>" data-rank="<?php echo $rank; ?>">
                                                            <td>
                                                                <?php 
                                                                if ($rank == 1) {
                                                                    echo "<i class='fas fa-medal medal-gold me-1'></i> " . $rank;
                                                                } elseif ($rank == 2) {
                                                                    echo "<i class='fas fa-medal medal-silver me-1'></i> " . $rank;
                                                                } elseif ($rank == 3) {
                                                                    echo "<i class='fas fa-medal medal-bronze me-1'></i> " . $rank;
                                                                } else {
                                                                    echo $rank;
                                                                }
                                                                $rank++;
                                                                ?>
                                                            </td>
                                                            <td><?php echo $row["nisn_peserta"]; ?></td>
                                                            <td><?php echo $row["nama_peserta"]; ?></td>
                                                            <td><?php echo $row["nama_sekolah"]; ?></td>
                                                            <td><strong><?php echo number_format($row["total_nilai"], 2); ?></strong></td>
                                                            <td><?php echo $row["jumlah_juri"]; ?></td>
                                                        </tr>
                                                    <?php endforeach;
                                                } else {
                                                    echo '<tr><td colspan="6" class="text-center text-muted">Tidak ada peserta dari Kabupaten Demak</td></tr>';
                                                }
                                                ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                        
                        <?php if (empty($pesertaPerCabangLomba)): ?>
                            <div class="alert alert-info">
                                Tidak ada data penilaian yang ditemukan.
                            </div>
                        <?php endif; ?>
                    </div>
                    
                    <!-- Tab Ringkasan Penilaian -->
                    <div class="tab-pane fade" id="ringkasan-content" role="tabpanel" aria-labelledby="ringkasan-tab">
                        <?php if (empty($ringkasanPerCabangLomba)): ?>
                            <div class="alert alert-info">
                                Tidak ada data ringkasan penilaian yang ditemukan.
                            </div>
                        <?php else: ?>
                            <?php foreach ($ringkasanPerCabangLomba as $cabangId => $cabangData): ?>
                                <div class="card ringkasan-card mb-4">
                                    <div class="card-header">
                                        <h3><?php echo $cabangData['nama_cabang']; ?></h3>
                                    </div>
                                    <div class="card-body">
                                        <!-- Statistics overview -->
                                         <!-- Statistics overview -->
<div class="row mb-4">
    <div class="col-md-3">
        <div class="stats-box">
            <div class="stats-title">Jumlah Juri</div>
            <div class="stats-value"><?php echo count($cabangData['juri']); ?></div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stats-box">
            <div class="stats-title">Total Peserta Dinilai</div>
            <div class="stats-value"><?php echo $cabangData['total_peserta'] / count($cabangData['juri']); ?></div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stats-box">
            <div class="stats-title">Tanggal Penilaian</div>
            <div class="stats-value"><?php echo date('d/m/Y'); ?></div>
        </div>
    </div>
</div>

<!-- Juri yang terlibat -->
<div class="mb-4">
    <h5>Juri yang Terlibat:</h5>
    <div class="juri-container">
        <?php foreach ($cabangData['juri'] as $juri): ?>
            <span class="juri-badge">
                <i class="fas fa-user-tie me-1"></i> <?php echo $juri['nama_juri']; ?>
            </span>
        <?php endforeach; ?>
    </div>
</div>

<!-- Table detail per juri -->
<div class="table-responsive">
    <table class="table table-bordered table-hover">
        <thead class="table-light">
            <tr>
                <th>Nama Juri</th>
                <th>Jumlah Peserta Dinilai</th>
                
            </tr>
        </thead>
        <tbody>
            <?php foreach ($cabangData['juri'] as $juri): ?>
                <tr>
                    <td><?php echo $juri['nama_juri']; ?></td>
                    <td><?php echo $juri['jumlah_peserta_dinilai']; ?></td>
                    
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    
    
    <!-- Modal Konfirmasi Hapus Semua Data -->
    <div class="modal fade" id="deleteAllModal" tabindex="-1" aria-labelledby="deleteAllModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-danger text-white">
                    <h5 class="modal-title" id="deleteAllModalLabel">Konfirmasi Hapus Semua Data</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="alert alert-warning">
                        <i class="fas fa-exclamation-triangle me-2"></i> Perhatian!
                    </div>
                    <p>Anda akan menghapus <strong>semua data penilaian</strong> dari sistem. Tindakan ini tidak dapat dibatalkan.</p>
                    <p>Ketik "confirm" pada kolom di bawah ini untuk melanjutkan:</p>
                    <form id="deleteAllForm" method="POST">
                        <div class="mb-3">
                            <input type="text" class="form-control" id="confirm_delete" name="confirm_delete" placeholder="confirm" required>
                        </div>
                        <input type="hidden" name="hapus_semua_data" value="1">
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="button" class="btn btn-danger" id="confirmDeleteAllBtn" disabled>Hapus Semua Data</button>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            // Toggle visibility
            $('#toggleButton').click(function() {
                const currentStatus = $('#visibilityCard').data('status');
                const newStatus = currentStatus == '1' ? '0' : '1';
                
                $.ajax({
                    url: 'toggle_visibility.php',
                    type: 'POST',
                    data: { new_status: newStatus },
                    success: function(response) {
                        // Update UI based on new status
                        if (newStatus == '1') {
                            $('#visibilityCard').removeClass('hidden').addClass('visible');
                            $('#visibilityCard').data('status', '1');
                            $('#statusText').html('<span class="text-success"><i class="fas fa-eye me-1"></i> Pengumuman pemenang saat ini <strong>DITAMPILKAN</strong> ke publik</span>');
                            $('#toggleButton').removeClass('btn-success').addClass('btn-danger');
                            $('#toggleButton').html('<i class="fas fa-eye-slash me-1"></i> Sembunyikan Pengumuman');
                        } else {
                            $('#visibilityCard').removeClass('visible').addClass('hidden');
                            $('#visibilityCard').data('status', '0');
                            $('#statusText').html('<span class="text-danger"><i class="fas fa-eye-slash me-1"></i> Pengumuman pemenang saat ini <strong>DISEMBUNYIKAN</strong> dari publik</span>');
                            $('#toggleButton').removeClass('btn-danger').addClass('btn-success');
                            $('#toggleButton').html('<i class="fas fa-eye me-1"></i> Tampilkan Pengumuman');
                        }
                    },
                    error: function() {
                        alert('Terjadi kesalahan. Silakan coba lagi.');
                    }
                });
            });
            
            // Search functionality
            $('#searchInput').on('keyup', function() {
                const value = $(this).val().toLowerCase();
                $('.peserta-row').filter(function() {
                    $(this).toggle($(this).data('nama').toLowerCase().indexOf(value) > -1);
                });
            });
            
            // Handle the delete confirmation
            $('#confirm_delete').on('keyup', function() {
                if ($(this).val() === 'confirm') {
                    $('#confirmDeleteAllBtn').prop('disabled', false);
                } else {
                    $('#confirmDeleteAllBtn').prop('disabled', true);
                }
            });
            
            $('#confirmDeleteAllBtn').click(function() {
                $('#deleteAllForm').submit();
            });
            
            // Detail Nilai Modal
            $('#detailNilaiModal').on('show.bs.modal', function(event) {
                const button = $(event.relatedTarget);
                const nisn = button.data('nisn');
                const nama = button.data('nama');
                const cabang = button.data('cabang');
                const domisili = button.data('domisili');
                
                // Set modal content
                $('#detailNamaPeserta').text(nama);
                $('#detailNISN').text('NISN: ' + nisn);
                $('#detailCabangLomba').text('Cabang Lomba: ' + cabang);
                $('#detailDomisili').text('Domisili: ' + (domisili === 'kota' ? 'Kota' : 'Kabupaten'));
                
                // Clear table
                $('#detailNilaiTable tbody').empty();
                
                // Get detail nilai via AJAX
                $.ajax({
                    url: 'get_detail_nilai.php',
                    type: 'GET',
                    data: {
                        nisn: nisn,
                        domisili: domisili
                    },
                    dataType: 'json',
                    success: function(data) {
                        if (data.length > 0) {
                            $.each(data, function(index, row) {
                                let tr = $('<tr>');
                                tr.append($('<td>').text(row.nama_juri));
                                tr.append($('<td>').text(row.kriteria1));
                                tr.append($('<td>').text(row.kriteria2));
                                tr.append($('<td>').text(row.kriteria3));
                                tr.append($('<td>').text(row.kriteria4));
                                tr.append($('<td>').text(row.kriteria5));
                                tr.append($('<td>').html('<strong>' + row.nilai_total + '</strong>'));
                                $('#detailNilaiTable tbody').append(tr);
                            });
                        } else {
                            $('#detailNilaiTable tbody').append('<tr><td colspan="7" class="text-center">Tidak ada data detail penilaian.</td></tr>');
                        }
                    },
                    error: function() {
                        $('#detailNilaiTable tbody').append('<tr><td colspan="7" class="text-center">Gagal memuat data. Silakan coba lagi.</td></tr>');
                    }
                });
            });
        });
        
        // Function untuk cetak hanya 10 pemenang per cabang lomba
        function printWinners() {
            // Cloning the page for printing
            const printContent = document.querySelector('.content').cloneNode(true);
            
            // Create header
            const header = document.createElement('div');
            header.className = 'text-center mb-4';
            header.innerHTML = `
                <h1>HASIL PENILAIAN LOMBA KARYA SISWA - 10 PEMENANG</h1>
                <h2>${document.getElementById('domisili').options[document.getElementById('domisili').selectedIndex].text}</h2>
                <p>Tanggal: ${new Date().toLocaleDateString('id-ID', {day: 'numeric', month: 'long', year: 'numeric'})}</p>
            `;
            
            // Show only first 10 rows per table
            const tables = printContent.querySelectorAll('.cabang-section table');
            tables.forEach(table => {
                const rows = table.querySelectorAll('tbody tr');
                for (let i = 0; i < rows.length; i++) {
                    if (i >= 10) {
                        rows[i].style.display = 'none';
                    }
                }
            });
            
            // Remove elements with no-print class
            const noPrintElements = printContent.querySelectorAll('.no-print');
            noPrintElements.forEach(el => el.remove());
            
            // Create a new window for printing
            const printWindow = window.open('', '_blank');
            printWindow.document.write(`
                <html>
                <head>
                    <title>10 Besar Pemenang</title>
                    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
                    <style>
                        body { padding: 20px; }
                        .peringkat-1 {
                            font-weight: bold;
                            background-color: rgba(255, 215, 0, 0.2) !important;
                        }
                        .peringkat-2 {
                            font-weight: bold;
                            background-color: rgba(192, 192, 192, 0.2) !important;
                        }
                        .peringkat-3 {
                            font-weight: bold;
                            background-color: rgba(205, 127, 50, 0.2) !important;
                        }
                    </style>
                </head>
                <body>
                    ${header.outerHTML}
                    ${printContent.innerHTML}
                </body>
                </html>
            `);
            
            // Execute print after window loads
            printWindow.document.close();
            printWindow.onload = function() {
                printWindow.focus();
                printWindow.print();
            };
        }
    </script>
</body>
</html>