@extends('admin.layout')

@section('content')
<link rel="stylesheet" href="{{ asset('css/fitur-admin.css') }}">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<div class="dashboard-section d-flex justify-content-center">
    <div style="width: 100%; max-width: 700px;">
        <div class="mb-4 text-center">
            <h4 class="fw-bold text-dark">Edit Data Siswa</h4>
            <p id="display_id_siswa" class="text-muted small fw-bold">Memuat data...</p>
        </div>

        <div class="card border-0 shadow-sm rounded-4">
            <div class="card-body p-5">
                <form id="editSiswaForm">
                    <input type="hidden" id="siswa_id_db" value="{{ $id }}">
                    
                    <div class="row g-4">
                        <div class="col-md-12 form-group-custom">
                            <label>Nama Lengkap</label>
                            <input type="text" id="nama_lengkap" class="form-control input-custom" required>
                        </div>
                        
                        <div class="col-md-12 form-group-custom">
                            <label>NISN</label>
                            <input type="text" id="nisn" class="form-control input-custom" required>
                        </div>

                        <div class="col-md-12 form-group-custom">
                            <label>Kelas</label>
                            <input type="text" id="kelas" class="form-control input-custom" required>
                        </div>

                        <div class="col-md-12 form-group-custom">
                            <label>Peminatan</label>
                            <select id="peminatan" class="form-select input-custom">
                                <option value="Saintek">Saintek</option>
                                <option value="Soshum">Soshum</option>
                            </select>
                        </div>
                    </div>

                    <div class="mt-5 d-flex gap-2 justify-content-end">
                        <button type="submit" id="btnUpdate" class="btn text-white px-5 shadow-sm" style="background-color: var(--primary-green); border-radius: 10px;">Perbarui Data</button>
                        <a href="{{ route('admin.siswa') }}" class="btn btn-light px-4" style="border-radius: 10px;">Batal</a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    const dbId = document.getElementById('siswa_id_db').value;

    // Mengambil data lama untuk ditampilkan di form
    async function loadSiswa() {
        try {
            const response = await fetch(`/api/admin/siswa/${dbId}`, {
                headers: { 
                    'Authorization': 'Bearer ' + localStorage.getItem('access_token'),
                    'Accept': 'application/json'
                }
            });
            const result = await response.json();
            if (response.ok) {
                document.getElementById('nama_lengkap').value = result.data.nama_lengkap;
                document.getElementById('nisn').value = result.data.nisn;
                document.getElementById('kelas').value = result.data.kelas;
                document.getElementById('peminatan').value = result.data.peminatan;
                document.getElementById('display_id_siswa').innerText = `EDITING: ${result.data.id_siswa}`;
            } else {
                Swal.fire('Gagal!', 'Data tidak ditemukan.', 'warning');
            }
        } catch (error) { 
            Swal.fire('Error!', 'Gagal mengambil data dari server.', 'error'); 
        }
    }

    // Mengirim data perbaikan ke API
    document.getElementById('editSiswaForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        const btn = document.getElementById('btnUpdate');
        btn.disabled = true;

        const payload = {
            nama_lengkap: document.getElementById('nama_lengkap').value,
            nisn: document.getElementById('nisn').value,
            kelas: document.getElementById('kelas').value,
            peminatan: document.getElementById('peminatan').value
        };

        try {
            const response = await fetch(`/api/admin/siswa/${dbId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer ' + localStorage.getItem('access_token'),
                    'Accept': 'application/json'
                },
                body: JSON.stringify(payload)
            });

            if (response.ok) {
                Swal.fire({ icon: 'success', title: 'Berhasil Diperbarui!', text: 'Data siswa telah diperbarui.', confirmButtonColor: '#2D7A47' })
                .then(() => { window.location.href = "{{ route('admin.siswa') }}"; });
            } else {
                const result = await response.json();
                Swal.fire('Gagal!', result.message || 'Cek inputan.', 'warning');
            }
        } catch (error) { 
            Swal.fire('Error!', 'Kesalahan koneksi server.', 'error'); 
        } finally { 
            btn.disabled = false; 
        }
    });

    // Jalankan load data saat halaman siap
    document.addEventListener('DOMContentLoaded', loadSiswa);
</script>
@endsection