<?php
require_once __DIR__ . '/../../core/init.php';
require_once __DIR__ . '/../../templates/header.php';
require_once __DIR__ . '/../../includes/receipt_helpers.php';
// Lấy các loại phiếu thu để đưa vào bộ lọc
$receipt_types = get_receipt_types();
// Lấy danh sách kho để đưa vào bộ lọc (nếu cần)
$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; display: flex; justify-content: space-between; align-items: center; }
    .summary-card .text-content .label { font-size:0.8rem; font-weight:700; text-transform:uppercase; margin-bottom:0.25rem; }
    .summary-card .text-content .value { font-size:1.75rem; font-weight:700; }
    .summary-card .icon-circle { width:50px; height:50px; border-radius:50%; display:flex; align-items:center; justify-content:center; color:white; font-size:1.5rem; }
    #receipts-table thead th { background-color:#4e73df !important; color:#ffffff !important; font-weight:bold; vertical-align: middle; }
    #receipts-table tfoot th { font-weight: bold; font-size: 1.1rem; }
</style>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800">Quản lý Phiếu thu</h1>

    <div class="row">
        <div class="col-xl-4 col-md-6 mb-4">
            <div class="card summary-card"><div class="card-body">
                <div class="text-content"><div class="label" style="color:#4e73df;">Tổng số phiếu</div><div class="value text-gray-800" id="summary-total-receipts">0</div></div>
                <div class="icon-circle" style="background-color:#4e73df;"><i class="fas fa-file-invoice"></i></div>
            </div></div>
        </div>
        <div class="col-xl-4 col-md-6 mb-4">
            <div class="card summary-card"><div class="card-body">
                <div class="text-content"><div class="label" style="color:#1cc88a;">Tổng tiền đã thu</div><div class="value text-gray-800" id="summary-total-amount">0</div></div>
                <div class="icon-circle" style="background-color:#1cc88a;"><i class="fas fa-wallet"></i></div>
            </div></div>
        </div>
        <div class="col-xl-4 col-md-6 mb-4">
            <div class="card summary-card"><div class="card-body">
                <div class="text-content"><div class="label" style="color:#36b9cc;">Tổng thu hôm nay</div><div class="value text-gray-800" id="summary-today-amount">0</div></div>
                <div class="icon-circle" style="background-color:#36b9cc;"><i class="fas fa-calendar-day"></i></div>
            </div></div>
        </div>
    </div>

    <div class="card shadow mb-4">
        <div class="card-header py-3 d-flex justify-content-between align-items-center">
            <h6 class="m-0 font-weight-bold text-primary">Danh sách phiếu thu</h6>
            <button class="btn btn-primary" id="btn-add-receipt"><i class="fas fa-plus fa-sm mr-2"></i>Tạo phiếu thu</button>
        </div>
        <div class="card-body">
            <form id="filter-form" class="mb-4">
                <div class="row align-items-end">
                    <div class="col-md-3 mb-3"><input type="text" class="form-control" name="search_term" id="search_term" placeholder="Nhập mã phiếu, ghi chú..."></div>
                    <div class="col-md-3 mb-3"><select name="type_id" id="type_id_filter" data-placeholder="-- Hình thức thu --"><option value=""></option><?php foreach($receipt_types as $id => $name) { echo "<option value='{$id}'>".htmlspecialchars($name)."</option>"; } ?></select></div>
                    <div class="col-md-2 mb-3"><input type="text" name="start_date" id="start_date" class="form-control" placeholder="Từ ngày"></div>
                    <div class="col-md-2 mb-3"><input type="text" name="end_date" 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 kiếm</button></div>
                </div>
            </form>

            <table id="receipts-table" class="table table-bordered table-hover" width="100%">
                <thead>
                    <tr>
                        <th>Mã phiếu</th>
                        <th>Chứng từ</th>
                        <th>Kho thu</th>
                        <th>Ngày thu</th>
                        <th>Người thu</th>
                        <th>Ghi chú</th>
                        <th>Hình thức thu</th>
                        <th>Tổng tiền</th>
                        <th>Hành động</th>
                    </tr>
                </thead>
                <tfoot>
                    <tr>
                        <th colspan="7" class="text-right">Tổng cộng:</th>
                        <th id="total-sum" class="text-right"></th>
                        <th></th>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="receipt-modal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form id="receipt-form" enctype="multipart/form-data">
                <input type="hidden" name="action" value="save_receipt">
                <input type="hidden" name="id" id="receipt-id">
                <input type="hidden" name="current_image" id="current-image">

                <div class="modal-header">
                    <h5 class="modal-title" id="modal-title">Tạo phiếu thu</h5>
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label for="notes">Ghi chú</label>
                        <input type="text" class="form-control" id="notes" name="notes" placeholder="Nhập ghi chú">
                    </div>
                    <div class="row">
                        <div class="col-md-6 form-group">
                            <label for="type_id_form">Hình thức thu</label>
                            <select name="type_id" id="type_id_form" class="form-control" required>
                                <option value="">-- Chọn hình thức --</option>
                                <?php foreach($receipt_types as $id => $name): ?>
                                    <option value="<?php echo $id; ?>"><?php echo htmlspecialchars($name); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                         <div class="col-md-6 form-group">
                            <label for="total_money">Số tiền thu</label>
                            <input type="text" class="form-control" id="total_money" name="total_money" required>
                        </div>
                    </div>
                     <div class="form-group">
                        <label for="customer_id">Khách hàng (nếu có)</label>
                        <select id="customer_id" name="customer_id" class="form-control" style="width: 100%;"></select>
                    </div>
                    <div class="form-group">
                        <label for="receipt_date">Ngày thu</label>
                        <input type="datetime-local" class="form-control" id="receipt_date" name="receipt_date" required>
                    </div>
                    <div class="form-group">
                        <label>Upload hình ảnh chứng từ</label>
                        <input type="file" name="receipt_image" class="form-control-file">
                        <div id="image-preview" class="mt-2"></div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Bỏ qua</button>
                    <button type="submit" class="btn btn-primary">Lưu</button>
                </div>
            </form>
        </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() {
    function formatNumber(num) { 
        return parseFloat(num || 0).toLocaleString('vi-VN');
    }
    function parseNumber(str) { 
        return parseFloat(String(str).replace(/\./g, '').replace(/,/g, '.')) || 0;
    }
    
    // Khởi tạo các thư viện cho bộ lọc
    $('#type_id_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);
    flatpickr('#end_date', fp_config);
    
    $('#customer_id').select2({
        placeholder: 'Tìm kiếm khách hàng (tên hoặc SĐT)',
        dropdownParent: $('#receipt-modal'),
        ajax: {
            url: '/quanlybanhang/ajax/customers_ajax.php',
            dataType: 'json',
            delay: 250,
            data: params => ({ action: 'get_customers', search_term: params.term, length: 10 }),
            processResults: data => ({
                results: $.map(data.data, item => ({ id: item.ID, text: `${item.customer_name} (${item.customer_phone || 'N/A'})` }))
            })
        }
    });

    $('#total_money').on('input', function() {
        let value = parseNumber($(this).val());
        $(this).val(formatNumber(value));
    });

    var table = $('#receipts-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: '/quanlybanhang/ajax/receipts_ajax.php',
            type: 'POST',
            data: d => {
                d.action = 'get_receipts';
                d.search_term = $('#search_term').val();
                d.type_id = $('#type_id_filter').val();
                d.start_date = $('#start_date').val();
                d.end_date = $('#end_date').val();
            }
        },
        columns: [
            { data: 'receipt_code' },
            { data: 'receipt_image', orderable: false, render: data => data ? `<a href="/quanlybanhang/${data}" target="_blank"><img src="/quanlybanhang/${data}" width="60" class="img-thumbnail"/></a>` : 'Không có' },
            { data: 'store_name' },
            { data: 'receipt_date' },
            { data: 'user_name' },
            { data: 'notes' },
            { data: 'type_name' },
            { data: 'total_money', className: 'text-right', render: $.fn.dataTable.render.number('.', ',', 0, '', ' đ') },
            { data: 'ID', orderable: false, searchable: false, className: 'text-center', render: data => `
                <a href="print.php?id=${data}" target="_blank" class="btn btn-info btn-sm" title="In phiếu"><i class="fas fa-print"></i></a>
                <button class="btn btn-warning btn-sm btn-edit" data-id="${data}" title="Sửa"><i class="fas fa-edit"></i></button>
                <button class="btn btn-danger btn-sm btn-delete" data-id="${data}" title="Xóa"><i class="fas fa-trash"></i></button>`
            }
        ],
        language: { "url": "/quanlybanhang/assets/libs/datatables/vietnamese.json" },
        footerCallback: function (row, data, start, end, display) {
            var api = this.api();
            var totalSum = api.ajax.json() ? api.ajax.json().totalSum : 0;
            $(api.column(7).footer()).html($.fn.dataTable.render.number('.', ',', 0, '', ' đ').display(totalSum));
        },
        drawCallback: function(settings) {
            var api = this.api();
            var json = api.ajax.json();
            if (json && json.summary) {
                $('#summary-total-receipts').text(formatNumber(json.summary.total_receipts));
                $('#summary-total-amount').text(formatNumber(json.summary.total_amount) + ' đ');
                $('#summary-today-amount').text(formatNumber(json.summary.today_amount) + ' đ');
            }
        }
    });

    $('#filter-form').on('submit', e => { e.preventDefault(); table.ajax.reload(); });

    $('#btn-add-receipt').on('click', function() {
        $('#receipt-form')[0].reset();
        $('#receipt-id').val('');
        $('#modal-title').text('Tạo phiếu thu');
        $('#image-preview').html('');
        $('#customer_id').val(null).trigger('change');
        const now = new Date();
        now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
        $('#receipt_date').val(now.toISOString().slice(0,16));
        $('#receipt-modal').modal('show');
    });

    $('#receipt-form').on('submit', function(e) {
        e.preventDefault();
        let formData = new FormData(this);
        let money = parseNumber($('#total_money').val());
        formData.set('total_money', money);

        $.ajax({
            url: '/quanlybanhang/ajax/receipts_ajax.php',
            type: 'POST', data: formData, contentType: false, processData: false, dataType: 'json',
            success: function(response) {
                alert(response.message);
                if (response.status === 'success') {
                    $('#receipt-modal').modal('hide');
                    table.ajax.reload();
                }
            }
        });
    });

    $('#receipts-table').on('click', '.btn-edit', function() {
        var id = $(this).data('id');
        // SỬA LỖI TẠI ĐÂY: Dùng $.post thay cho $.getJSON để thống nhất phương thức
        $.post('/quanlybanhang/ajax/receipts_ajax.php', { action: 'get_receipt_details', id: id }, function(response) {
            if (response.status === 'success' && response.data) {
                var d = response.data;
                $('#receipt-id').val(d.ID);
                $('#notes').val(d.notes);
                $('#type_id_form').val(d.type_id);
                $('#total_money').val(formatNumber(d.total_money));
                $('#receipt_date').val(d.receipt_date.replace(' ', 'T'));
                $('#current-image').val(d.receipt_image);
                $('#image-preview').html(d.receipt_image ? `<img src="/quanlybanhang/${d.receipt_image}" width="100" class="img-thumbnail"/>` : '');
                
                if (d.customer_id && d.customer_name) {
                    var customerOption = new Option(`${d.customer_name} (${d.customer_phone || 'N/A'})`, d.customer_id, true, true);
                    $('#customer_id').append(customerOption).trigger('change');
                } else {
                    $('#customer_id').val(null).trigger('change');
                }
                
                $('#modal-title').text('Sửa phiếu thu');
                $('#receipt-modal').modal('show');
            } else {
                alert(response.message || 'Có lỗi xảy ra khi lấy dữ liệu.');
            }
        }, 'json'); // Thêm 'json' để jQuery tự động parse kết quả
    });
    
    $('#receipts-table').on('click', '.btn-delete', function() {
        var id = $(this).data('id');
        if (confirm('Bạn có chắc muốn xóa phiếu thu này?')) {
            $.post('/quanlybanhang/ajax/receipts_ajax.php', { action: 'delete_receipt', id: id }, function(response) {
                alert(response.message);
                if(response.status === 'success') table.ajax.reload();
            }, 'json');
        }
    });
});
</script>