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

// Lấy dữ liệu cho bộ lọc
$users = $conn->query("SELECT id, display_name FROM cms_users WHERE user_status = 1 ORDER BY display_name ASC")->fetch_all(MYSQLI_ASSOC);
$stores = $conn->query("SELECT id, store_name FROM cms_stores ORDER BY store_name ASC")->fetch_all(MYSQLI_ASSOC);
?>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" />
<style>
    .summary-card { background-color:#fff; border:none; border-radius:0.75rem; box-shadow:0 .15rem 1.75rem 0 rgba(58,59,69,.15)!important; transition:all .2s ease-in-out; }
    .summary-card:hover { transform: translateY(-5px); }
    .summary-card .card-body { padding: 1.5rem; }
    .summary-card .label { font-size:0.8rem; font-weight:700; text-transform:uppercase; margin-bottom:0.25rem; }
    .summary-card .value { font-size:1.75rem; font-weight:700; }
    #cashbook-table thead th { background-color:#4e73df !important; color:#ffffff !important; font-weight:bold; vertical-align: middle; }
    #cashbook-table .col-thu { color: #1cc88a; font-weight: 500; }
    #cashbook-table .col-chi { color: #e74a3b; font-weight: 500; }
    #cashbook-table .col-ton { font-weight: bold; }
    #cashbook-table .opening-balance-row td { font-weight: bold; background-color: #f8f9fc; }
</style>

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

    <div class="row">
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card summary-card"><div class="card-body">
                <div class="label" style="color:#6e707e;">Tồn đầu</div>
                <div class="value text-gray-800" id="summary-opening">0 đ</div>
            </div></div>
        </div>
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card summary-card"><div class="card-body">
                <div class="label" style="color:#1cc88a;">Tổng thu</div>
                <div class="value text-success" id="summary-thu">0 đ</div>
            </div></div>
        </div>
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card summary-card"><div class="card-body">
                <div class="label" style="color:#e74a3b;">Tổng chi</div>
                <div class="value text-danger" id="summary-chi">0 đ</div>
            </div></div>
        </div>
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card summary-card"><div class="card-body">
                <div class="label" style="color:#4e73df;">Tồn cuối</div>
                <div class="value text-primary" id="summary-closing">0 đ</div>
            </div></div>
        </div>
    </div>

    <div class="card shadow mb-4">
         <div class="card-body">
            <form id="filter-form" class="mb-4">
                <div class="row align-items-end">
                    <div class="col-md-3 mb-3"><select id="user_filter" data-placeholder="-- Người tạo --"><option value=""></option><?php foreach($users as $user): ?><option value="<?php echo $user['id']; ?>"><?php echo htmlspecialchars($user['display_name']); ?></option><?php endforeach; ?></select></div>
                    <div class="col-md-3 mb-3"><select id="store_filter" data-placeholder="-- Cửa hàng --"><option value=""></option><?php foreach($stores as $store): ?><option value="<?php echo $store['id']; ?>"><?php echo htmlspecialchars($store['store_name']); ?></option><?php endforeach; ?></select></div>
                    <div class="col-md-2 mb-3"><input type="text" id="start_date" class="form-control" placeholder="Từ ngày"></div>
                    <div class="col-md-2 mb-3"><input type="text" id="end_date" class="form-control" placeholder="Đến ngày"></div>
                    <div class="col-md-2 mb-3"><button type="submit" class="btn btn-primary w-100"><i class="fas fa-search fa-sm mr-2"></i>Tìm</button></div>
                </div>
            </form>

            <table id="cashbook-table" class="table table-bordered table-hover" 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://cdn.jsdelivr.net/npm/flatpickr"></script>
<script src="https://npmcdn.com/flatpickr/dist/l10n/vn.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
$(document).ready(function() {
    $('#user_filter, #store_filter').select2({ theme: "bootstrap-5", allowClear: true });
    const fp_config = { locale: "vn", altInput: true, altFormat: "d/m/Y", dateFormat: "Y-m-d" };
    flatpickr('#start_date', { ...fp_config, defaultDate: "<?php echo date('Y-m-01'); ?>" });
    flatpickr('#end_date', { ...fp_config, defaultDate: "<?php echo date('Y-m-d'); ?>" });

    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: 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: json => {
                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));
                }
                return json.data;
            }
        },
        columns: [
            { data: 'code' },
            { data: 'transaction_date' },
            { data: 'display_name', defaultContent: 'N/A' }, // Sửa lỗi: Hiển thị N/A nếu tên NV null
            { data: 'notes' },
            { data: 'thu', className: 'text-right col-thu', render: data => data > 0 ? formatNumber(data) : '-' },
            { data: 'chi', className: 'text-right col-chi', render: data => data > 0 ? formatNumber(data) : '-' },
            { data: 'ton', className: 'text-right col-ton', render: data => 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?.summary?.openingBalance || 0;
            
            $('#cashbook-table tbody tr.opening-balance-row').remove();
            var openingRow = `<tr class="opening-balance-row">
                                <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', e => { e.preventDefault(); table.ajax.reload(); });
});
</script>