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

// Ambil ID dari URL
$id = $_GET['id'] ?? 0;

// Ambil data pendidikan berdasarkan ID
$query = "SELECT ps.*, s.nisn, s.nama_lengkap 
          FROM bind_pendidikan_siswa ps 
          JOIN bind_siswa s ON ps.id_siswa = s.id_siswa 
          WHERE ps.id_pendidikan = $id";
$result = mysqli_query($conn, $query);
$data = mysqli_fetch_assoc($result);

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

// Ambil tahun ajaran yang aktif
$query_tahun_aktif = "SELECT id_tahunajaran FROM bind_tahunajaran WHERE aktif = TRUE LIMIT 1";
$result_tahun_aktif = mysqli_query($conn, $query_tahun_aktif);
$tahun_aktif = mysqli_fetch_assoc($result_tahun_aktif);

// Ambil data siswa untuk dropdown berdasarkan tahun ajaran aktif
if ($tahun_aktif) {
    $id_tahun_aktif = $tahun_aktif['id_tahunajaran'];
    $query_siswa = "SELECT s.id_siswa, s.nisn, s.nis, s.nama_lengkap 
                   FROM bind_siswa s
                   JOIN bind_datasiswa ds ON s.id_siswa = ds.id_siswa
                   WHERE ds.id_tahunajaran = '$id_tahun_aktif' 
                   ORDER BY s.nama_lengkap";
} else {
    // Jika tidak ada tahun ajaran aktif, tampilkan semua siswa
    $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'];
    $asal_sekolah = $_POST['asal_sekolah'];
    $no_sttb = $_POST['no_sttb'];
    $tgl_sttb = (!empty($_POST['tgl_sttb'])) ? $_POST['tgl_sttb'] : NULL;
    $no_skhun = $_POST['no_skhun'];
    $tgl_skhun = (!empty($_POST['tgl_skhun'])) ? $_POST['tgl_skhun'] : NULL;
    $lama_belajar = $_POST['lama_belajar'];
    $pindahan_dari = $_POST['pindahan_dari'];
    $alasan_pindah = $_POST['alasan_pindah'];
    $diterima_di_kelas = $_POST['diterima_di_kelas'];
    $paket = $_POST['paket'];
    $tanggal_diterima = $_POST['tanggal_diterima'];
    
    // Query update dengan penanganan nilai NULL
    $sql = "UPDATE bind_pendidikan_siswa SET 
            id_siswa = '$id_siswa',
            asal_sekolah = " . (($asal_sekolah !== '') ? "'$asal_sekolah'" : "NULL") . ",
            no_sttb = " . (($no_sttb !== '') ? "'$no_sttb'" : "NULL") . ",
            tgl_sttb = " . (($tgl_sttb !== NULL) ? "'$tgl_sttb'" : "NULL") . ",
            no_skhun = " . (($no_skhun !== '') ? "'$no_skhun'" : "NULL") . ",
            tgl_skhun = " . (($tgl_skhun !== NULL) ? "'$tgl_skhun'" : "NULL") . ",
            lama_belajar = " . (($lama_belajar !== '') ? "'$lama_belajar'" : "NULL") . ",
            pindahan_dari = " . (($pindahan_dari !== '') ? "'$pindahan_dari'" : "NULL") . ",
            alasan_pindah = " . (($alasan_pindah !== '') ? "'$alasan_pindah'" : "NULL") . ",
            diterima_di_kelas = " . (($diterima_di_kelas !== '') ? "'$diterima_di_kelas'" : "NULL") . ",
            paket = " . (($paket !== '') ? "'$paket'" : "NULL") . ",
            tanggal_diterima = '$tanggal_diterima'
            WHERE id_pendidikan = $id";
    
    if ($conn->query($sql)) {
        echo "<script>
            Swal.fire({
                icon: 'success',
                title: 'Berhasil',
                text: 'Data pendidikan 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 Pendidikan</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-graduation-cap me-2"></i>Formulir Edit Data Pendidikan</h5>
            <?php if ($tahun_aktif): ?>
            <small class="d-block mt-1">Menampilkan siswa dari tahun ajaran aktif</small>
            <?php else: ?>
            <small class="d-block mt-1 text-warning">Tidak ada tahun ajaran aktif, menampilkan semua siswa</small>
            <?php endif; ?>
        </div>
        <div class="card-body p-4">
            <form method="POST" id="formEditPendidikan">
                <!-- Input hidden untuk menyimpan id_siswa -->
                <input type="hidden" name="id_siswa" value="<?= $data['id_siswa']; ?>">
                
                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="id_siswa_display" class="form-label">Siswa</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_display" name="id_siswa_display" disabled>
                                    <option value="">Pilih Siswa</option>
                                    <?php 
                                    // Reset pointer result siswa
                                    mysqli_data_seek($result_siswa, 0);
                                    while ($siswa = mysqli_fetch_assoc($result_siswa)): 
                                    ?>
                                    <option value="<?= $siswa['id_siswa']; ?>" <?= $siswa['id_siswa'] == $data['id_siswa'] ? 'selected' : ''; ?>>
                                        <?= $siswa['nisn'] . ' - ' . $siswa['nama_lengkap'] . ' (' . $siswa['nis'] . ')'; ?>
                                    </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <small class="form-text text-muted">Data siswa tidak dapat diubah setelah data pendidikan dibuat</small>
                        </div>
                        
                        <div class="mb-3">
                            <label for="asal_sekolah" class="form-label">Asal Sekolah</label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-school"></i></span>
                                <input type="text" class="form-control" id="asal_sekolah" name="asal_sekolah" value="<?= $data['asal_sekolah'] ?: ''; ?>" placeholder="Nama sekolah asal">
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="no_sttb" class="form-label">No. STTB</label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-file-alt"></i></span>
                                <input type="text" class="form-control" id="no_sttb" name="no_sttb" value="<?= $data['no_sttb'] ?: ''; ?>" placeholder="Nomor STTB">
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="tgl_sttb" class="form-label">Tanggal STTB</label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-calendar"></i></span>
                                <input type="date" class="form-control" id="tgl_sttb" name="tgl_sttb" value="<?= $data['tgl_sttb'] ?: ''; ?>">
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="no_skhun" class="form-label">No. SKHUN</label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-file-certificate"></i></span>
                                <input type="text" class="form-control" id="no_skhun" name="no_skhun" value="<?= $data['no_skhun'] ?: ''; ?>" placeholder="Nomor SKHUN">
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="tgl_skhun" class="form-label">Tanggal SKHUN</label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-calendar"></i></span>
                                <input type="date" class="form-control" id="tgl_skhun" name="tgl_skhun" value="<?= $data['tgl_skhun'] ?: ''; ?>">
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="lama_belajar" class="form-label">Lama Belajar</label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-clock"></i></span>
                                <input type="text" class="form-control" id="lama_belajar" name="lama_belajar" value="<?= $data['lama_belajar'] ?: ''; ?>" placeholder="Contoh: 6 tahun">
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="pindahan_dari" class="form-label">Pindahan Dari</label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-exchange-alt"></i></span>
                                <input type="text" class="form-control" id="pindahan_dari" name="pindahan_dari" value="<?= $data['pindahan_dari'] ?: ''; ?>" placeholder="Sekolah sebelumnya">
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="alasan_pindah" class="form-label">Alasan Pindah</label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-comment"></i></span>
                                <textarea class="form-control" id="alasan_pindah" name="alasan_pindah" rows="3" placeholder="Alasan pindah sekolah"><?= $data['alasan_pindah'] ?: ''; ?></textarea>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="diterima_di_kelas" class="form-label">Diterima di Kelas</label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-chalkboard"></i></span>
                                <select class="form-select" id="diterima_di_kelas" name="diterima_di_kelas">
                                    <option value="">Pilih Kelas</option>
                                    <option value="X" <?= $data['diterima_di_kelas'] == 'X' ? 'selected' : ''; ?>>Kelas X</option>
                                    <option value="XI" <?= $data['diterima_di_kelas'] == 'XI' ? 'selected' : ''; ?>>Kelas XI</option>
                                    <option value="XII" <?= $data['diterima_di_kelas'] == 'XII' ? 'selected' : ''; ?>>Kelas XII</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="paket" class="form-label">Paket</label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-book"></i></span>
                                <input type="text" class="form-control" id="paket" name="paket" value="<?= $data['paket'] ?: ''; ?>" placeholder="Paket pendidikan" maxlength="30">
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="tanggal_diterima" class="form-label">Tanggal Diterima <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-calendar-check"></i></span>
                                <input type="date" class="form-control" id="tanggal_diterima" name="tanggal_diterima" required value="<?= $data['tanggal_diterima']; ?>">
                            </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> Simpan Perubahan
                    </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('formEditPendidikan').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 untuk dropdown yang disabled
    $('#id_siswa_display').select2({
        theme: 'bootstrap4',
        placeholder: "Pilih Siswa",
        allowClear: false,
        language: {
            noResults: function() {
                return "Tidak ditemukan";
            },
            searching: function() {
                return "Mencari...";
            }
        }
    });
    
    // Nonaktifkan interaksi dengan Select2
    $('#id_siswa_display').next('.select2-container').css('pointer-events', 'none').css('opacity', '0.7');
});
</script>

<style>
/* Style untuk Select2 */
.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;
}

/* Menyesuaikan tampilan dengan input group */
.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 untuk select yang disabled */
.select2-container--disabled {
    opacity: 0.7;
    pointer-events: none;
}
</style>

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