<?php
// juri_form_penilaian.php - Form penilaian untuk juri
require_once '../../config.php';
requireRole('juri');

$conn = connectDB();
$juri_id = $_SESSION['user_id'];
$id_cabang_lomba = $_SESSION['id_cabang_lomba'];

// Validasi parameter
if (!isset($_GET['nisn']) || !isset($_GET['domisili'])) {
    header("Location: index.php");
    exit;
}

$nisn = $_GET['nisn'];
$domisili = $_GET['domisili'];

// Validasi domisili - support both old format (kota/kabupaten) and new format (kota semarang/kabupaten semarang)
$valid_domisili = false;
$is_kota = false;

if (strpos(strtolower($domisili), 'kota') !== false) {
    $valid_domisili = true;
    $is_kota = true;
} elseif (strpos(strtolower($domisili), 'kabupaten') !== false) {
    $valid_domisili = true;
    $is_kota = false;
}

if (!$valid_domisili) {
    header("Location: index.php");
    exit;
}

// Dapatkan data peserta berdasarkan NISN dan domisili
if ($is_kota) {
    $sql = "SELECT * FROM domisilikota WHERE NISN = ? AND ID_Cabang_Lomba = ?";
} else {
    $sql = "SELECT * FROM domisilikabupaten WHERE NISN = ? AND ID_Cabang_Lomba = ?";
}

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

if ($result->num_rows === 0) {
    header("Location: index.php");
    exit;
}

$peserta = $result->fetch_assoc();

// Dapatkan nama cabang lomba
$sql = "SELECT Bidang_Lomba FROM cabang_lomba WHERE ID = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $id_cabang_lomba);
$stmt->execute();
$result = $stmt->get_result();
$cabang_lomba = $result->fetch_assoc();
$nama_cabang_lomba = $cabang_lomba['Bidang_Lomba'];

// Dapatkan struktur penilaian berdasarkan cabang lomba
$aspek_penilaian = [];
$total_bobot = 0;

