@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="mb-4 d-flex justify-content-between align-items-center">
        <div>
            <h4 class="fw-bold text-dark">Data Master Jurusan</h4>
            <p class="text-muted small">Kelola daftar jurusan kuliah yang tersedia dalam sistem prediksi.</p>
        </div>
        <a href="{{ route('admin.jurusan.create') }}" class="btn text-white px-4 shadow-sm" style="background-color: var(--primary-green); border-radius: 10px;">
            <i class="fas fa-plus me-2"></i>Tambah Jurusan
        </a>
    </div>

    <div class="table-container-modern shadow-sm">
        <div class="table-responsive">
            <table class="table table-modern mb-0">
                <thead>
                    <tr>
                        <th class="text-center" width="60">No</th>
                        <th>Nama Jurusan</th>
                        <th class="text-center">Rumpun</th>
                        <th>Prospek Karir</th>
                        <th class="text-center" width="150">Opsi</th>
                    </tr>
                </thead>
                <tbody id="jurusan-table-body">
                    <tr><td colspan="5" class="text-center py-5 text-muted">Memuat data...</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" id="pagination-controls">
                </div>
        </div>
    </div>
</div>

<script>
    async function fetchJurusan(page = 1) {
        const token = localStorage.getItem('access_token');
        try {
            const response = await fetch(`/api/admin/jurusan?page=${page}`, {
                headers: { 
                    'Authorization': 'Bearer ' + token,
                    'Accept': 'application/json'
                }
            });
            const result = await response.json();
            const tbody = document.getElementById('jurusan-table-body');
            tbody.innerHTML = '';

            if(!result.data || result.data.length === 0) {
                tbody.innerHTML = '<tr><td colspan="5" class="text-center py-4">Tidak ada data jurusan.</td></tr>';
                return;
            }

            result.data.forEach((item, index) => {

            const rumpunClass = item.rumpun.toLowerCase() === 'saintek' ? 'badge-saintek' : 'badge-soshum';

                const row = `
                    <tr>
                        <td class="text-center text-muted">${(result.current_page - 1) * result.per_page + (index + 1)}</td>
                        <td class="fw-bold text-dark text-uppercase">${item.nama_jurusan}</td>
                        <td class="text-center">
                            <span class="badge rounded-pill px-3 py-2 ${rumpunClass}">
                                ${item.rumpun}
                            </span>
                        </td>
                        <td class="small text-muted">${item.prospek_karir || '-'}</td>
                        <td class="text-center">
                            <div class="opsi-wrapper">
                                <a href="/admin/jurusan/${item.id}/edit" class="btn-action btn-edit" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <button onclick="deleteJurusan(${item.id})" class="btn-action btn-delete" title="Hapus">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </td>
                    </tr>`;
                tbody.innerHTML += row;
            });

            document.getElementById('pagination-info').innerText = 
                `Menampilkan ${result.from || 0} sampai ${result.to || 0} dari ${result.total || 0} data`;
            
            renderPagination(result);
        } catch (error) { 
            tbody.innerHTML = '<tr><td colspan="5" class="text-center text-danger">Gagal memuat data.</td></tr>';
        }
    }

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

        const prevBtn = document.createElement('button');
        prevBtn.className = 'page-link-custom';
        prevBtn.innerHTML = '&laquo; Previous';
        prevBtn.disabled = data.current_page === 1;
        prevBtn.onclick = () => fetchJurusan(data.current_page - 1);
        controls.appendChild(prevBtn);

        const pageBtn = document.createElement('button');
        pageBtn.className = 'page-link-custom active';
        pageBtn.innerText = data.current_page;
        controls.appendChild(pageBtn);

        const nextBtn = document.createElement('button');
        nextBtn.className = 'page-link-custom';
        nextBtn.innerHTML = 'Next &raquo;';
        nextBtn.disabled = data.current_page === data.last_page;
        nextBtn.onclick = () => fetchJurusan(data.current_page + 1);
        controls.appendChild(nextBtn);
    }

    async function deleteJurusan(id) {
        const res = await Swal.fire({
            title: 'Hapus data?',
            text: "Data yang dihapus tidak dapat dikembalikan!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ef4444',
            confirmButtonText: 'Ya, Hapus'
        });

        if (res.isConfirmed) {
            const token = localStorage.getItem('access_token');
            try {
                const response = await fetch('/api/admin/jurusan/' + id, { 
                    method: 'DELETE', 
                    headers: { 'Authorization': 'Bearer ' + token } 
                });
                if(response.ok) {
                    Swal.fire('Terhapus!', 'Data berhasil dihapus.', 'success');
                    fetchJurusan();
                }
            } catch (error) { Swal.fire('Error!', 'Koneksi gagal.', 'error'); }
        }
    }
    
    document.addEventListener('DOMContentLoaded', () => fetchJurusan(1));
</script>
@endsection