@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">
    <div class="master-page-header">
        <div>
            <h4 class="master-page-title">Data Master Prospek Kerja</h4>
            <p class="master-page-subtitle">Kelola daftar karir dan estimasi gaji untuk setiap jurusan.</p>
        </div>

        <a href="{{ route('admin.prospek-kerja.create') }}" class="btn-add-modern">
            <i class="fas fa-plus"></i>
            Tambah Prospek
        </a>
    </div>

    <div class="table-container-modern shadow-sm">
        <div class="table-toolbar">
            <div class="search-wrapper-modern">
                <i class="fas fa-search"></i>
                <input type="text" id="searchInput" class="search-input-modern" placeholder="Cari profesi, jurusan, atau estimasi gaji...">
            </div>

            <div class="per-page-wrapper">
                <span>Tampilkan</span>
                <select id="perPageSelect" class="per-page-select">
                    <option value="7" selected>7 data</option>
                    <option value="5">5 data</option>
                </select>
            </div>
        </div>

        <div class="table-responsive">
            <table class="table table-modern mb-0">
                <thead>
                    <tr>
                        <th class="text-center" width="70">No</th>
                        <th>Nama Profesi</th>
                        <th>Asal Jurusan</th>
                        <th>Estimasi Gaji</th>
                        <th class="text-center" width="150">Opsi</th>
                    </tr>
                </thead>

                <tbody id="prospek-table-body">
                    <tr>
                        <td colspan="5" class="loading-state-modern">
                            <i class="fas fa-spinner fa-spin me-2"></i> Memuat data prospek kerja...
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <div class="pagination-container">
            <div class="text-muted small" id="pagination-info">
                Menampilkan 0 sampai 0 dari 0 data
            </div>

            <div class="d-flex gap-1 flex-wrap" id="pagination-controls"></div>
        </div>
    </div>
</div>

