@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 Profil Siswa</h4>
            <p class="text-muted small">Ubah rincian informasi dan akun profil siswa.</p>
        </div>

        <div class="card border-0 shadow-sm rounded-4">
            <div class="card-body p-5">
                <form id="formEditSiswa">
                    <input type="hidden" id="siswa_id" value="{{ $id }}">

                    <div class="row g-4">
                        
                        <div class="col-12">
                            <div class="text-muted small fw-bold text-uppercase mb-2" style="letter-spacing: 1px;">
                                <i class="fas fa-key me-2"></i>Informasi Akun Login
                            </div>
                            <hr class="mt-0 opacity-25">
                        </div>

                        <div class="col-md-6 form-group-custom">
                            <label class="fw-bold small text-muted">Username Login (Opsional)</label>
                            <input type="text" id="username" class="form-control input-custom" placeholder="Kosongkan jika tidak diubah">
                        </div>

                        <div class="col-md-6 form-group-custom">
                            <label class="fw-bold small text-muted">Password Baru (Opsional)</label>
                            <input type="password" id="password" class="form-control input-custom" placeholder="Kosongkan jika tidak diubah">
                        </div>

                        <div class="col-12 mt-4">
                            <div class="text-muted small fw-bold text-uppercase mb-2" style="letter-spacing: 1px;">
                                <i class="fas fa-user me-2"></i>Data Profil Siswa
                            </div>
                            <hr class="mt-0 opacity-25">
                        </div>

                        <div class="col-md-12 form-group-custom">
                            <label class="fw-bold small text-muted">Nama Lengkap</label>
                            <input type="text" id="nama_lengkap" class="form-control input-custom" required>
                        </div>

                        <div class="col-md-6 form-group-custom">
                            <label class="fw-bold small text-muted">NISN</label>
                            <input type="text" id="nisn" class="form-control input-custom" maxlength="10" required>
                        </div>

                        <div class="col-md-6 form-group-custom">
                            <label class="fw-bold small text-muted">Kelas</label>
                            <select id="kelas" class="form-select input-custom" required>
                                <option value="" disabled selected>Pilih Kelas...</option>
                                <option value="XII MIPA 1">XII MIPA 1</option>
                                <option value="XII MIPA 2">XII MIPA 2</option>
                                <option value="XII MIPA 3">XII MIPA 3</option>
                                <option value="XII MIPA 4">XII MIPA 4</option>
                                <option value="XII IPS 1">XII IPS 1</option>
                                <option value="XII IPS 2">XII IPS 2</option>
                                <option value="XII IPS 3">XII IPS 3</option>
                                <option value="XII IPS 4">XII IPS 4</option>
                                <option value="XII BAHASA">XII BAHASA</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>
    function getAppBaseUrl() {
        const origin = window.location.origin;
        const segments = window.location.pathname.split('/').filter(Boolean);
        const adminIndex = segments.indexOf('admin');
        if (adminIndex > 0) {
            return origin + '/' + segments.slice(0, adminIndex).join('/');
        }
        return origin;
    }

    const APP_BASE_URL = getAppBaseUrl();
    const API_SISWA_URL = `${APP_BASE_URL}/api/admin/siswa`;
    const LOGIN_URL = `${APP_BASE_URL}/login`;
    const SISWA_INDEX_URL = `${APP_BASE_URL}/admin/siswa`;

    function getToken() {
        return localStorage.getItem('access_token') || localStorage.getItem('token') || '';
    }

    async function parseJsonResponse(response) {
        const text = await response.text();
        try {
            return text ? JSON.parse(text) : {};
        } catch (error) {
            return { success: false, message: 'Respon server tidak valid.' };
        }
    }

    document.addEventListener('DOMContentLoaded', async function () {
        const id = document.getElementById('siswa_id').value;
        const token = getToken();

        if (!token) {
            window.location.href = LOGIN_URL;
            return;
        }

        try {
            const response = await fetch(`${API_SISWA_URL}/${id}`, {
                method: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token,
                    'Accept': 'application/json'
                }
            });

            const result = await parseJsonResponse(response);

            if (response.ok && result.success) {
                const s = result.data;
                document.getElementById('nama_lengkap').value = s.nama_lengkap || '';
                document.getElementById('nisn').value = s.nisn || '';
                
                if (s.kelas) {
                    document.getElementById('kelas').value = s.kelas;
                }
                
                if (s.user && s.user.username) {
                    document.getElementById('username').placeholder = `Username saat ini: ${s.user.username}`;
                }
            } else {
                Swal.fire('Gagal!', result.message || 'Gagal memuat rincian data siswa.', 'error');
            }
        } catch (error) {
            Swal.fire('Error!', 'Gagal menghubungi server untuk memuat data.', 'error');
        }
    });

    document.getElementById('formEditSiswa').addEventListener('submit', async function (e) {
        e.preventDefault();
        const id = document.getElementById('siswa_id').value;
        const btn = document.getElementById('btnUpdate');

        btn.disabled = true;
        btn.innerText = 'Memperbarui...';

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

        const passwordInput = document.getElementById('password').value.trim();
        if (passwordInput.length > 0) {
            payload.password = passwordInput;
        }

        const usernameInput = document.getElementById('username').value.trim();
        if (usernameInput.length > 0) {
            payload.username = usernameInput; 
        }

        try {
            const response = await fetch(`${API_SISWA_URL}/${id}`, {
                method: 'PUT',
                headers: {
                    'Authorization': 'Bearer ' + getToken(),
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify(payload)
            });

            const result = await parseJsonResponse(response);

            if (response.ok && result.success !== false) {
                Swal.fire({
                    icon: 'success',
                    title: 'Berhasil Diperbarui!',
                    text: result.message || 'Data siswa berhasil diperbarui.',
                    confirmButtonColor: '#2D7A47'
                }).then(() => {
                    window.location.href = SISWA_INDEX_URL;
                });
            } else {
                Swal.fire({
                    icon: 'warning',
                    title: 'Gagal!',
                    text: result.message || 'Cek kembali rincian data yang Anda ubah.',
                    confirmButtonColor: '#2D7A47'
                });
            }
        } catch (error) {
            Swal.fire('Error!', 'Gagal menghubungi server.', 'error');
        } finally {
            btn.disabled = false;
            btn.innerText = 'Perbarui Data';
        }
    });
</script>
@endsection