<?= $this->extend('layout/template'); ?>
<?= $this->section('content'); ?>

<nav class="page-breadcrumb">
    <ol class="breadcrumb">
        <li class="breadcrumb-item">Laporan</li>
        <li class="breadcrumb-item active" aria-current="page">Laporan Data <?= $Breadcumb ?></li>
    </ol>
</nav>

<div class="d-flex align-items-center justify-content-between border p-3 rounded flex-wrap gap-3">
    <!-- Filter Tanggal -->
    <form id="filterForm" class="row mb-3">
        <div class="d-flex align-items-center gap-2 flex-wrap">

            <label for="tanggal" class="mb-0">Tanggal Awal</label>
            <div class="input-group flatpickr w-auto" id="flatpickr-date">
                <input type="text" name="tanggal_awal" class="form-control form-control-sm" placeholder="Pilih tanggal" data-input required>
                <span class="input-group-text input-group-addon" data-toggle><i data-feather="calendar"></i></span>
            </div>

            <label for="tanggal" class="mb-0">Tanggal Akhir</label>
            <div class="input-group flatpickr w-auto" id="flatpickr-date">
                <input type="text" name="tanggal_akhir" class="form-control form-control-sm" placeholder="Pilih tanggal" data-input required>
                <span class="input-group-text input-group-addon" data-toggle><i data-feather="calendar"></i></span>
            </div>
            <!-- Tombol Filter -->
            <!-- <button type="button" id="btnFilter" class="btn btn-primary btn-sm">
                <i data-feather="filter"></i> Filter
            </button> -->
        </div>
    </form>


    <!-- Tombol Export -->
    <div class="d-flex gap-2">
        <button type="button" class="btn btn-danger btn-sm" title="Export PDF" onclick="exportPDF()">
            <i class="icon-md" data-feather="file"></i> Print PDF
        </button>
        <button type="button" class="btn btn-success btn-sm" title="Export Excel" onclick="exportExcel()">
            <i class="icon-md" data-feather="file-text"></i> Excel Excel
        </button>
    </div>
</div>

<!-- Data Table -->
<div class="table-responsive">
    <table id="dataTableExample" class="table table-bordered table-hover">
        <thead class="table-info text-dark">
            <tr>
                <th style="width: 5%;">No</th>
                <th>Tanggal Booking</th>
                <th>Customer</th>
                <th>Layanan</th>
                <th>Status</th>
                <th>Harga</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $no = 1;
            $totalHarga = 0;
            ?>
            <?php if (!empty($bookings)): ?>
                <?php foreach ($bookings as $row): ?>
                    <tr>
                        <td><?= $no++ ?></td>
                        <td><?= date('d F Y H:i', strtotime($row['booking_time'])) ?></td>
                        <td><?= esc($row['customer_name']) ?></td>
                        <td><?= esc($row['service_name']) ?></td>
                        <td>
                            <?php if ($row['status'] == 'booked'): ?>
                                <span class="badge bg-warning text-dark">Booked</span>
                            <?php elseif ($row['status'] == 'completed'): ?>
                                <span class="badge bg-success">Completed</span>
                            <?php else: ?>
                                <span class="badge bg-danger">Cancelled</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            Rp <?= number_format($row['price'], 0, ',', '.') ?>
                            <?php $totalHarga += $row['price']; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php else: ?>
                <tr>
                    <td colspan="7" class="text-center" style="background-color: #f9f9f9; color: #888; font-style: italic; padding: 20px;">
                        <i class="fas fa-folder-open" style="font-size: 24px; color: #ccc;"></i>
                        <br>
                        <span style="font-size: 16px; font-weight: bold;">Tidak ada data yang tersedia.</span>
                        <br>
                        <span style="font-size: 14px;">Silakan tambahkan data baru untuk mengisi tabel ini.</span>
                    </td>

                </tr>
            <?php endif; ?>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="5" class="text-right font-weight-bold">Total Harga</td>
                <td><strong>Rp <?= number_format($totalHarga, 0, ',', '.') ?></strong></td>
            </tr>
        </tfoot>
    </table>
</div>

