@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">Manajemen Data Siswa</h4>
            <p class="text-muted small">Daftar siswa SMAN 4 Jember yang terdaftar di sistem.</p>
        </div>
        <a href="{{ route('admin.siswa.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 Siswa
        </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="80">ID</th>
                        <th>Nama Lengkap</th>
                        <th>NISN</th>
                        <th class="text-center">Kelas</th>
                        <th class="text-center" width="150">Opsi</th>
                    </tr>
                </thead>
                <tbody id="siswa-table-body">
                    </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 fetchSiswa(page = 1) {
        const token = localStorage.getItem('access_token');
        const tbody = document.getElementById('siswa-table-body');
        
        tbody.innerHTML = '<tr><td colspan="5" class="text-center py-5">Memuat data...</td></tr>';

        try {
            const response = await fetch(`/api/admin/siswa?page=${page}`, {
                method: 'GET',
                headers: { 
                    'Authorization': 'Bearer ' + token,
                    'Accept': 'application/json'
                }
            });
            const result = await response.json();
            tbody.innerHTML = '';

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

            result.data.forEach((item) => {
                const row = `
                    <tr>
                        <td class="text-center fw-bold text-muted">${item.id_siswa}</td>
                        <td class="fw-bold text-dark">${item.nama_lengkap}</td>
                        <td class="text-muted">${item.nisn}</td>
                        <td class="text-center">
                            <span class="badge rounded-pill badge-kelas">${item.kelas}</span>
                        </td>
                        <td class="text-center">
                            <div class="opsi-wrapper">
                                <a href="/admin/siswa/${item.id}/edit" class="btn-action btn-edit" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <button onclick="deleteSiswa(${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 py-5 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 = () => fetchSiswa(data.current_page - 1);
        controls.appendChild(prevBtn);

        const pageBtn = document.createElement('button');
        pageBtn.className = 'page-link-custom active';
        pageBtn.innerText = data.current_page || 1;
        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 = () => fetchSiswa(data.current_page + 1);
        controls.appendChild(nextBtn);
    }

    async function deleteSiswa(id) {
        Swal.fire({
            title: 'Hapus data?',
            text: "Data akan dihapus permanen!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ef4444',
            confirmButtonText: 'Ya, Hapus'
        }).then(async (result) => {
            if (result.isConfirmed) {
                const token = localStorage.getItem('access_token');
                try {
                    const response = await fetch('/api/admin/siswa/' + id, {
                        method: 'DELETE',
                        headers: { 'Authorization': 'Bearer ' + token, 'Accept': 'application/json' }
                    });
                    if (response.ok) {
                        Swal.fire('Berhasil!', 'Data telah dihapus.', 'success');
                        fetchSiswa(); 
                    }
                } catch (error) { Swal.fire('Error!', 'Koneksi gagal.', 'error'); }
            }
        });
    }

    document.addEventListener('DOMContentLoaded', () => fetchSiswa(1));
</script>
@endsection