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

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

// Ambil data perkembangan - PERBAIKAN QUERY
$query_perkembangan = "SELECT ps.*, s.nisn, s.nama_lengkap, t.tahun_ajaran 
                       FROM bind_perkembangan_siswa ps 
                       JOIN bind_siswa s ON ps.id_siswa = s.id_siswa 
                       JOIN bind_datasiswa ds ON s.id_siswa = ds.id_siswa
                       JOIN bind_tahunajaran t ON ds.id_tahunajaran = t.id_tahunajaran 
                       WHERE ps.id_perkembangan = $id_perkembangan";
$result_perkembangan = mysqli_query($conn, $query_perkembangan);
$perkembangan = mysqli_fetch_assoc($result_perkembangan);

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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Ambil data dari form
    $tanggal_keluar = $_POST['tanggal_keluar'];
    $alasan_keluar = $_POST['alasan_keluar'];
    $lulus = isset($_POST['lulus']) ? 1 : 0;
    $no_ijazah = $_POST['no_ijazah'];
    $tgl_ijazah = $_POST['tgl_ijazah'];
    $no_skhun = $_POST['no_skhun'];
    $tgl_skhun = $_POST['tgl_skhun'];
    
    // Upload foto keluar jika ada perubahan
    $foto_lulus = $perkembangan['foto_lulus'];
    if ($_FILES['foto_lulus']['name']) {
        $target_dir = "../uploads/foto-lulus/";
        if (!is_dir($target_dir)) {
            mkdir($target_dir, 0777, true);
        }
        
        // Hapus foto lama jika ada
        if ($foto_lulus && file_exists($target_dir . $foto_lulus)) {
            unlink($target_dir . $foto_lulus);
        }
        
        $file_extension = pathinfo($_FILES['foto_lulus']['name'], PATHINFO_EXTENSION);
        $foto_lulus = "lulus_" . time() . "." . $file_extension;
        $target_file = $target_dir . $foto_lulus;
        
        move_uploaded_file($_FILES['foto_lulus']['tmp_name'], $target_file);
    }
    
    // Query update
    $sql = "UPDATE bind_perkembangan_siswa SET 
            tanggal_keluar = " . ($tanggal_keluar ? "'$tanggal_keluar'" : "NULL") . ",
            alasan_keluar = '$alasan_keluar',
            lulus = '$lulus',
            no_ijazah = " . ($no_ijazah ? "'$no_ijazah'" : "NULL") . ",
            tgl_ijazah = " . ($tgl_ijazah ? "'$tgl_ijazah'" : "NULL") . ",
            no_skhun = " . ($no_skhun ? "'$no_skhun'" : "NULL") . ",
            tgl_skhun = " . ($tgl_skhun ? "'$tgl_skhun'" : "NULL") . ",
            foto_lulus = " . ($foto_lulus ? "'$foto_lulus'" : "NULL") . "
            WHERE id_perkembangan = $id_perkembangan";
    
    if ($conn->query($sql)) {
        echo "<script>
            Swal.fire({
                icon: 'success',
                title: 'Berhasil',
                text: 'Data perkembangan siswa berhasil diperbarui'
            }).then(() => {
                window.location.href = 'index.php';
            });
        </script>";
    } else {
        echo "<script>
            Swal.fire({
                icon: 'error',
                title: 'Gagal',
                text: 'Terjadi kesalahan: " . $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 Perkembangan Siswa</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-info-circle me-2"></i>Formulir Edit Data Perkembangan Siswa</h5>
        </div>
        <div class="card-body p-4">
            <form method="POST" enctype="multipart/form-data" id="formEditPerkembangan">
                <div class="row mb-4">
                    <div class="col-md-6">
                        <div class="card bg-light">
                            <div class="card-body">
                                <h6 class="card-title text-primary">Informasi Siswa</h6>
                                <p class="mb-1"><strong>NISN:</strong> <?= $perkembangan['nisn'] ?></p>
                                <p class="mb-1"><strong>Nama:</strong> <?= $perkembangan['nama_lengkap'] ?></p>
                                <p class="mb-0"><strong>Tahun Ajaran:</strong> <?= $perkembangan['tahun_ajaran'] ?></p>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="tanggal_keluar" class="form-label">Tanggal Keluar</label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-calendar-times"></i></span>
                                <input type="date" class="form-control" id="tanggal_keluar" name="tanggal_keluar" 
                                       value="<?= $perkembangan['tanggal_keluar'] ?>">
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="alasan_keluar" class="form-label">Alasan Keluar</label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-comment-dots"></i></span>
                                <textarea class="form-control" id="alasan_keluar" name="alasan_keluar" rows="3" 
                                          placeholder="Alasan keluar dari sekolah"><?= $perkembangan['alasan_keluar'] ?></textarea>
                            </div>
                        </div>
                        
                        <div class="mb-3 form-check form-switch">
                            <input type="checkbox" class="form-check-input" id="lulus" name="lulus" value="1" 
                                <?= $perkembangan['lulus'] ? 'checked' : '' ?>>
                            <label class="form-check-label" for="lulus">Siswa Lulus</label>
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="no_ijazah" class="form-label">Nomor Ijazah</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_ijazah" name="no_ijazah" 
                                       value="<?= $perkembangan['no_ijazah'] ?>" placeholder="Nomor ijazah">
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="tgl_ijazah" class="form-label">Tanggal Ijazah</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="tgl_ijazah" name="tgl_ijazah" 
                                       value="<?= $perkembangan['tgl_ijazah'] ?>">
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="no_skhun" class="form-label">Nomor SKHUN</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_skhun" name="no_skhun" 
                                       value="<?= $perkembangan['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-day"></i></span>
                                <input type="date" class="form-control" id="tgl_skhun" name="tgl_skhun" 
                                       value="<?= $perkembangan['tgl_skhun'] ?>">
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="foto_lulus" class="form-label">Foto Keluar/Lulus</label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-camera"></i></span>
                                <input type="file" class="form-control" id="foto_lulus" name="foto_lulus" accept="image/*">
                            </div>
                            <small class="form-text text-muted">Format: JPG, PNG, GIF. Maksimal 2MB</small>
                            
                            <?php if ($perkembangan['foto_lulus']): ?>
                            <div class="mt-2">
                                <img src="../uploads/foto-lulus/<?= $perkembangan['foto_lulus'] ?>" alt="Foto Lulus" 
                                     class="img-thumbnail" style="max-height: 150px;">
                                <div class="form-text">Foto saat ini</div>
                            </div>
                            <?php endif; ?>
                            
                            <div class="mt-2" id="preview-container" style="display: none;">
                                <img id="preview-image" src="#" alt="Preview" class="img-thumbnail mt-2" style="max-height: 150px;">
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="d-flex justify-content-end mt-4">
                    <button type="submit" class="btn btn-success">
                        <i class="fas fa-save me-1"></i> Simpan Perubahan
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Image preview functionality
    const fotoInput = document.getElementById('foto_lulus');
    const previewContainer = document.getElementById('preview-container');
    const previewImage = document.getElementById('preview-image');
    
    fotoInput.addEventListener('change', function() {
        const file = this.files[0];
        if (file) {
            const reader = new FileReader();
            
            reader.addEventListener('load', function() {
                previewImage.setAttribute('src', this.result);
                previewContainer.style.display = 'block';
            });
            
            reader.readAsDataURL(file);
        } else {
            previewContainer.style.display = 'none';
        }
    });
    
    // Form validation before submit
    document.getElementById('formEditPerkembangan').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>

<style>
.card {
    border-radius: 12px;
    overflow: hidden;
}

.card-header {
    border-radius: 12px 12px 0 0 !important;
}

.input-group-text {
    background-color: #f8f9fa;
    border-right: none;
}

.form-control:focus + .input-group-text,
.form-select:focus + .input-group-text {
    border-color: #86b7fe;
}

.btn {
    border-radius: 6px;
    padding: 10px 20px;
    font-weight: 500;
}

.form-label {
    font-weight: 500;
    margin-bottom: 8px;
    color: #495057;
}

.text-danger {
    color: #dc3545 !important;
}
</style>

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