<?php
require_once '../../config.php';
require('../admin_penilaian/fpdf/fpdf.php');

$conn = connectDB();

if (!isset($_GET['cabang']) || !is_numeric($_GET['cabang'])) {
    die("ID cabang lomba tidak valid.");
}
$id_cabang_lomba = (int)$_GET['cabang'];

// Ambil nama cabang lomba
$stmt = $conn->prepare("SELECT Bidang_Lomba FROM cabang_lomba WHERE ID = ?");
$stmt->bind_param("i", $id_cabang_lomba);
$stmt->execute();
$stmt->bind_result($bidang_lomba);
$stmt->fetch();
$stmt->close();

if (!$bidang_lomba) {
    die("Cabang lomba tidak ditemukan.");
}

// Ambil aspek penilaian dengan bobot
$kriteria_list = [];
$stmt = $conn->prepare("SELECT aspek FROM aspek_penilaian WHERE bidang_lomba = ? ORDER BY id");
$stmt->bind_param("s", $bidang_lomba);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $kriteria_list[] = $row['aspek'];
}
$stmt->close();

if (empty($kriteria_list)) {
    die("Aspek penilaian tidak ditemukan.");
}

// Ambil data juri (maksimal 5)
$juri_list = [];
$stmt = $conn->prepare("SELECT DISTINCT u.id, u.nama_lengkap 
                        FROM penilaian p 
                        JOIN users u ON p.id_juri = u.id 
                        WHERE p.id_cabang_lomba = ?
                        ORDER BY u.id 
                        LIMIT 5");
$stmt->bind_param("i", $id_cabang_lomba);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $juri_list[] = $row;
}
$stmt->close();

if (empty($juri_list)) {
    die("Data juri tidak ditemukan.");
}

// Ambil data penilaian langsung dari tabel penilaian
$sql = "SELECT 
            p.nisn_peserta,
            COALESCE(dk.Nama_Peserta, dkb.Nama_Peserta) AS nama_peserta,
            COALESCE(dk.Nama_Sekolah, dkb.Nama_Sekolah) AS nama_sekolah,
            'Kota Salatiga' AS domisili,
            p.id_juri AS juri_id,
            p.nilai_total
        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 = 'kota_salatiga'
        WHERE p.id_cabang_lomba = ? AND p.domisili = 'kota_salatiga'
        ORDER BY p.nisn_peserta, p.id_juri";

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $id_cabang_lomba);
$stmt->execute();
$result = $stmt->get_result();

$data = [];
while ($row = $result->fetch_assoc()) {
    $nisn = $row['nisn_peserta'];
    $juri_id = $row['juri_id'];

    if (!isset($data[$nisn])) {
        $data[$nisn] = [
            'nama' => $row['nama_peserta'] ?: 'N/A',
            'sekolah' => $row['nama_sekolah'] ?: 'N/A',
            'domisili' => $row['domisili'],
            'juri' => []
        ];
    }

    $data[$nisn]['juri'][$juri_id] = [
        'nilai_total' => (float)$row['nilai_total']
    ];
}
$stmt->close();

if (empty($data)) {
    die("Data penilaian tidak ditemukan.");
}

// Hitung total dari semua juri untuk ranking
$ranking_data = [];
foreach ($data as $nisn => $peserta) {
    $total_semua_juri = 0;
    $count_juri = 0;
    
    foreach ($peserta['juri'] as $juri_id => $juri_data) {
        $total_semua_juri += $juri_data['nilai_total'];
        $count_juri++;
    }
    
    $ranking_data[$nisn] = [
        'nama' => $peserta['nama'],
        'sekolah' => $peserta['sekolah'],
        'domisili' => $peserta['domisili'],
        'total_semua_juri' => $total_semua_juri,
        'count_juri' => $count_juri,
        'juri' => $peserta['juri']
    ];
}

// Urutkan berdasarkan total nilai semua juri (tertinggi ke terendah)
uasort($ranking_data, function($a, $b) {
    return $b['total_semua_juri'] <=> $a['total_semua_juri'];
});

// PDF Setup dengan orientasi landscape
$pdf = new FPDF('L', 'mm', 'A4'); // 297 x 210 mm
$pdf->AddPage();
$pdf->SetMargins(10, 10, 10);

// Header
$pdf->SetFont('Arial', 'B', 16);
$pdf->Cell(0, 8, 'REKAP NILAI FLS3N TINGKAT CABANG DINAS PENDIDIKAN WILAYAH I - KOTA SEMARANG', 0, 1, 'C');
$pdf->SetFont('Arial', 'B', 14);
$pdf->Cell(0, 6, 'Lomba: ' . strtoupper($bidang_lomba), 0, 1, 'C');
$pdf->Ln(5);

