<?php
require_once __DIR__ . '/../../core/init.php';
require_once __DIR__ . '/../../templates/header.php';
require_once __DIR__ . '/../../includes/payment_helpers.php';
$payment_types = get_payment_types();
?>

<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; }
    #payments-table thead th { background-color:#4e73df !important; color:#ffffff !important; font-weight:bold; vertical-align: middle; }
    #payments-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 chi</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-payments">0</div></div>
                <div class="icon-circle" style="background-color:#4e73df;"><i class="fas fa-file-invoice-dollar"></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:#e74a3b;">Tổng tiền đã chi</div><div class="value text-gray-800" id="summary-total-amount">0</div></div>
                <div class="icon-circle" style="background-color:#e74a3b;"><i class="fas fa-money-bill-wave"></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:#f6c23e;">Tổng chi hôm nay</div><div class="value text-gray-800" id="summary-today-amount">0</div></div>
                <div class="icon-circle" style="background-color:#f6c23e;"><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 chi</h6>
            <button class="btn btn-primary" id="btn-add-payment"><i class="fas fa-plus fa-sm mr-2"></i>Tạo phiếu chi</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" id="search_term" placeholder="Nhập mã phiếu, ghi chú..."></div>
                    <div class="col-md-3 mb-3"><select id="type_id_filter" data-placeholder="-- Hình thức chi --"><option value=""></option><?php foreach($payment_types as $id => $name) { echo "<option value='{$id}'>".htmlspecialchars($name)."</option>"; } ?></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 kiếm</button></div>
                </div>
            </form>

            <table id="payments-table" class="table table-bordered table-hover" width="100%">
                <thead>
                    <tr>
                        <th>Mã phiếu</th>
                        <th>Chứng từ</th>
                        <th>Kho chi</th>
                        <th>Ngày chi</th>
                        <th>Người chi</th>
                        <th>Chi cho</th>
                        <th>Ghi chú</th>
                        <th>Hình thức chi</th>
                        <th>Tổng tiền</th>
                        <th>Hành động</th>
                    </tr>
                </thead>
                <tfoot>
                    <tr>
                        <th colspan="8" 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="payment-modal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form id="payment-form" enctype="multipart/form-data">
                <input type="hidden" name="action" value="save_payment">
                <input type="hidden" name="id" id="payment-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 chi</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label>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>Hình thức chi</label>
                            <div class="input-group">
                                <select name="type_id" id="type_id_form" class="form-control" required>
                                    <option value="">-- Chọn hình thức --</option>
                                    <?php foreach($payment_types as $id => $name): ?>
                                        <option value="<?php echo $id; ?>"><?php echo htmlspecialchars($name); ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <div class="input-group-append">
                                    <button class="btn btn-outline-primary" type="button" id="btn-add-payment-type" title="Thêm hình thức chi mới"><i class="fas fa-plus"></i></button>
                                </div>
                            </div>
                        </div>
                         <div class="col-md-6 form-group">
                            <label>Số tiền chi</label>
                            <input type="text" class="form-control" id="total_money" name="total_money" required>
                        </div>
                    </div>
                    <div class="form-group" id="supplier-group" style="display:none;">
                        <label>Chi cho (Nhà cung cấp)</label>
                        <select id="supplier_id" name="supplier_id" class="form-control" style="width:100%;"></select>
                    </div>
                     <div class="form-group" id="user-group" style="display:none;">
                        <label>Chi cho (Nhân viên)</label>
                        <select id="pay_to_user_id" name="pay_to_user_id" class="form-control" style="width:100%;"></select>
                    </div>
                    <div class="form-group">
                        <label>Ngày chi</label>
                        <input type="datetime-local" class="form-control" id="payment_date" name="payment_date" required>
                    </div>
                    <div class="form-group">
                        <label>Upload hình ảnh chứng từ</label>
                        <input type="file" name="payment_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-bs-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; }

    $('#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);
    
    $('#supplier_id, #pay_to_user_id').select2({
        dropdownParent: $('#payment-modal'),
        width: '100%',
        ajax: {
            url: '/quanlybanhang/ajax/payments_ajax.php',
            dataType: 'json',
            delay: 250,
            data: function (params) {
                let action = $(this).attr('id') === 'supplier_id' ? 'search_suppliers' : 'search_users';
                return { q: params.term, action: action };
            },
            processResults: function (data) { return { results: data.results }; }
        }
    });

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

    var table = $('#payments-table').DataTable({
        processing: true,
        serverSide: true,
        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' },
            { data: 'payment_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: 'payment_date' },
            { data: 'creator_name' },
            { data: 'payee_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}"><i class="fas fa-edit"></i></button>
                <button class="btn btn-danger btn-sm btn-delete" data-id="${data}"><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(8).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-payments').text(formatNumber(json.summary.total_payments));
                $('#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(); });

    $('#type_id_form').on('change', function() {
        var type = $(this).val();
        $('#supplier_id, #pay_to_user_id').val(null).trigger('change');
        $('#supplier-group').hide();
        $('#user-group').hide();
        if (type == '1' || type == '3') { $('#supplier-group').show(); } 
        else if (type == '2') { $('#user-group').show(); }
    });

    $('#btn-add-payment-type').on('click', function() {
        var newTypeName = prompt("Nhập tên hình thức chi mới:");
        if (newTypeName && newTypeName.trim() !== '') {
            $.ajax({
                url: '/quanlybanhang/ajax/payments_ajax.php',
                type: 'POST',
                data: {
                    action: 'add_payment_type',
                    name: newTypeName.trim()
                },
                dataType: 'json',
                success: function(response) {
                    if (response.status === 'success') {
                        var newOption = new Option(response.data.name, response.data.id, true, true);
                        $('#type_id_form').append(newOption).trigger('change');
                        $('#type_id_filter').append(new Option(response.data.name, response.data.id)).trigger('change');
                        alert('Thêm hình thức chi thành công!');
                    } else {
                        alert('Lỗi: ' + response.message);
                    }
                },
                error: function() {
                    alert('Đã xảy ra lỗi khi kết nối đến máy chủ.');
                }
            });
        }
    });

    $('#btn-add-payment').on('click', function() {
        $('#payment-id').val('');
        $('#current-image').val('');
        $('#notes').val('');
        $('#total_money').val('');
        $('#type_id_form').val('').trigger('change');
        $('input[name="payment_image"]').val('');

        $('#modal-title').text('Tạo phiếu chi');
        $('#supplier-group, #user-group').hide();
        $('#supplier_id, #pay_to_user_id').val(null).trigger('change');
        $('#image-preview').html('');
        
        const now = new Date();
        now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
        $('#payment_date').val(now.toISOString().slice(0,16));
        
        $('#payment-modal').modal('show');
    });

    $('#payment-form').on('submit', function(e) {
        e.preventDefault();
        let formData = new FormData(this);
        formData.set('total_money', parseNumber($('#total_money').val()));
        $.ajax({
            url: '/quanlybanhang/ajax/payments_ajax.php',
            type: 'POST', data: formData, contentType: false, processData: false, dataType: 'json',
            success: function(response) {
                alert(response.message);
                if (response.status === 'success') {
                    $('#payment-modal').modal('hide');
                    table.ajax.reload();
                }
            }
        });
    });

    $('#payments-table').on('click', '.btn-edit', function() {
        var id = $(this).data('id');
        $.getJSON('/quanlybanhang/ajax/payments_ajax.php', { action: 'get_payment_details', id: id }, function(response) {
            if (response.status === 'success' && response.data) {
                var d = response.data;
                $('#payment-id').val(d.ID);
                $('#notes').val(d.notes);
                $('#total_money').val(formatNumber(d.total_money));
                $('#payment_date').val(d.payment_date.replace(' ', 'T'));
                $('#current-image').val(d.payment_image);
                $('#image-preview').html(d.payment_image ? `<img src="/quanlybanhang/${d.payment_image}" width="100" class="img-thumbnail"/>` : '');
                $('#type_id_form').val(d.type_id).trigger('change');

                if ((d.type_id == 1 || d.type_id == 3) && d.payment_for && d.supplier_name) {
                    var option = new Option(d.supplier_name, d.payment_for, true, true);
                    $('#supplier_id').append(option).trigger('change');
                } else if (d.type_id == 2 && d.payment_for && d.payee_user_name) {
                    var option = new Option(d.payee_user_name, d.payment_for, true, true);
                    $('#pay_to_user_id').append(option).trigger('change');
                }
                
                $('#modal-title').text('Sửa phiếu chi');
                $('#payment-modal').modal('show');
            }
        });
    });
    
    $('#payments-table').on('click', '.btn-delete', function() {
        var id = $(this).data('id');
        if (confirm('Bạn có chắc muốn xóa phiếu chi này?')) {
            $.post('/quanlybanhang/ajax/payments_ajax.php', { action: 'delete_payment', id: id }, function(response) {
                alert(response.message);
                if(response.status === 'success') table.ajax.reload();
            }, 'json');
        }
    });
});
</script>