<?php $__env->startSection('content'); ?>
    <style>
        #datatable td,
        #datatable th {
            white-space: nowrap;
            vertical-align: middle;
        }

        @media (max-width: 768px) {
            .btn {
                padding: 0.25rem 0.5rem;
            }
        }
    </style>

    <div class="row mb-3">
        <div class="col-md-6">
            <h2>Data Karyawan</h2>
        </div>

        <div class="col-md-6 text-end">
            <a href="<?php echo e(route('karyawan.create')); ?>" class="btn btn-primary">
                Tambah Karyawan
            </a>
        </div>
    </div>

    <div class="card shadow-sm border-0 rounded-4">

        <div class="card-body">

            <div class="row pb-3 align-items-center g-2">

                <div class="col-12 col-md-auto d-flex gap-2">
                    <div class="dropdown">
                        <button class="btn btn-white btn-sm dropdown-toggle shadow-sm px-3" type="button"
                            data-bs-toggle="dropdown">
                            <i class="bi bi-list-ol me-1 text-secondary"></i>
                            Tampilkan:
                            <span class="baris fw-bold text-primary">10</span>
                        </button>

                        <ul class="dropdown-menu shadow border-0">
                            <li><button class="dropdown-item" onclick="loadPerPage(10)">10 Baris</button></li>
                            <li><button class="dropdown-item" onclick="loadPerPage(25)">25 Baris</button></li>
                            <li><button class="dropdown-item" onclick="loadPerPage(50)">50 Baris</button></li>
                            <li><button class="dropdown-item" onclick="loadPerPage(100)">100 Baris</button></li>
                        </ul>
                    </div>
                </div>
                <div class="col d-none d-md-block"></div>
                <div class="col-12 col-md-4">
                    <div class="input-group input-group-sm shadow-sm">
                        <span class="input-group-text bg-white border-end-0 text-secondary">
                            <i class="bi bi-search"></i>
                        </span>
                        <input type="text" id="searchInput" name="search" class="form-control border-start-0 ps-0"
                            placeholder="Cari data di sini...">
                    </div>
                </div>
            </div>

            <div class="table-responsive">
                <table id="datatable" class="table table-hover table-sm align-middle mb-0">
                    <thead class="table-light">
                        <tr>
                            <th class="d-none d-md-table-cell">No</th>
                            <th>NRP</th>
                            <th>Nama</th>
                            <th class="d-none d-md-table-cell">Jabatan</th>
                            <th class="d-none d-md-table-cell">Departemen</th>
                            <th class="d-none d-md-table-cell text-center">ATR</th>
                            <th class="text-center d-none d-md-table-cell">Aksi</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>

            <nav class="mt-3">
                <ul class="pagination pagination-sm justify-content-end" id="pagination"></ul>
            </nav>

        </div>
    </div>

    <div id="modalContainer"></div>

    <script>
        document.addEventListener("DOMContentLoaded", function() {

            const params = new URLSearchParams(window.location.search);

            let page = parseInt(params.get('page')) || 1;
            let perPage = parseInt(params.get('perPage')) || 10;
            let search = params.get('search') || '';

            let typingTimer;
            const delay = 500;

            $("#searchInput").on("keyup", function() {
                clearTimeout(typingTimer);
                typingTimer = setTimeout(() => {
                    search = this.value;
                    page = 1;
                    loadReport();
                }, delay);
            });

            document.getElementById("searchInput").value = search;
            document.querySelector(".baris").innerText = perPage;

            function formatTanggalPendek(dateString) {
                if (!dateString) return '-';
                const date = new Date(dateString.replace(' ', 'T'));
                return date.toLocaleDateString('id-ID', {
                    day: 'numeric',
                    month: 'short',
                    year: 'numeric'
                });
            }

            window.loadPerPage = function(limit) {
                perPage = limit;
                page = 1;
                document.querySelector(".baris").innerText = limit;
                loadReport();
            };

            window.goPage = function(p) {
                page = p;
                loadReport();
            };

            window.simpanAtr = function(event, karyawanId) {
                event.preventDefault();

                const form = event.target;
                const nilaiAtr = form.querySelector('input[name="nilai_atr"]').value;
                const spinner = document.getElementById(`spinAtr${karyawanId}`);
                const submitBtn = form.querySelector('button[type="submit"]');

                if (spinner) spinner.classList.remove('d-none');
                submitBtn.disabled = true;

                fetch(`<?php echo e(url('/karyawan')); ?>/${karyawanId}/atr`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'
                        },
                        body: JSON.stringify({
                            atr: nilaiAtr
                        })
                    })
                    .then(response => { 
                        if (!response.ok) {
                            return response.text().then(htmlError => { 
                                const parser = new DOMParser();
                                const doc = parser.parseFromString(htmlError, 'text/html');
                                const errorTitle = doc.querySelector('.exception-message, title')
                                    ?.innerText || 'Server Error 500';
                                throw new Error(errorTitle);
                            });
                        }
                        return response.json();
                    })
                    .then(res => {
                        form.reset();
                        $(`#collapseFormAtr${karyawanId}`).collapse('hide');

                        const modalElement = document.getElementById(`modalAtr${karyawanId}`);
                        if (modalElement) {
                            const closeBtn = modalElement.querySelector(
                                '.btn-close, [data-bs-dismiss="modal"]');
                            if (closeBtn) closeBtn.click();
                        }

                        showToast('success', res.message || 'Nilai ATR berhasil ditambahkan!');
                        loadReport();
                    })
                    .catch(err => {
                        console.error(err);
                        alert("Detail Error: " + err.message);
                    })
                    .finally(() => {
                        if (spinner) spinner.classList.add('d-none');
                        submitBtn.disabled = false;
                    });
            };

            window.loadReport = function() {
                const newUrl = `?page=${page}&perPage=${perPage}&search=${search}`;
                window.history.replaceState({}, '', newUrl);

                const url = `<?php echo e(route('karyawan.getData')); ?>?page=${page}&perPage=${perPage}&search=${search}`;

                document.querySelector("#datatable tbody").innerHTML = `
                    <tr>
                        <td colspan="7" class="text-center py-3">
                            Loading...
                        </td>
                    </tr>
                `;
                document.getElementById("modalContainer").innerHTML = '';

                fetch(url)
                    .then(response => response.json())
                    .then(res => {
                        let rows = '';
                        let modals = '';
                        let no = (page - 1) * perPage + 1;
                        let paginationHtml = '';
 
                        let start = Math.max(1, res.current_page - 2);
                        let end = Math.min(res.last_page, res.current_page + 2);

                        for (let i = start; i <= end; i++) {
                            paginationHtml += `
                                <li class="page-item ${i === res.current_page ? 'active' : ''}">
                                    <button class="page-link" onclick="goPage(${i})">${i}</button>
                                </li>
                            `;
                        }
                        document.getElementById("pagination").innerHTML = paginationHtml;
 
                        if (res.data.length === 0) {
                            rows = `
                                <tr>
                                    <td colspan="7" class="text-center text-muted py-3">
                                        Data tidak ditemukan
                                    </td>
                                </tr>
                            `;
                        } else {
                            res.data.forEach(item => {
                                const atrTerbaru = item.atr?.[0] ? parseFloat(item.atr[0]
                                    .nilai_atr) : 0;

                                rows += `
                                    <tr>
                                        <td class="d-none d-md-table-cell">${no++}</td>
                                        <td>
                                            <div class="fw-semibold text-dark">${item.nrp ?? '-'}</div>
                                        </td>
                                        <td>
                                            <div>${item.nama ?? '-'}</div>
                                            <div class="small text-muted d-block d-md-none mt-1">
                                                <div>${item.jabatan?.jabatan ?? '-'}</div>
                                                <div>${item.departemen?.departemen ?? '-'}</div>
                                            </div>
                                            <div class="d-flex gap-1 flex-wrap mt-2 d-md-none">
                                                <button type="button" class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#modalAtr${item.id}">${atrTerbaru}%
                                                </button>
                                                <a href="/karyawan/${item.slug}" class="btn btn-sm btn-info rounded-pill px-3">
                                                    <i class="bi bi-eye"></i>
                                                </a>
                                                <a href="/karyawan/${item.slug}/edit" class="btn btn-sm btn-warning rounded-pill px-3">
                                                    <i class="bi bi-pencil"></i>
                                                </a>
                                                <form action="/karyawan/${item.slug}" method="POST" onsubmit="return confirm('Apakah Anda yakin ingin menghapus data ini?');">
                                                    <input type="hidden" name="_token" value="<?php echo e(csrf_token()); ?>">
                                                    <input type="hidden" name="_method" value="DELETE">
                                                    <button type="submit" class="btn btn-sm btn-danger rounded-pill px-3">
                                                        <i class="bi bi-trash"></i>
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                        <td class="d-none d-md-table-cell">${item.jabatan?.jabatan ?? '-'}</td>
                                        <td class="d-none d-md-table-cell">${item.departemen?.departemen ?? '-'}</td>
                                        <td class="d-none d-md-table-cell text-center">
                                            <button type="button" class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#modalAtr${item.id}">${atrTerbaru}%
                                            </button>
                                        </td>
                                        <td class="text-center d-none d-md-table-cell">
                                            <form action="/karyawan/${item.slug}" method="POST" onsubmit="return confirm('Apakah Anda yakin ingin menghapus data ini?');">
                                                <input type="hidden" name="_token" value="<?php echo e(csrf_token()); ?>">
                                                <input type="hidden" name="_method" value="DELETE">
                                                <div class="d-flex flex-wrap gap-1 justify-content-center">
                                                    <a href="/karyawan/${item.slug}" class="btn btn-sm btn-info">
                                                        <i class="bi bi-eye"></i>
                                                        <span class="d-none d-md-inline ms-1">Detail</span>
                                                    </a>
                                                    <a href="/karyawan/${item.slug}/edit" class="btn btn-sm btn-warning">
                                                        <i class="bi bi-pencil"></i>
                                                        <span class="d-none d-md-inline ms-1">Edit</span>
                                                    </a>
                                                    <button type="submit" class="btn btn-sm btn-danger">
                                                        <i class="bi bi-trash"></i>
                                                        <span class="d-none d-md-inline ms-1">Hapus</span>
                                                    </button>
                                                </div>
                                            </form>
                                        </td>
                                    </tr>
                                `;

                                modals += `
                                    <div class="modal fade" id="modalAtr${item.id}" tabindex="-1" aria-hidden="true">
                                        <div class="modal-dialog modal-dialog-centered">
                                            <div class="modal-content border-0 shadow rounded-4">
                                                <div class="modal-header bg-primary text-white">
                                                    <h5 class="modal-title">ATR - ${item.nama ?? '-'}</h5>
                                                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                                                </div>
                                                <div class="modal-body">
                                                    <div class="text-center mb-4">
                                                        <h2 class="fw-bold text-primary mb-1">${atrTerbaru}%</h2>
                                                        <div class="text-muted small">ATR Terbaru</div>
                                                    </div>

                                                    <div class="mb-3">
                                                        <button class="btn btn-outline-primary btn-sm w-100 fw-semibold" type="button" data-bs-toggle="collapse" data-bs-target="#collapseFormAtr${item.id}">
                                                            <i class="bi bi-plus-circle me-1"></i> Tambah Penilaian ATR
                                                        </button>
                                                    </div>

                                                    <div class="collapse mb-4" id="collapseFormAtr${item.id}">
                                                        <div class="card card-body bg-light border-0 rounded-3 p-3">
                                                            <form onsubmit="simpanAtr(event, ${item.id})">
                                                                <div class="mb-3">
                                                                    <label class="form-label small fw-bold text-secondary">Nilai ATR (%)</label>
                                                                    <div class="input-group input-group-sm">
                                                                        <input type="number" name="nilai_atr" class="form-control" min="0" max="100" required placeholder="Contoh: 85">
                                                                        <span class="input-group-text">%</span>
                                                                    </div>
                                                                </div>
                                                                <div class="d-flex gap-2 justify-content-end">
                                                                    <button type="button" class="btn btn-sm btn-white text-secondary" data-bs-toggle="collapse" data-bs-target="#collapseFormAtr${item.id}">Batal</button>
                                                                    <button type="submit" class="btn btn-sm btn-primary px-3">
                                                                        <span class="spinner-border spinner-border-sm d-none me-1" id="spinAtr${item.id}"></span> Simpan
                                                                    </button>
                                                                </div>
                                                            </form>
                                                        </div>
                                                    </div>

                                                    <div class="fw-bold text-secondary small mb-2"><i class="bi bi-clock-history me-1"></i> Histori Penilaian</div>
                                                    <div style="max-height: 200px; overflow-y: auto;">
                                                        <table class="table table-sm align-middle mb-0">
                                                            <thead class="table-light sticky-top">
                                                                <tr>
                                                                    <th>Tanggal</th>
                                                                    <th class="text-center">Nilai</th>
                                                                </tr>
                                                            </thead>
                                                            <tbody>
                                                                ${
                                                                    item.atr?.length
                                                                    ? item.atr.map(a => `<tr><td>${formatTanggalPendek(a.created_at)}</td><td class="text-center"><span class="badge bg-primary-subtle text-primary border border-primary-subtle">${parseFloat(a.nilai_atr)}%</span></td></tr>`).join('')
                                                                    : `<tr><td colspan="2" class="text-center text-muted py-3 small">Belum ada penilaian</td></tr>`
                                                                }
                                                            </tbody>
                                                        </table>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                `;
                            });
                        }

                        document.querySelector("#datatable tbody").innerHTML = rows;
                        document.getElementById("modalContainer").innerHTML = modals;
                    })
                    .catch(err => {
                        console.error("Error:", err);
                        document.querySelector("#datatable tbody").innerHTML = `
                            <tr>
                                <td colspan="7" class="text-center text-danger py-3">
                                    Gagal memuat data
                                </td>
                            </tr>
                        `;
                    });
            };

            loadReport();
        });
    </script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /home/u544939042/domains/mitracempaka.id/gl-asuh/resources/views/menu/karyawan/index.blade.php ENDPATH**/ ?>