@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">Tambah Data Siswa Baru</h4>
            <p class="text-muted small">Isi data di bawah ini untuk membuat profil siswa sekaligus akun login sistem.</p>
        </div>

        <div class="card border-0 shadow-sm rounded-4">
            <div class="card-body p-5">
                <form id="formCreateSiswa">
                    <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</label>
                            <input type="text" id="username" class="form-control input-custom" placeholder="Contoh: siswabaru12" required>
                        </div>

                        <div class="col-md-6 form-group-custom">
                            <label class="fw-bold small text-muted">Password</label>
                            <input type="password" id="password" class="form-control input-custom" placeholder="Minimal 6 karakter" required>
                        </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" placeholder="Masukkan nama sesuai ijazah/rapor" 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" placeholder="10 Digit nomor NISN" 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="btnSave" class="btn text-white px-5 shadow-sm" style="background-color: var(--primary-green); border-radius: 10px;">
                            Simpan 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') || '';
    }

    function getValue(id) {
        return document.getElementById(id).value.trim();
    }

    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.'
            };
        }
    }

    function formatErrors(errors) {
        if (!errors) return '';
        return Object.values(errors).flat().map(item => String(item)).join('<br>');
    }

    document.getElementById('formCreateSiswa').addEventListener('submit', async function (e) {
        e.preventDefault();
        const token = getToken();

        if (!token) {
            Swal.fire('Sesi Berakhir', 'Silakan login ulang.', 'warning')
                .then(() => window.location.href = LOGIN_URL);
            return;
        }

        const btn = document.getElementById('btnSave');
        btn.disabled = true;
        btn.innerText = 'Menyimpan...';

        const payload = {
            username: getValue('username'),
            password: getValue('password'),
            nama_lengkap: getValue('nama_lengkap'),
            nisn: getValue('nisn'),
            kelas: getValue('kelas')
        };

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

            const result = await parseJsonResponse(response);

            if (response.status === 401 || response.status === 403) {
                Swal.fire('Sesi Berakhir', 'Silakan login ulang.', 'warning')
                    .then(() => window.location.href = LOGIN_URL);
                return;
            }

            if (response.ok && result.success !== false) {
                Swal.fire({
                    icon: 'success',
                    title: 'Berhasil!',
                    text: result.message || 'Data siswa berhasil ditambahkan.',
                    confirmButtonColor: '#2D6A4F'
                }).then(() => {
                    window.location.href = SISWA_INDEX_URL;
                });
            } else {
                Swal.fire({
                    icon: 'warning',
                    title: 'Gagal!',
                    html: formatErrors(result.errors) || result.message || 'Periksa kembali isian Anda.',
                    confirmButtonColor: '#2D6A4F'
                });
            }
        } catch (error) {
            Swal.fire('Error!', error.message || 'Gagal menghubungi server.', 'error');
        } finally {
            btn.disabled = false;
            btn.innerText = 'Simpan Data';
        }
    });
</script>
@endsection