<?php
require_once '../includes/header.php';
require_once '../includes/navbar.php';

// Cek apakah parameter ID tersedia
if (!isset($_GET['id']) || empty($_GET['id'])) {
    echo "<script>
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'ID prestasi tidak valid!'
        }).then(() => {
            window.location.href = 'index.php';
        });
    </script>";
    exit();
}

$id_prestasi = mysqli_real_escape_string($conn, $_GET['id']);

// Ambil data prestasi berdasarkan ID
$query_prestasi = "SELECT p.*, s.id_siswa, s.nisn, s.nis, s.nama_lengkap 
                   FROM bind_prestasi_siswa p 
                   JOIN bind_siswa s ON p.id_siswa = s.id_siswa 
                   WHERE p.id_prestasi = '$id_prestasi'";
$result_prestasi = mysqli_query($conn, $query_prestasi);

if (mysqli_num_rows($result_prestasi) == 0) {
    echo "<script>
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'Data prestasi tidak ditemukan!'
        }).then(() => {
            window.location.href = 'index.php';
        });
    </script>";
    exit();
}

$prestasi = mysqli_fetch_assoc($result_prestasi);

// Ambil data siswa untuk dropdown
$query_siswa = "SELECT id_siswa, nisn, nis, nama_lengkap 
               FROM bind_siswa 
               ORDER BY nama_lengkap";
$result_siswa = mysqli_query($conn, $query_siswa);

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Ambil data dari form
    $id_siswa = $_POST['id_siswa'];
    $jenis = $_POST['jenis'];
    $tingkat = $_POST['tingkat'];
    $nama_prestasi = $_POST['nama_prestasi'];
    $tahun = $_POST['tahun'];
    $keterangan = $_POST['keterangan'];
    
    // Validasi: Cek apakah siswa sudah memiliki data prestasi dengan nama yang sama (kecuali data yang sedang diedit)
    $query_cek = "SELECT p.id_prestasi, s.nisn, s.nama_lengkap 
                 FROM bind_prestasi_siswa p 
                 JOIN bind_siswa s ON p.id_siswa = s.id_siswa 
                 WHERE p.id_siswa = '$id_siswa' 
                 AND p.nama_prestasi = '$nama_prestasi' 
                 AND p.id_prestasi != '$id_prestasi'";
    $result_cek = mysqli_query($conn, $query_cek);
    
    if (mysqli_num_rows($result_cek) > 0) {
        $data_siswa = mysqli_fetch_assoc($result_cek);
        echo "<script>
            Swal.fire({
                icon: 'error',
                title: 'Gagal',
                html: 'Data prestasi <b>" . addslashes($nama_prestasi) . "</b> untuk siswa <b>" . addslashes($data_siswa['nama_lengkap']) . "</b> (NISN: " . $data_siswa['nisn'] . ") sudah ada.'
            });
        </script>";
    } else {
        // Update data
        $sql = "UPDATE bind_prestasi_siswa SET 
                id_siswa = '$id_siswa',
                jenis = '$jenis',
                tingkat = '$tingkat',
                nama_prestasi = '$nama_prestasi',
                tahun = '$tahun',
                keterangan = '$keterangan'
                WHERE id_prestasi = '$id_prestasi'";
        
        if ($conn->query($sql)) {
            echo "<script>
                Swal.fire({
                    icon: 'success',
                    title: 'Berhasil',
                    text: 'Data prestasi berhasil diperbarui'
                }).then(() => {
                    window.location.href = 'index.php';
                });
            </script>";
        } else {
            echo "<script>
                Swal.fire({
                    icon: 'error',
                    title: 'Gagal',
                    text: 'Terjadi kesalahan: " . addslashes($conn->error) . "'
                });
            </script>";
        }
    }
}
?>

