@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 Guru BK Baru</h4>
            <p class="text-muted small">Daftarkan akun guru pembimbing baru beserta akun login sistem.</p>
        </div>

        <div class="card border-0 shadow-sm rounded-4">
            <div class="card-body p-5">
                <form id="formCreateGuru">
                    <div class="row g-4">
                        <div class="col-md-12">
                            <h6 class="fw-bold text-success border-bottom pb-2 mb-3"><i class="fas fa-user-tie me-2"></i>Data Profil Guru</h6>
                        </div>

                        <div class="col-md-12 form-group-custom">
                            <label class="fw-bold small text-muted">Nama Lengkap & Gelar</label>
                            <input type="text" id="nama_guru" class="form-control input-custom" placeholder="Contoh: Dra. Endang Sri, M.Pd" required>
                        </div>

                        <div class="col-md-12 mt-4">
                            <h6 class="fw-bold text-success border-bottom pb-2 mb-3"><i class="fas fa-key me-2"></i>Akun Akses Login Guru</h6>
                        </div>

                        <div class="col-md-6 form-group-custom">
                            <label class="fw-bold small text-muted">Username Akses</label>
                            <input type="text" id="username" class="form-control input-custom" placeholder="Contoh: endangbk" required>
                        </div>

                        <div class="col-md-6 form-group-custom">
                            <label class="fw-bold small text-muted">Email Guru</label>
                            <input type="email" id="email" class="form-control input-custom" placeholder="Contoh: endang@sman4jember.sch.id" required>
                        </div>

                        <div class="col-md-12 form-group-custom">
                            <label class="fw-bold small text-muted">Password Akun</label>
                            <input type="password" id="password" class="form-control input-custom" placeholder="Sandi rahasia minimal 6 karakter" required>
                        </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;">
                            Daftarkan Guru & Akun
                        </button>

                        <a href="{{ route('admin.guru') }}" class="btn btn-light px-4" style="border-radius: 10px;">
                            Batal
                        </a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    // Meniru Persis Logika Penentu URL Prospek Kerja
    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_GURU_URL = `${APP_BASE_URL}/api/admin/guru`;
    const LOGIN_URL = `${APP_BASE_URL}/login`;
    const GURU_INDEX_URL = `${APP_BASE_URL}/admin/guru`;

    function getToken() {
        return localStorage.getItem('access_token') ||
            localStorage.getItem('token') ||
            sessionStorage.getItem('access_token') ||
            sessionStorage.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: text || response.statusText || 'Respon server tidak valid.'
            };
        }
    }

    function formatErrors(errors) {
        if (!errors) return '';

        return Object.values(errors)
            .flat()
            .map(item => String(item))
            .join('<br>');
    }

    // Meniru Persis Logika Submit Event Prospek Kerja
    document.getElementById('formCreateGuru').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 = {
            nama_guru: getValue('nama_guru'),
            username: getValue('username'),
            email: getValue('email'),
            password: document.getElementById('password').value
        };

        try {
            const response = await fetch(API_GURU_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 guru dan akun login berhasil disimpan.',
                    confirmButtonColor: '#2D6A4F'
                }).then(() => {
                    window.location.href = GURU_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 = 'Daftarkan Guru & Akun';
        }
    });
</script>
@endsection