<script>
    $(document).ready(function() {
        function loadData() {
            let tanggal_awal = $('input[name="tanggal_awal"]').val();
            let tanggal_akhir = $('input[name="tanggal_akhir"]').val();

            $.ajax({
                url: "<?= base_url('laporan/filterBookings') ?>",
                type: "POST",
                data: {
                    tanggal_awal: tanggal_awal,
                    tanggal_akhir: tanggal_akhir
                },
                dataType: "json",
                success: function(response) {
                    let tbody = $("#dataTableExample tbody");
                    tbody.empty();

                    let totalHarga = 0;

                    if (response.length > 0) {
                        $.each(response, function(index, row) {
                            let statusBadge = '';
                            if (row.status === 'booked') {
                                statusBadge = `<span class="badge bg-warning text-dark">Booked</span>`;
                            } else if (row.status === 'completed') {
                                statusBadge = `<span class="badge bg-success">Completed</span>`;
                            } else {
                                statusBadge = `<span class="badge bg-danger">Cancelled</span>`;
                            }

                            let harga = parseInt(row.price);
                            totalHarga += harga;

                            let tr = `
                                <tr>
                                    <td>${index + 1}</td>
                                    <td>${new Date(row.booking_time).toLocaleString('id-ID')}</td>
                                    <td>${row.customer_name}</td>
                                    <td>${row.service_name}</td>
                                    <td>${statusBadge}</td>
                                    <td>Rp ${harga.toLocaleString('id-ID')}</td>
                                </tr>
                            `;
                            tbody.append(tr);
                        });

                        $("#dataTableExample tfoot").html(`
                            <tr>
                                <td colspan="5" class="text-end font-weight-bold">Total Harga</td>
                                <td><strong>Rp ${totalHarga.toLocaleString('id-ID')}</strong></td>
                            </tr>
                        `);
                    } else {
                        tbody.append(`
                            <tr>
                                <td colspan="6" class="text-center">
                                    <i class="fas fa-folder-open" style="font-size: 24px; color: #ccc;"></i><br>
                                    <span style="font-size: 16px; font-weight: bold;">Tidak ada data booking.</span>
                                </td>
                            </tr>
                        `);
                        $("#dataTableExample tfoot").html('');
                    }
                },
                error: function(xhr, status, error) {
                    console.error("Error:", error);
                }
            });
        }

        // Trigger saat input tanggal berubah
        $('input[name="tanggal_awal"], input[name="tanggal_akhir"]').on("change", loadData);

        // ✅ Trigger saat tombol filter ditekan
        $('#btnFilter').on('click', loadData);

        // Load data awal saat page pertama kali dibuka
        loadData();
    });
</script>


<!-- untuk script export pdf dan excel -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.25/jspdf.plugin.autotable.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.3/xlsx.full.min.js"></script>

<script>
    function exportPDF() {
        if (!window.jspdf || !window.jspdf.jsPDF) {
            alert("Library jsPDF tidak ditemukan! Coba refresh halaman.");
            return;
        }

        const {
            jsPDF
        } = window.jspdf;
        let doc = new jsPDF('p', 'mm', 'a4');

        // Judul PDF
        doc.setFont("helvetica", "bold");
        doc.setFontSize(16);
        doc.text("Laporan Booking", 14, 15);

        // Header PDF
        let headers = [
            ["No", "Tanggal", "Customer", "Service", "Status", "Harga"]
        ];

        let data = [];
        $("#dataTableExample tbody tr:visible").each(function() {
            let row = [];
            row.push($(this).find("td:eq(0)").text().trim()); // No
            row.push($(this).find("td:eq(1)").text().trim()); // Tanggal
            row.push($(this).find("td:eq(2)").text().trim()); // Customer
            row.push($(this).find("td:eq(3)").text().trim()); // Service
            row.push($(this).find("td:eq(4)").text().trim()); // Status
            row.push($(this).find("td:eq(5)").text().trim()); // Harga
            data.push(row);
        });

        // Ambil total dari footer
        let totalHarga = $("#dataTableExample tfoot td:eq(1)").text().trim();

        if (data.length === 0) {
            alert("Tidak ada data untuk diekspor!");
            return;
        }

        data.push(["", "", "", "Total", "", totalHarga]);

        doc.autoTable({
            head: headers,
            body: data,
            startY: 25,
            styles: {
                fontSize: 10
            },
            theme: 'grid',
            headStyles: {
                fillColor: [22, 160, 133]
            },
            margin: {
                top: 30
            }
        });

        doc.save("Laporan_Booking.pdf");
    }

    function exportExcel() {
        if (typeof XLSX === 'undefined') {
            alert("XLSX tidak ditemukan!");
            return;
        }

        let ws = XLSX.utils.aoa_to_sheet([]);

        let headers = [
            ["No", "Tanggal", "Customer", "Service", "Status", "Harga"]
        ];
        XLSX.utils.sheet_add_aoa(ws, headers, {
            origin: "A1"
        });

        let data = [];
        $("#dataTableExample tbody tr:visible").each(function() {
            let row = [];
            row.push($(this).find("td:eq(0)").text().trim()); // No
            row.push($(this).find("td:eq(1)").text().trim()); // Tanggal
            row.push($(this).find("td:eq(2)").text().trim()); // Customer
            row.push($(this).find("td:eq(3)").text().trim()); // Service
            row.push($(this).find("td:eq(4)").text().trim()); // Status
            row.push($(this).find("td:eq(5)").text().trim()); // Harga
            data.push(row);
        });

        let totalHarga = $("#dataTableExample tfoot td:eq(1)").text().trim();

        if (data.length === 0) {
            alert("Tidak ada data untuk diekspor!");
            return;
        }

        data.push(["", "", "", "Total", "", totalHarga]);

        XLSX.utils.sheet_add_aoa(ws, data, {
            origin: "A2"
        });

        let wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, "Laporan Booking");
        XLSX.writeFile(wb, "Laporan_Booking.xlsx");
    }
</script>


<?= $this->endSection(); ?>