<div class="container mt-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fas fa-edit me-2"></i>Edit Data Prestasi</h2>
        <a href="index.php" class="btn btn-secondary">
            <i class="fas fa-arrow-left me-1"></i> Kembali
        </a>
    </div>
    
    <div class="card border-0 shadow-lg">
        <div class="card-header bg-primary text-white py-3">
            <h5 class="card-title mb-0"><i class="fas fa-trophy me-2"></i>Edit Data Prestasi</h5>
        </div>
        <div class="card-body p-4">
            <form method="POST" id="formEditPrestasi">
                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="id_siswa" class="form-label">Siswa <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-user-graduate"></i></span>
                                <select class="form-select select2" id="id_siswa" name="id_siswa" required>
                                    <option value="">Pilih Siswa</option>
                                    <?php 
                                    mysqli_data_seek($result_siswa, 0);
                                    while ($siswa = mysqli_fetch_assoc($result_siswa)): 
                                        $selected = ($siswa['id_siswa'] == $prestasi['id_siswa']) ? 'selected' : '';
                                    ?>
                                    <option value="<?= $siswa['id_siswa']; ?>" <?= $selected; ?>>
                                        <?= $siswa['nisn'] . ' - ' . $siswa['nama_lengkap'] . ' (' . $siswa['nis'] . ')'; ?>
                                    </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="jenis" class="form-label">Jenis Prestasi <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-tag"></i></span>
                                <select class="form-select" id="jenis" name="jenis" required>
                                    <option value="">Pilih Jenis</option>
                                    <option value="Akademik" <?= ($prestasi['jenis'] == 'Akademik') ? 'selected' : ''; ?>>Akademik</option>
                                    <option value="Non Akademik" <?= ($prestasi['jenis'] == 'Non Akademik') ? 'selected' : ''; ?>>Non Akademik</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="tingkat" class="form-label">Tingkat Prestasi <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-signal"></i></span>
                                <select class="form-select" id="tingkat" name="tingkat" required>
                                    <option value="">Pilih Tingkat</option>
                                    <option value="Sekolah" <?= ($prestasi['tingkat'] == 'Sekolah') ? 'selected' : ''; ?>>Sekolah</option>
                                    <option value="Kabupaten" <?= ($prestasi['tingkat'] == 'Kabupaten') ? 'selected' : ''; ?>>Kabupaten</option>
                                    <option value="Provinsi" <?= ($prestasi['tingkat'] == 'Provinsi') ? 'selected' : ''; ?>>Provinsi</option>
                                    <option value="Nasional" <?= ($prestasi['tingkat'] == 'Nasional') ? 'selected' : ''; ?>>Nasional</option>
                                    <option value="International" <?= ($prestasi['tingkat'] == 'International') ? 'selected' : ''; ?>>International</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="nama_prestasi" class="form-label">Nama Prestasi <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-trophy"></i></span>
                                <input type="text" class="form-control" id="nama_prestasi" name="nama_prestasi" required 
                                       value="<?= htmlspecialchars($prestasi['nama_prestasi']); ?>" placeholder="Nama prestasi">
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="tahun" class="form-label">Tahun <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-calendar"></i></span>
                                <input type="number" class="form-control" id="tahun" name="tahun" required 
                                       min="2000" max="2099" value="<?= $prestasi['tahun']; ?>" placeholder="Tahun prestasi">
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="keterangan" class="form-label">Keterangan</label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-info-circle"></i></span>
                                <textarea class="form-control" id="keterangan" name="keterangan" rows="3" placeholder="Keterangan tambahan"><?= htmlspecialchars($prestasi['keterangan']); ?></textarea>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="d-flex justify-content-end mt-4">
                    <a href="index.php" class="btn btn-secondary me-2">
                        <i class="fas fa-times me-1"></i> Batal
                    </a>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save me-1"></i> Perbarui
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- jQuery (required for Select2) -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- Select2 CSS -->
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<!-- Select2 JS -->
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Form validation
    document.getElementById('formEditPrestasi').addEventListener('submit', function(e) {
        let isValid = true;
        const requiredInputs = this.querySelectorAll('[required]');
        
        requiredInputs.forEach(input => {
            if (!input.value.trim()) {
                isValid = false;
                input.classList.add('is-invalid');
            } else {
                input.classList.remove('is-invalid');
            }
        });
        
        if (!isValid) {
            e.preventDefault();
            Swal.fire({
                icon: 'error',
                title: 'Oops...',
                text: 'Harap isi semua field yang wajib diisi!',
                confirmButtonColor: '#3085d6'
            });
        }
    });
});

$(document).ready(function() {
    // Inisialisasi Select2
    $('#id_siswa').select2({
        theme: 'bootstrap4',
        placeholder: "Pilih Siswa",
        allowClear: true
    });
});
</script>

<style>
.select2-container--bootstrap4 .select2-selection--single {
    height: 38px;
    padding: 4px 12px;
    font-size: 1rem;
    border: 1px solid #ced4da;
    border-radius: 0.375rem;
}

.select2-container--bootstrap4 .select2-selection--single .select2-selection__rendered {
    padding-left: 0;
}

.select2-container--bootstrap4 .select2-dropdown {
    border: 1px solid #ced4da;
    border-radius: 0.375rem;
}

.select2-container--bootstrap4 .select2-search--dropdown .select2-search__field {
    border: 1px solid #ced4da;
    border-radius: 0.375rem;
}

.select2-container--bootstrap4 .select2-results__option--highlighted {
    background-color: #0d6efd;
    color: white;
}

.input-group .select2-container--bootstrap4 {
    flex: 1 1 auto;
    width: 1% !important;
}

.input-group .select2-container--bootstrap4 .select2-selection {
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
    border-left: 0;
}
</style>

<?php
require_once '../includes/footer.php';
?>