<?php
// modules/payments/index.php - FULL CODE
ini_set('display_errors', 1);
error_reporting(E_ALL);

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

// Lấy danh sách loại chi để fill vào select box
$payment_types = [];
if (isset($conn)) {
    $result = $conn->query("SELECT id, type_name FROM cms_payment_type ORDER BY id ASC");
    if ($result) {
        $payment_types = $result->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>
    /* --- STYLE CHUNG --- */
    .summary-card { border: none; border-radius: 15px; box-shadow: 0 4px 20px rgba(0,0,0,0.05); transition: transform 0.3s; overflow: hidden; color: #fff; }
    .summary-card:hover { transform: translateY(-5px); }
    .bg-gradient-primary { background: linear-gradient(45deg, #4e73df, #224abe); }
    .bg-gradient-danger { background: linear-gradient(45deg, #e74a3b, #be2617); }
    .bg-gradient-warning { background: linear-gradient(45deg, #f6c23e, #dda20a); }
    
    .card-body-content { padding: 1.5rem; position: relative; z-index: 2; }
    .text-content .label { font-size: 0.85rem; font-weight: 600; text-transform: uppercase; opacity: 0.9; margin-bottom: 5px; }
    .text-content .value { font-size: 2rem; font-weight: 800; }
    .icon-box { position: absolute; right: 15px; bottom: 10px; font-size: 3.5rem; opacity: 0.2; transform: rotate(-15deg); }

    /* TABLE */
    #payments-table thead th { background-color: #f8f9fc; color: #5a5c69; font-weight: 700; text-transform: uppercase; font-size: 0.85rem; padding: 12px; border-bottom: 2px solid #e3e6f0; }
    #payments-table tbody td { vertical-align: middle; padding: 12px; font-size: 0.95rem; }

    /* --- MODAL FORM ĐẸP --- */
    .modal-content { border-radius: 12px; border: none; box-shadow: 0 10px 30px rgba(0,0,0,0.1); }
    .modal-header { background: #4e73df; color: white; border-top-left-radius: 12px; border-top-right-radius: 12px; }
    .modal-title { font-weight: 700; font-size: 1.1rem; }
    .btn-close { filter: invert(1); opacity: 0.8; }
    
    .form-label { font-weight: 600; color: #444; font-size: 0.9rem; margin-bottom: 0.4rem; }
    
    /* Input Tiền Siêu To */
    #total_money { 
        font-size: 1.8rem; font-weight: 800; color: #e74a3b; text-align: right; height: 55px; 
        border: 2px solid #e3e6f0; background-color: #fffafa;
    }
    #total_money:focus { border-color: #e74a3b; box-shadow: 0 0 0 0.25rem rgba(231, 74, 59, 0.1); }
    
    .form-control { border-radius: 8px; padding: 10px 15px; border: 1px solid #d1d3e2; }
    .form-control:focus { border-color: #4e73df; box-shadow: 0 0 0 0.25rem rgba(78, 115, 223, 0.1); }

    /* Select2 Custom Fix */
    .select2-container--bootstrap-5 .select2-selection { border-radius: 8px; min-height: 42px; border-color: #d1d3e2; }
    .select2-container--bootstrap-5 .select2-selection--single .select2-selection__rendered { line-height: 40px; padding-left: 15px; font-weight: 600; }
</style>

<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="h3 mb-0 text-gray-800 fw-bold">Quản lý Chi phí</h1>
        <button class="btn btn-primary shadow-sm btn-lg" id="btn-add-payment">
            <i class="fas fa-plus fa-sm me-2"></i>Tạo Phiếu Chi
        </button>
    </div>

    <div class="row mb-4">
        <div class="col-xl-4 col-md-6">
            <div class="summary-card bg-gradient-primary">
                <div class="card-body-content">
                    <div class="text-content"><div class="label">Tổng số phiếu</div><div class="value" id="summary-total-payments">0</div></div>
                    <div class="icon-box"><i class="fas fa-file-invoice"></i></div>
                </div>
            </div>
        </div>
        <div class="col-xl-4 col-md-6">
            <div class="summary-card bg-gradient-danger">
                <div class="card-body-content">
                    <div class="text-content"><div class="label">Tổng tiền đã chi</div><div class="value" id="summary-total-amount">0 ₫</div></div>
                    <div class="icon-box"><i class="fas fa-money-bill-wave"></i></div>
                </div>
            </div>
        </div>
        <div class="col-xl-4 col-md-6">
            <div class="summary-card bg-gradient-warning">
                <div class="card-body-content">
                    <div class="text-content"><div class="label">Chi trong ngày</div><div class="value" id="summary-today-amount">0 ₫</div></div>
                    <div class="icon-box"><i class="fas fa-calendar-day"></i></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 g-2">
                    <div class="col-md-3"><input type="text" class="form-control" id="search_term" placeholder="Tìm mã phiếu, ghi chú..."></div>
                    <div class="col-md-3">
                        <select id="type_id_filter" class="form-select">
                            <option value="">Tất cả loại chi</option>
                            <?php foreach($payment_types as $type) { echo "<option value='{$type['id']}'>{$type['type_name']}</option>"; } ?>
                        </select>
                    </div>
                    <div class="col-md-2"><input type="text" id="start_date" class="form-control flatpickr" placeholder="Từ ngày"></div>
                    <div class="col-md-2"><input type="text" id="end_date" class="form-control flatpickr" placeholder="Đến ngày"></div>
                    <div class="col-md-2"><button type="submit" class="btn btn-dark w-100 fw-bold" style="height: 42px;"><i class="fas fa-search me-1"></i> Lọc</button></div>
                </div>
            </form>

            <div class="table-responsive">
                <table id="payments-table" class="table table-hover w-100">
                    <thead><tr><th>Mã phiếu</th><th>Ngày chi</th><th>Loại chi</th><th>Ghi chú</th><th>Người tạo</th><th class="text-end">Số tiền</th><th class="text-center">Hành động</th></tr></thead>
                    <tfoot><tr><th colspan="5" class="text-end fw-bold">Tổng trang:</th><th id="total-sum" class="text-end fw-bold text-danger h5"></th><th></th></tr></tfoot>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="payment-modal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <form id="payment-form">
                <input type="hidden" name="action" value="save_payment">
                <input type="hidden" name="id" id="payment-id">
                
                <div class="modal-header py-3">
                    <h5 class="modal-title text-white" id="modal-title"><i class="fas fa-pen-square me-2"></i>Tạo Phiếu Chi</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                
                <div class="modal-body p-4">
                    <div class="mb-4">
                        <label class="form-label">Số tiền chi <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <input type="text" class="form-control" id="total_money" name="total_money" placeholder="0" required autocomplete="off">
                            <span class="input-group-text fw-bold bg-light text-danger border-start-0" style="font-size: 1.2rem;">₫</span>
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-7">
                            <label class="form-label">Lý do chi (Loại)</label>
                            <div class="input-group">
                                <select name="type_id" id="type_id_form" class="form-select" required style="width: 85%;">
                                    <option value="">-- Chọn --</option>
                                    <?php foreach($payment_types as $type): ?>
                                        <option value="<?= $type['id'] ?>"><?= $type['type_name'] ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <button class="btn btn-outline-primary" type="button" id="btn-quick-add-type" title="Thêm loại mới"><i class="fas fa-plus"></i></button>
                            </div>
                        </div>
                        <div class="col-md-5">
                            <label class="form-label">Ngày chi</label>
                            <input type="datetime-local" class="form-control" id="payment_date" name="payment_date" required>
                        </div>
                    </div>

                    <div class="mb-2">
                        <label class="form-label">Ghi chú / Nội dung</label>
                        <textarea class="form-control" id="notes" name="notes" rows="3" placeholder="Ví dụ: Mua 5kg đường, 10 hộp sữa..."></textarea>
                    </div>
                </div>
                
                <div class="modal-footer bg-light px-4 py-3">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Hủy bỏ</button>
                    <button type="submit" class="btn btn-primary fw-bold px-4"><i class="fas fa-save me-2"></i> LƯU PHIẾ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() {
    const formatMoney = (num) => new Intl.NumberFormat('vi-VN').format(num || 0);
    const parseMoney = (str) => parseFloat(String(str).replace(/\./g, '').replace(/,/g, '.')) || 0;

    flatpickr(".flatpickr", { locale: "vn", dateFormat: "Y-m-d" });

    // Select2
    $('#type_id_form').select2({
        theme: "bootstrap-5",
        dropdownParent: $('#payment-modal'),
        placeholder: "Chọn hoặc tìm kiếm...",
        allowClear: true
    });

    $('#total_money').on('keyup', function() {
        $(this).val(formatMoney(parseMoney($(this).val())));
    });

    // DataTable: FIX LỖI HIỂN THỊ NGÀY
    var table = $('#payments-table').DataTable({
        processing: true, serverSide: true, searching: false,
        ajax: {
            url: '/quanlybanhang/ajax/payments_ajax.php', type: 'POST',
            data: d => {
                d.action = 'get_payments';
                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: 'payment_code', className: 'fw-bold text-primary' },
            { 
                data: 'payment_date', 
                // --- LOGIC FIX NGÀY THÁNG ---
                render: function(data) {
                    if (!data || data == '0000-00-00 00:00:00') return '<span class="text-muted">--</span>';
                    var date = new Date(data);
                    var day = ("0" + date.getDate()).slice(-2);
                    var month = ("0" + (date.getMonth() + 1)).slice(-2);
                    var year = date.getFullYear();
                    var hours = ("0" + date.getHours()).slice(-2);
                    var minutes = ("0" + date.getMinutes()).slice(-2);
                    return `${day}/${month}/${year} ${hours}:${minutes}`;
                }
            },
            { data: 'type_name', render: d => `<span class="badge bg-info text-dark">${d}</span>` },
            { data: 'notes' },
            { data: 'creator_name' },
            { data: 'total_money', className: 'text-end fw-bold text-danger', render: d => formatMoney(d) + ' ₫' },
            { data: 'ID', className: 'text-center', orderable: false, render: d => `
                <div class="btn-group btn-group-sm">
                    <button class="btn btn-outline-primary btn-edit" data-id="${d}"><i class="fas fa-pen"></i></button>
                    <button class="btn btn-outline-danger btn-delete" data-id="${d}"><i class="fas fa-trash"></i></button>
                </div>
            `}
        ],
        footerCallback: function (row, data, start, end, display) {
            var api = this.api();
            var totalSum = api.ajax.json() ? api.ajax.json().totalSum : 0;
            $('#total-sum').html(formatMoney(totalSum) + ' ₫');
        },
        drawCallback: function(settings) {
            var json = this.api().ajax.json();
            if (json && json.summary) {
                $('#summary-total-payments').text(formatMoney(json.summary.total_payments));
                $('#summary-total-amount').text(formatMoney(json.summary.total_amount) + ' ₫');
                $('#summary-today-amount').text(formatMoney(json.summary.today_amount) + ' ₫');
            }
        },
        language: { url: "//cdn.datatables.net/plug-ins/1.10.21/i18n/Vietnamese.json" }
    });

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

    $('#btn-add-payment').click(function() {
        $('#payment-form')[0].reset();
        $('#payment-id').val('');
        $('#modal-title').html('<i class="fas fa-pen-square me-2"></i>Tạo Phiếu Chi Mới');
        $('#type_id_form').val('').trigger('change');
        
        const now = new Date();
        now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
        $('#payment_date').val(now.toISOString().slice(0,16));
        
        $('#payment-modal').modal('show');
        setTimeout(() => $('#total_money').focus(), 500);
    });

    // Thêm nhanh loại chi
    $('#btn-quick-add-type').click(function() {
        let newType = prompt("Nhập tên loại chi phí mới (Ví dụ: Mua đá, Gas...):");
        if(newType) {
            $.post('/quanlybanhang/ajax/payments_ajax.php', { action: 'add_payment_type', name: newType }, function(res) {
                if(res.status === 'success') {
                    let newOption = new Option(res.data.name, res.data.id, true, true);
                    $('#type_id_form').append(newOption).trigger('change');
                } else {
                    alert(res.message);
                }
            }, 'json');
        }
    });

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

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

    $('body').on('click', '.btn-edit', function() {
        let id = $(this).data('id');
        $.getJSON('/quanlybanhang/ajax/payments_ajax.php', { action: 'get_detail', id: id }, function(res) {
            if(res.status === 'success') {
                let d = res.data;
                $('#payment-id').val(d.ID);
                $('#total_money').val(formatMoney(d.total_money));
                $('#notes').val(d.notes);
                $('#type_id_form').val(d.type_id).trigger('change');
                
                // Fix ngày tháng khi sửa
                if(d.payment_date) {
                     let dateStr = d.payment_date.replace(' ', 'T').substring(0, 16);
                     $('#payment_date').val(dateStr);
                }
                
                $('#modal-title').text('Sửa Phiếu Chi: ' + d.payment_code);
                $('#payment-modal').modal('show');
            }
        });
    });

    $('body').on('click', '.btn-delete', function() {
        if(confirm('Bạn có chắc chắn muốn xóa phiếu này?')) {
            let id = $(this).data('id');
            $.post('/quanlybanhang/ajax/payments_ajax.php', { action: 'delete_payment', id: id }, function(res) {
                if(res.status === 'success') { alert('Đã xóa!'); table.ajax.reload(); }
                else alert(res.message);
            }, 'json');
        }
    });
});
</script>