<?php
require_once __DIR__ . '/../../core/init.php';
require_once __DIR__ . '/../../templates/header.php';
?>

<div class="container-fluid">
    <h1 class="h3 mb-2 text-gray-800">Sổ quỹ tiền mặt</h1>

    <div class="row mb-4">
        <div class="col"><div class="card shadow py-2"><div class="card-body text-center">Tồn đầu<h5 id="summary-opening" class="font-weight-bold text-primary">0</h5></div></div></div>
        <div class="col"><div class="card shadow py-2"><div class="card-body text-center">Tổng thu<h5 id="summary-thu" class="font-weight-bold text-success">0</h5></div></div></div>
        <div class="col"><div class="card shadow py-2"><div class="card-body text-center">Tổng chi<h5 id="summary-chi" class="font-weight-bold text-danger">0</h5></div></div></div>
        <div class="col"><div class="card shadow py-2"><div class="card-body text-center">Tồn cuối<h5 id="summary-closing" class="font-weight-bold text-primary">0</h5></div></div></div>
        <div class="col"><div class="card shadow py-2"><div class="card-body text-center">Tổng số phiếu<h5 id="summary-vouchers" class="font-weight-bold text-info">0</h5></div></div></div>
    </div>

    <div class="card shadow mb-4">
        <div class="card-header py-3">
             <form id="filter-form" class="row g-3 align-items-center">
                <div class="col-md-2"><select id="user_filter" class="form-control"><option value="">-- Người tạo --</option></select></div>
                <div class="col-md-2"><select id="store_filter" class="form-control"><option value="">-- Cửa hàng --</option></select></div>
                <div class="col-md-2"><input type="text" id="start_date" class="form-control" placeholder="Từ ngày"></div>
                <div class="col-md-2"><input type="text" id="end_date" class="form-control" placeholder="Đến ngày"></div>
                <div class="col-md-2"><button type="submit" class="btn btn-primary"><i class="fas fa-search"></i> Tìm</button></div>
                <div class="col-md-2"><a href="#" id="export-excel" class="btn btn-success"><i class="fas fa-file-excel"></i> Excel</a></div>
            </form>
        </div>
        <div class="card-body">
            <table id="cashbook-table" class="table table-bordered" width="100%">
                <thead>
                    <tr>
                        <th>Mã phiếu</th>
                        <th>Ngày</th>
                        <th>Tên NV</th>
                        <th>Diễn giải</th>
                        <th class="text-right">Thu</th>
                        <th class="text-right">Chi</th>
                        <th class="text-right">Tồn</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../../templates/footer.php'; ?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css" rel="stylesheet"/>

<script>
$(document).ready(function() {
    $('#start_date, #end_date').datepicker({
        format: 'yyyy-mm-dd',
        autoclose: true,
        todayHighlight: true
    });

    const formatCurrency = (number) => new Intl.NumberFormat('vi-VN').format(number || 0) + ' đ';
    const formatNumber = (number) => new Intl.NumberFormat('vi-VN').format(number || 0);

    var table = $('#cashbook-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: '/quanlybanhang/ajax/cashbook_ajax.php',
            type: 'POST',
            data: function(d) {
                d.start_date = $('#start_date').val();
                d.end_date = $('#end_date').val();
                d.user_id = $('#user_filter').val();
                d.store_id = $('#store_filter').val();
            },
            dataSrc: function(json) {
                // Cập nhật các thẻ tóm tắt
                if (json.summary) {
                    $('#summary-opening').text(formatCurrency(json.summary.openingBalance));
                    $('#summary-thu').text(formatCurrency(json.summary.totalThu));
                    $('#summary-chi').text(formatCurrency(json.summary.totalChi));
                    $('#summary-closing').text(formatCurrency(json.summary.closingBalance));
                    $('#summary-vouchers').text(formatNumber(json.summary.totalVouchers));
                }
                return json.data;
            }
        },
        columns: [
            { data: 'code' },
            { data: 'transaction_date' },
            { data: 'display_name' },
            { data: 'notes' },
            { data: 'thu', className: 'text-right', render: function(data) {
                return data > 0 ? formatNumber(data) : '-';
            }},
            { data: 'chi', className: 'text-right', render: function(data) {
                return data > 0 ? formatNumber(data) : '-';
            }},
            { data: 'ton', className: 'text-right', render: function(data) {
                return formatNumber(data);
            }}
        ],
        paging: true,
        pageLength: 25,
        ordering: false,
        language: { "url": "/quanlybanhang/assets/libs/datatables/vietnamese.json" },
        drawCallback: function (settings) {
            var api = this.api();
            var json = api.ajax.json();
            var openingBalance = json ? (json.summary ? json.summary.openingBalance : 0) : 0;
            
            $('#cashbook-table tbody tr.opening-balance-row').remove();
            var openingRow = `<tr class="opening-balance-row font-weight-bold bg-light">
                                <td colspan="6" class="text-right">Tồn đầu kỳ</td>
                                <td class="text-right">${formatNumber(openingBalance)}</td>
                              </tr>`;
            $('#cashbook-table tbody').prepend(openingRow);
        }
    });

    $('#filter-form').on('submit', function(e) {
        e.preventDefault();
        table.ajax.reload();
        updateExportLink();
    });
    
    function updateExportLink() {
        var params = {
            start_date: $('#start_date').val(),
            end_date: $('#end_date').val(),
            user_id: $('#user_filter').val(),
            store_id: $('#store_filter').val()
        };
        // Cần tạo file export/cashbook_excel.php để link này hoạt động
        $('#export-excel').attr('href', '/quanlybanhang/export/cashbook_excel.php?' + $.param(params));
    }
    updateExportLink();
});
</script>