<?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 kegemaran tidak valid!'
        }).then(() => {
            window.location.href = 'index.php';
        });
    </script>";
    exit();
}

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

// Ambil data kegemaran berdasarkan ID
$query_kegemaran = "SELECT kg.*, s.id_siswa, s.nisn, s.nis, s.nama_lengkap 
                   FROM bind_siswa_kegemaran kg 
                   JOIN bind_siswa s ON kg.id_siswa = s.id_siswa 
                   WHERE kg.id_kegemaran = '$id_kegemaran'";
$result_kegemaran = mysqli_query($conn, $query_kegemaran);

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

$kegemaran = mysqli_fetch_assoc($result_kegemaran);

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Ambil data dari form
    $id_siswa = $_POST['id_siswa'];
    $kategori = $_POST['kategori'];
    $nama_kegemaran = $_POST['nama_kegemaran'];
    
    // Validasi: Cek apakah siswa sudah memiliki data kegemaran dengan nama yang sama (kecuali data yang sedang diedit)
    $query_cek = "SELECT kg.id_kegemaran, s.nisn, s.nama_lengkap 
                 FROM bind_siswa_kegemaran kg 
                 JOIN bind_siswa s ON kg.id_siswa = s.id_siswa 
                 WHERE kg.id_siswa = '$id_siswa' 
                 AND kg.nama_kegemaran = '$nama_kegemaran' 
                 AND kg.id_kegemaran != '$id_kegemaran'";
    $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 kegemaran <b>" . addslashes($nama_kegemaran) . "</b> untuk siswa <b>" . addslashes($data_siswa['nama_lengkap']) . "</b> (NISN: " . $data_siswa['nisn'] . ") sudah ada.'
            });
        </script>";
    } else {
        // Update data
        $sql = "UPDATE bind_siswa_kegemaran SET 
                kategori = '$kategori',
                nama_kegemaran = '$nama_kegemaran'
                WHERE id_kegemaran = '$id_kegemaran'";
        
        if ($conn->query($sql)) {
            echo "<script>
                Swal.fire({
                    icon: 'success',
                    title: 'Berhasil',
                    text: 'Data kegemaran 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 Kegemaran</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-heart me-2"></i>Edit Data Kegemaran</h5>
        </div>
        <div class="card-body p-4">
            <form method="POST" id="formEditKegemaran">
                <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>
                                <input type="text" class="form-control" id="display_siswa" 
                                       value="<?= $kegemaran['nisn'] . ' - ' . $kegemaran['nama_lengkap'] . ' (' . $kegemaran['nis'] . ')'; ?>" 
                                       disabled readonly>
                                <input type="hidden" name="id_siswa" value="<?= $kegemaran['id_siswa']; ?>">
                            </div>
                            <small class="form-text text-muted">Nama siswa tidak dapat diubah</small>
                        </div>
                        
                        <div class="mb-3">
                            <label for="kategori" class="form-label">Kategori <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="kategori" name="kategori" required>
                                    <option value="">Pilih Kategori</option>
                                    <option value="Kesenian" <?= ($kegemaran['kategori'] == 'Kesenian') ? 'selected' : ''; ?>>Kesenian</option>
                                    <option value="Olahraga" <?= ($kegemaran['kategori'] == 'Olahraga') ? 'selected' : ''; ?>>Olahraga</option>
                                    <option value="Organisasi" <?= ($kegemaran['kategori'] == 'Organisasi') ? 'selected' : ''; ?>>Organisasi</option>
                                    <option value="Lainnya" <?= ($kegemaran['kategori'] == 'Lainnya') ? 'selected' : ''; ?>>Lainnya</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="nama_kegemaran" class="form-label">Nama Kegemaran <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-heart"></i></span>
                                <input type="text" class="form-control" id="nama_kegemaran" name="nama_kegemaran" required 
                                       value="<?= htmlspecialchars($kegemaran['nama_kegemaran']); ?>" placeholder="Nama kegemaran">
                            </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>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Form validation
    document.getElementById('formEditKegemaran').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'
            });
        }
    });
});
</script>

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