switch ($nama_cabang_lomba) {
    case 'Baca Puisi':
        $aspek_penilaian = [
            ['nama' => 'Penghayatan', 'bobot' => 40],
            ['nama' => 'Pengucapan', 'bobot' => 30],
            ['nama' => 'Gerak Tubuh', 'bobot' => 30]
        ];
        break;
        
    case 'Cipta Lagu':
        $aspek_penilaian = [
            ['nama' => 'Ide Karya', 'bobot' => 30],
            ['nama' => 'Proses Penciptaan', 'bobot' => 25],
            ['nama' => 'Estetika', 'bobot' => 25],
            ['nama' => 'Keunikan', 'bobot' => 20]
        ];
        break;
        
    case 'Cipta Puisi':
        $aspek_penilaian = [
            ['nama' => 'Kesesuaian/Keselarasan', 'bobot' => 20],
            ['nama' => 'Originalitas, Kreativitas, dan Kesegaran Bahasa', 'bobot' => 60],
            ['nama' => 'Keutuhan', 'bobot' => 20]
        ];
        break;
        
    case 'Desain Poster':
        $aspek_penilaian = [
            ['nama' => 'Form', 'bobot' => 30],
            ['nama' => 'Content', 'bobot' => 30],
            ['nama' => 'Context', 'bobot' => 40]
        ];
        break;
        
    case 'Fotografi':
        $aspek_penilaian = [
            ['nama' => 'Ide cerita', 'bobot' => 30],
            ['nama' => 'Komposisi foto', 'bobot' => 30],
            ['nama' => 'Alur Cerita', 'bobot' => 25],
            ['nama' => 'Teknik Pemotretan', 'bobot' => 15]
        ];
        break;
        
    case 'Gitar Solo':
        $aspek_penilaian = [
            ['nama' => 'Teknik', 'bobot' => 30],
            ['nama' => 'Musikalitas', 'bobot' => 40],
            ['nama' => 'Arransemen', 'bobot' => 20],
            ['nama' => 'Penampilan', 'bobot' => 10]
        ];
        break;
        
    case 'Vocal Solo Putra':
    case 'Vocal Solo Putri':
        $aspek_penilaian = [
            ['nama' => 'Materi Suara', 'bobot' => 20],
            ['nama' => 'Teknik Vokal', 'bobot' => 30],
            ['nama' => 'Penghayatan', 'bobot' => 40],
            ['nama' => 'Penampilan', 'bobot' => 10]
        ];
        break;
        
    case 'Jurnalistik':
        $aspek_penilaian = [
            ['nama' => 'Konten/Substansif', 'bobot' => 50],
            ['nama' => 'Kaidah Jurnalistik', 'bobot' => 25],
            ['nama' => 'Segi Kebahasaan', 'bobot' => 25]
        ];
        break;
        
    case 'Kriya':
        $aspek_penilaian = [
            ['nama' => 'Estetika', 'bobot' => 30],
            ['nama' => 'Ketrampilan', 'bobot' => 25],
            ['nama' => 'Kreativitas', 'bobot' => 25],
            ['nama' => 'Kualitas material', 'bobot' => 10],
            ['nama' => 'Fungsional', 'bobot' => 10]
        ];
        break;
        
    case 'Komik Digital':
        $aspek_penilaian = [
            ['nama' => 'Tema', 'bobot' => 10],
            ['nama' => 'Narasi', 'bobot' => 30],
            ['nama' => 'Kreativitas dan Orisinalitas', 'bobot' => 30],
            ['nama' => 'Estetika', 'bobot' => 30]
        ];
        break;
        
    case 'Cerpen':
        $aspek_penilaian = [
            ['nama' => 'Kreativitas pengolahan tema', 'bobot' => 20],
            ['nama' => 'Perspektif/gaya bercerita', 'bobot' => 25],
            ['nama' => 'Orisinalitas dan keunikan', 'bobot' => 30],
            ['nama' => 'Bahasa', 'bobot' => 25]
        ];
        break;
        
    case 'Monolog':
        $aspek_penilaian = [
            ['nama' => 'Naskah monolog', 'bobot' => 20],
            ['nama' => 'Karakter peran', 'bobot' => 50],
            ['nama' => 'Artistic', 'bobot' => 10],
            ['nama' => 'Musik', 'bobot' => 10],
            ['nama' => 'Video', 'bobot' => 10]
        ];
        break;
        
    case 'Tari Kreasi':
        $aspek_penilaian = [
            ['nama' => 'Gagasan/ide karya', 'bobot' => 25],
            ['nama' => 'Garapan karya', 'bobot' => 30],
            ['nama' => 'Penyajian karya', 'bobot' => 45]
        ];
        break;
        
    case 'Film Pendek':
        $aspek_penilaian = [
            ['nama' => 'Keseuaian dengan tema', 'bobot' => 30],
            ['nama' => 'Kreativitas', 'bobot' => 40],
            ['nama' => 'Keindahan/estetika karya', 'bobot' => 30]
        ];
        break;
        
    case 'Musik Tradisional':
        $aspek_penilaian = [
            ['nama' => 'Penyajian', 'bobot' => 20],
            ['nama' => 'Dinamika', 'bobot' => 10],
            ['nama' => 'Ketrampilan Instrumen', 'bobot' => 20],
            ['nama' => 'Keselarasan', 'bobot' => 15],
            ['nama' => 'Penghayatan', 'bobot' => 15],
            ['nama' => 'Intensitas', 'bobot' => 20]
        ];
        break;
        
    default:
        header("Location: index.php");
        exit;
}