// Informasi tambahan
$pdf->SetFont('Arial', '', 10);
$pdf->Cell(0, 5, 'Tanggal Cetak: ' . date('d F Y, H:i:s'), 0, 1, 'R');
$pdf->Cell(0, 5, 'Jumlah Peserta: ' . count($ranking_data) . ' | Jumlah Juri: ' . count($juri_list), 0, 1, 'R');
$pdf->Ln(3);

// Hitung lebar kolom dinamis
$total_width = 277; // Total lebar halaman landscape - margin
$width_no = 15;
$width_nama = 45;
$width_sekolah = 55;
$width_domisili = 25;
$width_total = 25; // Kolom untuk total semua juri

$remaining_width = $total_width - ($width_no + $width_nama + $width_sekolah + $width_domisili + $width_total);
$width_per_juri = $remaining_width / count($juri_list);

// Header tabel
$pdf->SetFont('Arial', 'B', 9);
$pdf->SetFillColor(200, 200, 200);

// Baris header utama
$pdf->Cell($width_no, 10, 'No', 1, 0, 'C', true);
$pdf->Cell($width_nama, 10, 'Nama Peserta', 1, 0, 'C', true);
$pdf->Cell($width_sekolah, 10, 'Nama Sekolah', 1, 0, 'C', true);
$pdf->Cell($width_domisili, 10, 'Domisili', 1, 0, 'C', true);

foreach ($juri_list as $index => $juri) {
    $juri_name = 'JURI ' . ($index + 1);
    $pdf->Cell($width_per_juri, 10, $juri_name, 1, 0, 'C', true);
}

$pdf->Cell($width_total, 10, 'TOTAL', 1, 0, 'C', true);
$pdf->Ln();

// Data peserta
$pdf->SetFont('Arial', '', 7);
$no = 1;

foreach ($ranking_data as $nisn => $peserta) {
    // Cek jika butuh halaman baru
    if ($pdf->GetY() > 180) {
        $pdf->AddPage();
        // Ulangi header
        $pdf->SetFont('Arial', 'B', 9);
        $pdf->SetFillColor(200, 200, 200);
        
        $pdf->Cell($width_no, 10, 'No', 1, 0, 'C', true);
        $pdf->Cell($width_nama, 10, 'Nama Peserta', 1, 0, 'C', true);
        $pdf->Cell($width_sekolah, 10, 'Nama Sekolah', 1, 0, 'C', true);
        $pdf->Cell($width_domisili, 10, 'Domisili', 1, 0, 'C', true);
        
        foreach ($juri_list as $index => $juri) {
            $juri_name = 'JURI ' . ($index + 1);
            $pdf->Cell($width_per_juri, 10, $juri_name, 1, 0, 'C', true);
        }
        
        $pdf->Cell($width_total, 10, 'TOTAL', 1, 0, 'C', true);
        $pdf->Ln();
        
        $pdf->SetFont('Arial', '', 8);
    }
    
    // Warna baris bergantian
    $fill = ($no % 2 == 0);
    $pdf->SetFillColor(245, 245, 245);
    
    $pdf->Cell($width_no, 8, $no, 1, 0, 'C', $fill);
    $pdf->Cell($width_nama, 8, substr($peserta['nama'], 0, 22), 1, 0, 'L', $fill);
    $pdf->Cell($width_sekolah, 8, substr($peserta['sekolah'], 0, 28), 1, 0, 'L', $fill);
    $pdf->Cell($width_domisili, 8, $peserta['domisili'], 1, 0, 'C', $fill);

    // Data juri - hanya total nilai
    foreach ($juri_list as $juri) {
        $id_juri = $juri['id'];
        $nilai_juri = $peserta['juri'][$id_juri] ?? null;
        
        if ($nilai_juri) {
            $pdf->Cell($width_per_juri, 8, number_format($nilai_juri['nilai_total'], 1), 1, 0, 'C', $fill);
        } else {
            // Jika juri belum menilai
            $pdf->Cell($width_per_juri, 8, '-', 1, 0, 'C', $fill);
        }
    }

    // Total dari semua juri
    $pdf->Cell($width_total, 8, number_format($peserta['total_semua_juri'], 1), 1, 0, 'C', $fill);
    $pdf->Ln();
    
    $no++;
}

// Footer informasi
$pdf->Ln(5);
$pdf->SetFont('Arial', 'I', 8);
$pdf->Cell(0, 5, 'Data diurutkan berdasarkan total nilai dari semua juri (tertinggi ke terendah)', 0, 1, 'L');
$pdf->Cell(0, 5, 'Kolom TOTAL merupakan penjumlahan nilai dari semua juri', 0, 1, 'L');

// Output PDF
$filename = "Rekap_Nilai_FLS3N_" . str_replace(' ', '_', $bidang_lomba) . "_" . date('Y-m-d_H-i-s') . ".pdf";
$pdf->Output("I", $filename);

$conn->close();
?>