<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Teh Tarik 99 - Riwayat Transaksi</title>
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
    
    <style>
        body { font-family: 'Poppins', sans-serif; background-color: #ffffff; color: #000; margin: 0; overflow: hidden; }
        .main-wrapper { display: flex; height: 100vh; }

        /* SIDEBAR */
        .sidebar { width: 220px; border-right: 1px solid #e0e0e0; display: flex; flex-direction: column; padding: 30px 0; }
        .brand { padding: 0 25px 40px; font-weight: 800; font-size: 1.5rem; }
        .nav-link-custom { padding: 12px 25px; display: flex; align-items: center; text-decoration: none; color: #333; font-weight: 500; font-size: 0.95rem; }
        .nav-link-custom i { width: 30px; font-size: 1.2rem; }
        .nav-link-custom.active { background-color: #448b39; color: white; border-radius: 0 12px 12px 0; margin-right: 15px; }

        /* CONTENT AREA */
        .content-area { flex: 1; display: flex; flex-direction: column; }
        .top-header { padding: 15px 30px; border-bottom: 1px solid #f0f0f0; display: flex; justify-content: space-between; align-items: center; }
        .search-bar { background-color: #e9e9e9; border: none; border-radius: 6px; padding: 10px 15px; width: 400px; font-size: 0.85rem; }

        .main-scroll { padding: 40px; overflow-y: auto; flex: 1; }

        /* STATS CARDS */
        .stat-card { border: none; border-radius: 20px; padding: 25px; height: 160px; box-shadow: 0 4px 15px rgba(0,0,0,0.02); }
        .card-income { background-color: #fff1e6; } 
        .card-orders { background-color: #e0f2f1; } 
        .card-cups { background-color: #f1f8e9; }   
        
        .card-label { font-size: 0.85rem; font-weight: 700; display: flex; align-items: center; gap: 10px; margin-bottom: 15px; }
        .card-value { font-size: 1.8rem; font-weight: 800; }

        /* TABLE TRANSAKSI */
        .table-container { background: white; border-radius: 25px; padding: 30px; margin-top: 40px; border: 1px solid #f5f5f5; }
        .table thead th { border: none !important; color: #999; font-weight: 600; font-size: 0.8rem; padding-bottom: 20px !important; text-transform: uppercase; }
        .table tbody td { vertical-align: middle; padding: 18px 0; border-bottom: 1px solid #fcfcfc; font-size: 0.85rem; }

        .status-badge { padding: 6px 14px; border-radius: 8px; font-weight: 700; font-size: 0.75rem; }
        .bg-success-subtle { background-color: #e8f5e9; color: #2e7d32; }

        .btn-export { background-color: #448b39; color: white; border: none; border-radius: 8px; padding: 8px 18px; font-size: 0.8rem; font-weight: 600; }
        .date-filter { background-color: #f5f5f5; border: none; border-radius: 8px; padding: 8px 15px; font-size: 0.8rem; font-weight: 600; color: #666; }
    </style>
</head>
<body>

<?php
    // Ambil semua data transaksi dari awal agar pencarian filter kalender Javascript DataTables bekerja 100%
    $transaksiSemua = \App\Models\Transaksi::with('details')->orderBy('created_at', 'desc')->get();

    // Hitung ringkasan hari ini untuk tampilan default awal kartu atas
    $hariIni = date('Y-m-d');
    $transaksiHariIni = $transaksiSemua->filter(function($item) use ($hariIni) {
        return date('Y-m-d', strtotime($item->created_at)) === $hariIni;
    });

    $totalPendapatanHariIni = $transaksiHariIni->sum('total_harga');
    $totalTransaksiHariIni = $transaksiHariIni->count();
    $totalCupHariIni = 0;
    foreach($transaksiHariIni as $t) {
        $totalCupHariIni += $t->details->sum('qty');
    }
?>

<div class="main-wrapper">
    <div class="sidebar">
        <div class="brand">Teh Tarik 99</div>
        <nav class="flex-grow-1">
            <a href="<?php echo e(route('kasir.dashboard')); ?>" class="nav-link-custom <?php echo e(request()->is('kasir/dashboard') ? 'active' : ''); ?>">
                <i class="fa-solid fa-table-cells-large"></i> Dashboard
            </a>
            <a href="<?php echo e(route('kasir.transaksi')); ?>" class="nav-link-custom <?php echo e(request()->is('kasir/transaksi') ? 'active' : ''); ?>">
                <i class="fa-solid fa-receipt"></i> Riwayat
            </a>
            <a href="<?php echo e(route('kasir.laporan')); ?>" class="nav-link-custom <?php echo e(request()->is('kasir/laporan') ? 'active' : ''); ?>">
                <i class="fa-solid fa-chart-simple"></i> Laporan
            </a>
            <a href="<?php echo e(route('kasir.stok')); ?>" class="nav-link-custom <?php echo e(request()->is('kasir/stok') ? 'active' : ''); ?>">
                <i class="fa-solid fa-calendar-days"></i> Stok
            </a>
        </nav>
        <div class="mt-auto">
            <a href="#" class="nav-link-custom"><i class="fa-regular fa-circle-user"></i> Profil</a>
            <form action="<?php echo e(route('logout')); ?>" method="POST">
                <?php echo csrf_field(); ?>
                <button type="submit" class="nav-link-custom border-0 bg-transparent text-danger w-100 text-start">
                    <i class="fa-solid fa-arrow-right-from-bracket"></i> Keluar
                </button>
            </form>
        </div>
    </div>

    <div class="content-area">
        <div class="top-header">
            <input type="text" id="inputSearch" class="search-bar" placeholder="cari info riwayat...">
            <div class="user-panel d-flex align-items-center gap-3">
                <i class="fa-solid fa-bell fs-5"></i>
                <div class="text-end" style="line-height: 1.2;">
                    <div class="fw-bold small"><?php echo e(auth()->user()->name); ?></div>
                    <div class="text-muted" style="font-size: 0.7rem;">Kasir</div>
                </div>
                <img src="https://ui-avatars.com/api/?name=<?php echo e(urlencode(auth()->user()->name)); ?>&background=448b39&color=fff" class="user-avatar" style="width: 35px; height: 35px; border-radius: 50%;">
            </div>
        </div>

        <div class="main-scroll">
            <div class="d-flex justify-content-between align-items-start mb-4">
                <div>
                    <h2 class="fw-bold m-0">Riwayat</h2>
                    <p class="text-muted small m-0" id="header-date">Memuat...</p>
                </div>
                <div class="d-flex gap-2">
                    <input type="date" id="filterTanggal" class="date-filter" value="<?php echo e(date('Y-m-d')); ?>">
                    
                </div>
            </div>

            <div class="row g-4">
                <div class="col-md-4">
                    <div class="stat-card card-income">
                        <div class="card-label"><i class="fa-solid fa-wallet"></i> PENDAPATAN HARI INI</div>
                        <div class="card-value" id="box-pendapatan">
                            Rp. <?php echo e(number_format($totalPendapatanHariIni, 0, ',', '.')); ?>

                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="stat-card card-orders">
                        <div class="card-label"><i class="fa-solid fa-chart-line"></i> TRANSAKSI HARI INI</div>
                        <div class="card-value" id="box-transaksi">
                            <?php echo e($totalTransaksiHariIni); ?>

                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="stat-card card-cups">
                        <div class="card-label"><i class="fa-solid fa-glass-water"></i> CUP TERJUAL</div>
                        <div class="card-value" id="box-cup">
                            <?php echo e($totalCupHariIni); ?>

                        </div>
                    </div>
                </div>
            </div>

            <div class="table-container">
                <table id="tabelTransaksi" class="table table-hover w-100">
                    <thead>
                        <tr>
                            <th>ID Transaksi</th> 
                            <th>Waktu</th>        
                            <th>Item</th>         
                            <th>Total</th>         
                            <th>Status</th>        
                            <th class="text-end" style="padding-right:15px;">Aksi</th> 
                        </tr>
                    </thead>
                    <tbody>
                        <?php $__empty_1 = true; $__currentLoopData = $transaksiSemua; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $t): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                        <tr>
                            <td class="fw-bold">#<?php echo e($t->kode_transaksi); ?></td>
                            <td data-order="<?php echo e($t->created_at->format('Y-m-d')); ?>" class="text-muted">
                                <?php echo e($t->created_at->format('d M Y, H:i')); ?> WIB
                            </td>
                            <td>
                                <?php echo e($t->details->map(fn($item) => $item->nama_produk . " (" . $item->qty . ")")->implode(', ')); ?>

                            </td>
                            <td data-harga="<?php echo e($t->total_harga); ?>" class="fw-bold">Rp. <?php echo e(number_format($t->total_harga, 0, ',', '.')); ?></td>
                            <td><span class="badge bg-success-subtle text-success px-3 border-0">Selesai</span></td>
                            <td class="text-end" style="padding-right:15px;">
                                <button class="btn btn-sm btn-light border" onclick="printStruk('<?php echo e($t->kode_transaksi); ?>', '<?php echo e($t->created_at->format('d M Y, H:i')); ?>', [], '<?php echo e(number_format($t->total_harga, 0, ',', '.')); ?>')">
                                    <i class="fa-solid fa-print"></i>
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                        <tr>
                            <td colspan="6" class="text-center py-4 text-muted">Belum ada data transaksi di dalam database.</td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
<script src="https://gridjs.io/"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/linways/table-to-excel@v1.0.4/dist/tableToExcel.js"></script>

<script>
    $(document).ready(function() {
        const optionsHeader = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
        const headerDate = new Date().toLocaleDateString('id-ID', optionsHeader);
        document.getElementById('header-date').innerText = headerDate + " | Selamat Datang <?php echo e(explode(' ', auth()->user()->name)[0]); ?>";

        // Inisialisasi DataTables
        var table = $('#tabelTransaksi').DataTable({
            "searching": true,
            "dom": 'lrtip',
            "pageLength": 10,
            "order": [[1, "desc"]],
            "language": {
                "lengthMenu": "Show _MENU_ entries",
                "info": "Showing _START_ to _END_ of _TOTAL_ entries",
                "paginate": { "next": ">", "previous": "<" }
            }
        });

        // Sinkronisasi Input Search Atas
        $('#inputSearch').on('keyup', function() {
            table.search(this.value).draw();
            recalculateCards();
        });

        // Custom Engine Filter Rentang Tanggal Tunggal DataTables
        $.fn.dataTable.ext.search.push(
            function(settings, data, dataIndex) {
                var filterDate = $('#filterTanggal').val(); // YYYY-MM-DD
                var rowDate = table.row(dataIndex).node().children[1].getAttribute('data-order'); // YYYY-MM-DD

                if (!filterDate || filterDate === rowDate) {
                    return true;
                }
                return false;
            }
        );

        // Filter tanggal dijalankan saat input berubah
        $('#filterTanggal').on('change', function() {
            table.draw();
            recalculateCards();
        });

        // Fungsi Otomatis Rekalkulasi Angka di 3 Kotak Atas Sesuai Hasil Filter (Menjawab Keluhan Dospem)
        function recalculateCards() {
            let totalPendapatan = 0;
            let totalTransaksi = 0;
            let totalCup = 0;

            // Iterasi baris tabel yang lolos filter pencarian/tanggal saja
            table.rows({ filter: 'applied' }).every(function() {
                let node = this.node();
                let hargaMurni = parseFloat(node.children[3].getAttribute('data-harga')) || 0;
                let textItem = node.children[2].innerText;

                totalPendapatan += hargaMurni;
                totalTransaksi++;

                // Regex untuk mengambil angka di dalam tanda kurung, misal: Es Teh Tarik (2)
                let matches = textItem.match(/\((\d+)\)/g);
                if (matches) {
                    matches.forEach(m => {
                        let num = parseInt(m.replace(/[\(\)]/g, ''));
                        totalCup += num;
                    });
                }
            });

            // Update UI Card Realtime
            $('#box-pendapatan').text('Rp. ' + totalPendapatan.toLocaleString('id-ID'));
            $('#box-transaksi').text(totalTransaksi);
            $('#box-cup').text(totalCup);
        }

        // Jalankan rekalkulasi pertama kali agar filter tanggal bawaan hari ini langsung aktif
        table.draw();
        recalculateCards();
    });

    function exportLaporan() {
        let tableElement = document.getElementById("tabelTransaksi");
        let date = $('#filterTanggal').val() || new Date().toISOString().slice(0, 10);
        let namaFile = "Laporan_Riwayat_Transaksi_" + date + ".xlsx";

        TableToExcel.convert(tableElement, {
            name: namaFile,
            sheet: { name: "Riwayat" }
        });
    }
</script>
</body>
</html><?php /**PATH C:\xampp\htdocs\tehtarik\resources\views/kasir/transaksi.blade.php ENDPATH**/ ?>