// Validasi dan proses formulir yang disubmit
$error = "";
$success = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validasi input
    $valid = true;
    $nilai_aspek = [];
    $total_nilai = 0;
    
    foreach ($aspek_penilaian as $aspek) {
        $nama_aspek = str_replace(' ', '_', strtolower($aspek['nama']));
        
        if (!isset($_POST[$nama_aspek]) || !is_numeric($_POST[$nama_aspek]) || $_POST[$nama_aspek] < 0 || $_POST[$nama_aspek] > 100) {
            $valid = false;
            $error = "Nilai untuk " . $aspek['nama'] . " harus berupa angka antara 0-100";
            break;
        }
        
        // Hitung nilai berbobot
        $nilai = (float)$_POST[$nama_aspek];
        $nilai_berbobot = ($nilai * $aspek['bobot']) / 100;
        $nilai_aspek[] = [
            'nama_aspek' => $aspek['nama'],
            'nilai' => $nilai,
            'bobot' => $aspek['bobot'],
            'nilai_berbobot' => $nilai_berbobot
        ];
        
        $total_nilai += $nilai_berbobot;
    }
    
    // Ambil catatan juri jika ada
    $catatan = isset($_POST['catatan']) ? trim($_POST['catatan']) : '';
    
    if ($valid) {
        // Simpan penilaian ke database
        $sql = "INSERT INTO penilaian (id_juri, id_cabang_lomba, nisn_peserta, domisili, nilai_total, catatan, tanggal) 
                VALUES (?, ?, ?, ?, ?, ?, NOW())";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("iissds", $juri_id, $id_cabang_lomba, $nisn, $domisili, $total_nilai, $catatan);
        
        if ($stmt->execute()) {
            $penilaian_id = $conn->insert_id;
            
            // Simpan detail penilaian
            foreach ($nilai_aspek as $detail) {
                $sql = "INSERT INTO penilaian_detail (id_penilaian, aspek, nilai, bobot) 
                        VALUES (?, ?, ?, ?)";
                $stmt = $conn->prepare($sql);
                $stmt->bind_param("isdd", $penilaian_id, $detail['nama_aspek'], $detail['nilai'], $detail['bobot']);
                $stmt->execute();
            }
            
            $success = "Penilaian berhasil disimpan!";
            
            // Redirect setelah 2 detik
            header("refresh:2;url=index.php");
        } else {
            $error = "Gagal menyimpan penilaian: " . $conn->error;
        }
    }
}
?>