<script>
    const API_PROSPEK_URL = @json(url('/api/admin/prospek-kerja'));
    const LOGIN_URL = @json(url('/login'));
    const PROSPEK_EDIT_BASE_URL = @json(url('/admin/prospek-kerja'));

    let currentPage = 1;
    let currentSearch = '';
    let perPage = 7;
    let searchTimer = null;

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

    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 showLoading() {
        document.getElementById('prospek-table-body').innerHTML = `
            <tr>
                <td colspan="5" class="loading-state-modern">
                    <i class="fas fa-spinner fa-spin me-2"></i> Memuat data prospek kerja...
                </td>
            </tr>
        `;
    }

    async function fetchProspek(page = 1) {
        const token = getToken();
        const tbody = document.getElementById('prospek-table-body');

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

        currentPage = page;
        showLoading();

        const params = new URLSearchParams({
            page: page,
            per_page: perPage
        });

        if (currentSearch !== '') {
            params.append('search', currentSearch);
        }

        try {
            const response = await fetch(`${API_PROSPEK_URL}?${params.toString()}`, {
                method: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token,
                    'Accept': 'application/json'
                }
            });

            const result = await parseJsonResponse(response);

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

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

            const data = result.data || [];
            tbody.innerHTML = '';

            if (data.length === 0) {
                tbody.innerHTML = `
                    <tr>
                        <td colspan="5" class="empty-state-modern">
                            <i class="fas fa-folder-open"></i>
                            Tidak ada data prospek kerja yang ditemukan.
                        </td>
                    </tr>
                `;

                updatePaginationInfo(null);
                renderPagination({ current_page: 1, last_page: 1, total: 0 });
                return;
            }

            data.forEach((item, index) => {
                const namaJurusan = item.jurusan ? escapeHtml(item.jurusan.nama_jurusan) : 'Jurusan Dihapus';
                const editUrl = `${PROSPEK_EDIT_BASE_URL}/${encodeURIComponent(item.id)}/edit`;

                tbody.innerHTML += `
                    <tr>
                        <td class="text-center text-muted fw-bold">${(result.from || 1) + index}</td>

                        <td>
                            <div class="table-user-cell">
                                <div class="avatar-circle blue">
                                    <i class="fas fa-briefcase"></i>
                                </div>

                                <div>
                                    <div class="fw-bold text-dark">${escapeHtml(item.nama_profesi)}</div>
                                    <div class="text-cell-muted">Prospek kerja</div>
                                </div>
                            </div>
                        </td>

                        <td>
                            <span class="badge-soft badge-result">${namaJurusan}</span>
                        </td>

                        <td class="fw-bold text-success">${escapeHtml(item.range_gaji || 'Belum diatur')}</td>

                        <td class="text-center">
                            <div class="opsi-wrapper">
                                <a href="${editUrl}" class="btn-action btn-edit" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </a>

                                <button type="button" onclick="deleteProspek(${item.id})" class="btn-action btn-delete" title="Hapus">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                `;
            });

            updatePaginationInfo(result);
            renderPagination(result);

        } catch (error) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="5" class="empty-state-modern text-danger">
                        <i class="fas fa-exclamation-circle"></i>
                        ${escapeHtml(error.message || 'Gagal memuat data prospek kerja.')}
                    </td>
                </tr>
            `;
        }
    }

    function updatePaginationInfo(data) {
        const info = document.getElementById('pagination-info');

        if (!data || !data.total) {
            info.innerText = 'Menampilkan 0 sampai 0 dari 0 data';
            return;
        }

        info.innerText = `Menampilkan ${data.from || 0} sampai ${data.to || 0} dari ${data.total || 0} data`;
    }

    function renderPagination(data) {
        const controls = document.getElementById('pagination-controls');
        controls.innerHTML = '';

        const current = Number(data.current_page || 1);
        const last = Number(data.last_page || 1);
        const total = Number(data.total || 0);

        if (total === 0) return;

        const createButton = (label, page, disabled = false, active = false) => {
            const btn = document.createElement('button');
            btn.className = `page-link-custom ${active ? 'active' : ''}`;
            btn.innerHTML = label;
            btn.disabled = disabled;

            btn.onclick = () => {
                if (!disabled && !active) fetchProspek(page);
            };

            return btn;
        };

        controls.appendChild(createButton('<i class="fas fa-chevron-left"></i>', current - 1, current === 1));

        let pages = [];

        if (last <= 5) {
            for (let i = 1; i <= last; i++) {
                pages.push(i);
            }
        } else {
            pages.push(1);

            if (current > 3) {
                pages.push('...');
            }

            const start = Math.max(2, current - 1);
            const end = Math.min(last - 1, current + 1);

            for (let i = start; i <= end; i++) {
                pages.push(i);
            }

            if (current < last - 2) {
                pages.push('...');
            }

            pages.push(last);
        }

        pages.forEach(page => {
            if (page === '...') {
                controls.appendChild(createButton('...', current, true));
            } else {
                controls.appendChild(createButton(page, page, false, page === current));
            }
        });

        controls.appendChild(createButton('<i class="fas fa-chevron-right"></i>', current + 1, current === last));
    }

    async function deleteProspek(id) {
        const result = await Swal.fire({
            title: 'Hapus data?',
            text: 'Data prospek kerja yang dihapus tidak dapat dikembalikan!',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ef4444',
            cancelButtonColor: '#64748b',
            confirmButtonText: 'Ya, Hapus',
            cancelButtonText: 'Batal'
        });

        if (!result.isConfirmed) return;

        const token = getToken();

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

            const resultDelete = await parseJsonResponse(response);

            if (response.ok && resultDelete.success !== false) {
                Swal.fire('Terhapus!', resultDelete.message || 'Data prospek kerja berhasil dihapus.', 'success');
                fetchProspek(currentPage);
            } else {
                Swal.fire('Gagal!', resultDelete.message || 'Data prospek kerja gagal dihapus.', 'error');
            }
        } catch (error) {
            Swal.fire('Error!', error.message || 'Koneksi ke server gagal.', 'error');
        }
    }

    document.addEventListener('DOMContentLoaded', function () {
        fetchProspek(1);

        document.getElementById('searchInput').addEventListener('input', function () {
            clearTimeout(searchTimer);

            searchTimer = setTimeout(() => {
                currentSearch = this.value.trim();
                fetchProspek(1);
            }, 350);
        });

        document.getElementById('perPageSelect').addEventListener('change', function () {
            perPage = this.value;
            fetchProspek(1);
        });
    });
</script>
@endsection