<?php $__env->startSection('content'); ?>
    <div class="d-flex justify-content-between align-items-center mb-2   ">
        <div>
            <h2> Data Laporan GL Asuh</h2>
        </div>
    </div>

    <div class="card shadow-sm border-0 rounded-4">
        <div class="card-body">
            <div class="row align-items-center mb-4">
                <div class="col-12 col-sm-10 d-flex justify-content-start align-items-center">
                    <!-- Grup Navigasi Tanggal -->
                    <div class="btn-group shadow-sm" role="group" aria-label="Date Navigation">
                        <!-- Tombol Prev -->
                        <button type="button" id="prevDate" class="btn btn-white border-end px-3 py-2" title="Sebelumnya">
                            <i class="bi bi-chevron-left fw-bold text-primary"></i>
                        </button>

                        <!-- Tombol Display Tanggal -->
                        <button type="button" class="btn btn-white px-4 py-2 d-flex align-items-center"
                            data-bs-toggle="modal" data-bs-target="#ModalFilter">
                            <i class="bi bi-calendar3 me-2 text-secondary"></i>
                            <span class="date-display fw-bold text-dark" id="dateDisplay" style="font-size: 1.1rem;">
                                <!-- Tanggal muncul di sini -->
                                Pilih Tanggal
                            </span>
                        </button>

                        <!-- Tombol Next -->
                        <button type="button" id="nextDate" class="btn btn-white border-start px-3 py-2"
                            title="Selanjutnya">
                            <i class="bi bi-chevron-right fw-bold text-primary"></i>
                        </button>
                    </div>
                </div>
            </div>

            <div class="row pb-3 align-items-center g-2">
                <!-- Kontrol Tampilkan Baris & Export -->
                <div class="col-12 col-md-auto d-flex gap-2">
                    <!-- Per page -->
                    <div class="dropdown">
                        <button class="btn btn-white btn-sm dropdown-toggle shadow-sm px-3" type="button"
                            data-bs-toggle="dropdown" aria-expanded="false">
                            <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>

                    <!-- Export Excel -->
                    <button class="btn btn-outline-success btn-sm shadow-sm px-3 d-flex align-items-center"
                        onclick="printExcel()">
                        <i class="bi bi-file-earmark-excel-fill me-1"></i>
                        <span>Excel</span>
                    </button>
                </div>

                <!-- Spasi Pemisah (Hanya muncul di Desktop) -->
                <div class="col d-none d-md-block"></div>

                <!-- Search Input -->
                <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>


            <!-- TABLE -->
            <div class="table-responsive">
                <table id="datatable" class="table table-hover align-middle mb-0">

                    <thead class="table-light">
                        <tr class="text-muted small text-uppercase">
                            <th>#</th>
                            <th>Tanggal</th>
                            <th>Nama GL</th>
                            <th class="d-none d-md-table-cell">Departemen</th>
                            <th class="d-none d-md-table-cell">Plant</th>
                            <th>Manpower</th>
                            <th class="text-center">Aksi</th>
                        </tr>
                    </thead>

                    <tbody></tbody>
                </table>
            </div>

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

        </div>
    </div>

    <!-- MODAL -->
    <div class="modal fade" id="ModalFilter" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content p-3 rounded-4 border-0 shadow">

                <div class="modal-header border-0">
                    <h5 class="modal-title fw-semibold">Pilih Bulan & Tahun</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>

                <div class="modal-body">

                    <!-- Tahun -->
                    <select id="tahunPicker" class="form-select mb-3">
                        <?php for($t = date('Y') - 5; $t <= date('Y') + 2; $t++): ?>
                            <option value="<?php echo e($t); ?>" <?php echo e($t == date('Y') ? 'selected' : ''); ?>>
                                <?php echo e($t); ?>

                            </option>
                        <?php endfor; ?>
                    </select>

                    <!-- Bulan -->
                    <div class="d-flex flex-wrap justify-content-center">
                        <?php $__currentLoopData = ['Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $i => $b): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <button type="button" class="btn btn-outline-primary m-1 pilih-bulan"
                                data-bulan="<?php echo e($i + 1); ?>">
                                <?php echo e($b); ?>

                            </button>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </div>

                </div>

            </div>
        </div>
    </div>
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            const params = new URLSearchParams(window.location.search);
            let today = new Date();
            let bulan = parseInt(params.get('bulan')) || (new Date().getMonth() + 1);
            let tahun = parseInt(params.get('tahun')) || (new Date().getFullYear());

            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(bulan, tahun);
                }, 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'
                });
            }

            $("#tahunPicker").val(tahun);

            function updateDateDisplay(b, t) {
                const monthNames = [
                    'Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni',
                    'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'
                ];
                $('#dateDisplay').text(monthNames[b - 1] + ' ' + t);
            }

            window.loadPerPage = function(limit) {
                perPage = limit;
                page = 1; // reset ke halaman pertama

                document.querySelector(".baris").innerText = limit;

                loadReport(bulan, tahun);
            };

            window.loadReport = function(b, t) {
                bulan = b;
                tahun = t;

                const newUrl = `?bulan=${b}&tahun=${t}&page=${page}&perPage=${perPage}&search=${search}`;
                window.history.replaceState({}, '', newUrl);

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

                // loading state
                document.querySelector("#datatable tbody").innerHTML = `
                    <tr>
                        <td colspan="7" class="text-center">Loading...</td>
                    </tr>
                `;

                fetch(url)
                    .then(response => response.json())
                    .then(res => {
                        let rows = '';
                        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">
                                        Data tidak ditemukan
                                    </td>
                                </tr>
                            `;
                        } else {
                            res.data.forEach(item => {
                                rows += `
                            <tr>
                                <td>${no++}</td>
                                <td>${formatTanggalPendek(item.tanggal)}</td>
                                <td>${item.gl?.nama ?? '-'}</td>
                                <td>${item.departemen ?? '-'}</td>
                                <td>${item.plant ?? '-'}</td>
                                <td>${item.manpower?.nama ?? '-'}</td>
                                <td class="text-center">
                                    <a href="/laporan/${item.id}" class="btn btn-sm btn-outline-primary">
                                        <i class="fas fa-eye me-1"></i> Detail
                                    </a>
                                </td>
                            </tr>
                        `;
                            });
                        }

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

                updateDateDisplay(b, t);
                const modalEl = document.getElementById('ModalFilter');
                const modal = bootstrap.Modal.getInstance(modalEl);
                if (modal) modal.hide();
            };

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

            $("#prevDate").on("click", function() {
                bulan--;
                if (bulan < 1) {
                    bulan = 12;
                    tahun--;
                }
                page = 1;
                loadReport(bulan, tahun);
            });

            $("#nextDate").on("click", function() {
                bulan++;
                if (bulan > 12) {
                    bulan = 1;
                    tahun++;
                }
                page = 1;
                loadReport(bulan, tahun);
            });

            $(document).on("click", ".pilih-bulan", function() {
                $(".pilih-bulan").removeClass("active");
                $(this).addClass("active");

                let pilihBulan = $(this).data("bulan");
                let pilihTahun = $("#tahunPicker").val();
                page = 1;
                loadReport(pilihBulan, pilihTahun);
            });

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

                const bulan = params.get('bulan') || '';
                const tahun = params.get('tahun') || '';

                window.location.href = `<?php echo e(route('laporan.export')); ?>?bulan=${bulan}&tahun=${tahun}`;
            };

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

<?php echo $__env->make('layouts/app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\laragon\www\gl-asuh\resources\views/menu/laporan/index.blade.php ENDPATH**/ ?>