@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 Prospek Kerja</h4>
            <p class="text-muted small">Ubah informasi profesi atau estimasi gaji.</p>
        </div>

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

                    <div class="row g-4">
                        <div class="col-md-12 form-group-custom">
                            <label class="fw-bold small text-muted">Kaitkan dengan Jurusan</label>
                            <select id="jurusan_id" class="form-select input-custom" required>
                                <option value="" disabled>Memuat daftar jurusan...</option>
                            </select>
                        </div>

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

                        <div class="col-md-12 form-group-custom">
                            <label class="fw-bold small text-muted">Range Gaji</label>
                            <input type="text" id="range_gaji" class="form-control input-custom">
                        </div>

                        <div class="col-md-12 form-group-custom">
                            <label class="fw-bold small text-muted">Deskripsi Pekerjaan</label>
                            <textarea id="deskripsi_pekerjaan" class="form-control input-custom" rows="3"></textarea>
                        </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.prospek-kerja') }}" 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_PROSPEK_URL = `${APP_BASE_URL}/api/admin/prospek-kerja`;
    const API_JURUSAN_URL = `${APP_BASE_URL}/api/admin/jurusan`;
    const LOGIN_URL = `${APP_BASE_URL}/login`;
    const PROSPEK_INDEX_URL = `${APP_BASE_URL}/admin/prospek-kerja`;
    const prospekId = document.getElementById('prospek_id').value;

    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();
    }

    function escapeHtml(value) {
        if (value === null || value === undefined || value === '') return '-';

        return String(value)
            .replaceAll('&', '&amp;')
            .replaceAll('<', '&lt;')
            .replaceAll('>', '&gt;')
            .replaceAll('"', '&quot;')
            .replaceAll("'", '&#039;');
    }

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

    async function loadJurusanOptions(selectedId = '') {
        const token = getToken();
        const select = document.getElementById('jurusan_id');

        const response = await fetch(`${API_JURUSAN_URL}?per_page=100`, {
            method: 'GET',
            headers: {
                'Authorization': 'Bearer ' + token,
                'Accept': 'application/json'
            }
        });

        const result = await parseJsonResponse(response);

        select.innerHTML = '<option value="" disabled>Pilih Jurusan Terkait...</option>';

        if (response.status === 401 || response.status === 403) {
            window.location.href = LOGIN_URL;
            return;
        }

        if (!response.ok || result.success === false) {
            throw new Error(result.message || 'Gagal memuat data jurusan.');
        }

        const data = result.data || [];

        if (data.length === 0) {
            select.innerHTML = '<option value="" disabled>Belum ada data jurusan</option>';
            return;
        }

        data.forEach(item => {
            const selected = String(item.id) === String(selectedId) ? 'selected' : '';
            select.innerHTML += `<option value="${escapeHtml(item.id)}" ${selected}>${escapeHtml(item.nama_jurusan)}</option>`;
        });
    }

    async function loadJurusanAndData() {
        const token = getToken();

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

        try {
            const resProspek = await fetch(`${API_PROSPEK_URL}/${encodeURIComponent(prospekId)}`, {
                method: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token,
                    'Accept': 'application/json'
                }
            });

            const resultProspek = await parseJsonResponse(resProspek);

            if (resProspek.status === 401 || resProspek.status === 403) {
                window.location.href = LOGIN_URL;
                return;
            }

            if (!resProspek.ok || resultProspek.success === false || !resultProspek.data) {
                throw new Error(resultProspek.message || 'Data prospek kerja tidak ditemukan.');
            }

            await loadJurusanOptions(resultProspek.data.jurusan_id);

            document.getElementById('jurusan_id').value = resultProspek.data.jurusan_id || '';
            document.getElementById('nama_profesi').value = resultProspek.data.nama_profesi || '';
            document.getElementById('range_gaji').value = resultProspek.data.range_gaji || '';
            document.getElementById('deskripsi_pekerjaan').value = resultProspek.data.deskripsi_pekerjaan || '';

        } catch (error) {
            Swal.fire('Error!', error.message || 'Gagal memuat data prospek kerja.', 'error');
        }
    }

    document.getElementById('formEditProspek').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('btnUpdate');
        btn.disabled = true;
        btn.innerText = 'Memperbarui...';

        const payload = {
            jurusan_id: getValue('jurusan_id'),
            nama_profesi: getValue('nama_profesi'),
            range_gaji: getValue('range_gaji'),
            deskripsi_pekerjaan: getValue('deskripsi_pekerjaan')
        };

        try {
            const response = await fetch(`${API_PROSPEK_URL}/${encodeURIComponent(prospekId)}`, {
                method: 'PUT',
                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 Diperbarui!',
                    text: result.message || 'Data prospek kerja berhasil diperbarui.',
                    confirmButtonColor: '#2D6A4F'
                }).then(() => {
                    window.location.href = PROSPEK_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 koneksi ke server.', 'error');
        } finally {
            btn.disabled = false;
            btn.innerText = 'Perbarui Data';
        }
    });

    document.addEventListener('DOMContentLoaded', loadJurusanAndData);
</script>
@endsection