<!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>Form Penilaian - Sistem Penilaian FLS3N</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>
        .sidebar {
            min-height: 100vh;
            background-color: #212529;
            color: white;
            position: sticky;
            top: 0;
        }
        .sidebar a {
            color: rgba(255, 255, 255, 0.8);
            text-decoration: none;
            transition: color 0.3s;
        }
        .sidebar a:hover {
            color: white;
        }
        .sidebar .nav-link.active {
            background-color: rgba(255, 255, 255, 0.1);
            color: white;
        }
        .sidebar .nav-item {
            margin-bottom: 5px;
        }
        .content {
            padding: 20px;
        }
        .dashboard-card {
            border-radius: 5px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        .form-penilaian {
            max-width: 800px;
            margin: 0 auto;
        }
        .info-peserta {
            background-color: #f8f9fa;
            border-left: 4px solid #007bff;
            padding: 15px;
            margin-bottom: 20px;
        }
        .preview-karya {
            margin-bottom: 20px;
        }
        .karya-link {
            display: inline-block;
            margin-top: 10px;
        }
        .thumbnail {
            width: 120px;
            height: 120px;
            object-fit: cover;
            border-radius: 5px;
            margin-right: 15px;
        }
        .badge-domisili {
            font-size: 0.9rem;
            padding: 5px 10px;
            margin-right: 10px;
        }
        .badge-kota {
            background-color: #17a2b8;
        }
        .badge-kabupaten {
            background-color: #28a745;
        }
        .slider-nilai {
            width: 100%;
        }
        .nilai-display {
            font-size: 1.5em;
            font-weight: bold;
            color: #007bff;
        }
        .bobot-info {
            font-size: 0.8em;
            color: #6c757d;
            margin-bottom: 5px;
        }
        .total-nilai {
            font-size: 1.8em;
            font-weight: bold;
            color: #28a745;
        }
        .total-display {
            border-top: 2px solid #dee2e6;
            padding-top: 15px;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-3 col-lg-2 px-0 sidebar">
                <div class="d-flex flex-column p-3">
                    <a href="../juri_dashboard" class="d-flex align-items-center mb-3 mb-md-0 me-md-auto text-white text-decoration-none">
                        <span class="fs-4">Panel Juri</span>
                    </a>
                    <hr>
                    <ul class="nav nav-pills flex-column mb-auto">
                        <li class="nav-item">
                            <a href="../index.php" class="nav-link">
                                <i class="fas fa-home me-2"></i> Dashboard
                            </a>
                        </li>
                        <li class="nav-item">
                            <a href="index.php" class="nav-link">
                                <i class="fas fa-users me-2"></i> Daftar Peserta Kota/Kab
                            </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">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">Form Penilaian</h1>
                </div>
                
                <?php if (!empty($error)): ?>
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-circle me-2"></i> <?php echo $error; ?>
                    </div>
                <?php endif; ?>
                
                <?php if (!empty($success)): ?>
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle me-2"></i> <?php echo $success; ?>
                    </div>
                <?php endif; ?>
                
                <div class="form-penilaian">
                    <!-- Info Peserta -->
                    
                    
                    <!-- Preview Karya -->
                    <div class="preview-karya card mb-4">
                        <div class="card-header bg-light">
                            <h5 class="mb-0"><i class="fas fa-palette me-2"></i> Hasil Karya</h5>
                        </div>
                        <div class="card-body">
                            <?php 
                            // Cek apakah URL karya adalah link Google Drive, YouTube, atau lainnya
                            $karya_url = $peserta['Karya'];
                            if (strpos($karya_url, 'drive.google.com') !== false) {
                                echo "<p><i class='fab fa-google-drive me-1'></i> Link Google Drive:</p>";
                                echo "<a href='{$karya_url}' target='_blank' class='btn btn-outline-primary karya-link'>
                                    <i class='fas fa-external-link-alt me-1'></i> Buka Karya di Google Drive
                                </a>";
                            } elseif (strpos($karya_url, 'youtu.be') !== false || strpos($karya_url, 'youtube.com') !== false) {
                                // Ekstrak video ID dari URL YouTube
                                $video_id = '';
                                if (strpos($karya_url, 'youtu.be/') !== false) {
                                    $parts = explode('youtu.be/', $karya_url);
                                    if (isset($parts[1])) $video_id = $parts[1];
                                } elseif (strpos($karya_url, 'watch?v=') !== false) {
                                    $parts = explode('watch?v=', $karya_url);
                                    if (isset($parts[1])) $video_id = $parts[1];
                                }
                                
                                if (!empty($video_id)) {
                                    echo "<div class='embed-responsive embed-responsive-16by9 mb-3'>";
                                    echo "<iframe class='embed-responsive-item' width='100%' height='315' src='https://www.youtube.com/embed/{$video_id}' frameborder='0' allow='accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture' allowfullscreen></iframe>";
                                    echo "</div>";
                                }
                                
                                echo "<a href='{$karya_url}' target='_blank' class='btn btn-outline-danger karya-link'>
                                    <i class='fab fa-youtube me-1'></i> Buka di YouTube
                                </a>";
                            } else {
                                echo "<p><i class='fas fa-link me-1'></i> Link Karya:</p>";
                                echo "<a href='{$karya_url}' target='_blank' class='btn btn-outline-secondary karya-link'>
                                    <i class='fas fa-external-link-alt me-1'></i> Buka Karya
                                </a>";
                            }
                            ?>
                        </div>
                    </div>
                    
                    <!-- Form Penilaian -->
                    <form method="post" action="" id="formPenilaian" class="card">
                        <div class="card-header bg-primary text-white">
                            <h5 class="mb-0"><i class="fas fa-star me-2"></i> Formulir Penilaian</h5>
                        </div>
                        <div class="card-body">
                            <!-- Kriteria Penilaian Dinamis -->
                            <?php foreach ($aspek_penilaian as $index => $aspek): ?>
                                <?php $nama_aspek = str_replace(' ', '_', strtolower($aspek['nama'])); ?>
                                <div class="mb-4">
                                    <label for="<?php echo $nama_aspek; ?>" class="form-label">
                                        <strong><?php echo $aspek['nama']; ?></strong>
                                    </label>
                                    <p class="bobot-info">Bobot: <?php echo $aspek['bobot']; ?>%</p>
                                    
                                    <div class="row align-items-center">
                                        <div class="col-md-8">
                                            <input type="range" class="form-range slider-nilai" id="<?php echo $nama_aspek; ?>" 
                                                   name="<?php echo $nama_aspek; ?>" min="0" max="100" step="1" value="70"
                                                   oninput="updateNilai('<?php echo $nama_aspek; ?>')">
                                        </div>
                                        <div class="col-md-4 text-center">
                                            <span id="<?php echo $nama_aspek; ?>_nilai" class="nilai-display">70</span>
                                            <span>/100</span>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                            
                            <!-- Total Nilai -->
                            <div class="total-display">
                                <div class="row align-items-center">
                                    <div class="col-md-8">
                                        <h5>Total Nilai (Tertimbang)</h5>
                                    </div>
                                    <div class="col-md-4 text-center">
                                        <span id="total_nilai" class="total-nilai">70.00</span>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Catatan -->
                            <div class="mb-3 mt-4">
                                <label for="catatan" class="form-label"><strong>Catatan Penilaian</strong> (Opsional)</label>
                                <textarea class="form-control" id="catatan" name="catatan" rows="4" placeholder="Tulis catatan atau umpan balik untuk peserta ini..."></textarea>
                            </div>
                            
                            <!-- Tombol Submit -->
                            <div class="text-center mt-4">
                                <button type="submit" class="btn btn-primary btn-lg">
                                    <i class="fas fa-save me-2"></i> Simpan Penilaian
                                </button>
                                <a href="index.php" class="btn btn-outline-secondary btn-lg ms-2">
                                    <i class="fas fa-arrow-left me-2"></i> Kembali
                                </a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Fungsi untuk menghitung total nilai berdasarkan bobot
        function calculateTotal() {
            let totalNilai = 0;
            
            <?php foreach ($aspek_penilaian as $aspek): ?>
                <?php $nama_aspek = str_replace(' ', '_', strtolower($aspek['nama'])); ?>
                const nilai_<?php echo $nama_aspek; ?> = parseFloat(document.getElementById('<?php echo $nama_aspek; ?>').value);
                const bobot_<?php echo $nama_aspek; ?> = <?php echo $aspek['bobot']; ?>;
                totalNilai += (nilai_<?php echo $nama_aspek; ?> * bobot_<?php echo $nama_aspek; ?>) / 100;
            <?php endforeach; ?>
            
            document.getElementById('total_nilai').textContent = totalNilai.toFixed(2);
        }
        
        // Fungsi untuk mengupdate tampilan nilai
        function updateNilai(aspek) {
            const nilai = document.getElementById(aspek).value;
            document.getElementById(aspek + '_nilai').textContent = nilai;
            calculateTotal();
        }
        
        // Inisialisasi nilai awal
        document.addEventListener('DOMContentLoaded', function() {
            <?php foreach ($aspek_penilaian as $aspek): ?>
                <?php $nama_aspek = str_replace(' ', '_', strtolower($aspek['nama'])); ?>
                updateNilai('<?php echo $nama_aspek; ?>');
            <?php endforeach; ?>
        });
    </script>
</body>
</html>

<?php $conn->close(); ?>