<?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();
?>

<div class="container-fluid">
    <h1 class="h3 mb-2 text-gray-800">Danh sách phiếu chi</h1>
    <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">Phiếu chi</h6>
            <button class="btn btn-primary btn-sm" id="btn-add-payment"><i class="fas fa-plus"></i> Tạo mới</button>
        </div>
        <div class="card-body">
            <form id="filter-form" class="row g-3 mb-3 align-items-center">
                <div class="col-md-3">
                    <input type="text" class="form-control" id="search_term" placeholder="Nhập mã phiếu để tìm">
                </div>
                <div class="col-md-2">
                    <select id="type_id_filter" class="form-control">
                        <option value="">Tất cả 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>
                <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 kiếm</button>
                </div>
            </form>

            <table id="payments-table" class="table table-bordered" 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="close" data-dismiss="modal">&times;</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>
                            <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>
                         <div class="col-md-6 form-group">
                            <label>Số tiền chi</label>
                            <input type="number" class="form-control" id="total_money" name="total_money" required>
                        </div>
                    </div>
                    <div class="form-group" id="supplier-group" style="display:none;">
                        <label>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-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'; ?>

<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<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() {
    // Khởi tạo datepicker
    $('#start_date, #end_date').datepicker({
        format: 'yyyy-mm-dd',
        autoclose: true,
        todayHighlight: true,
        language: 'vi'
    });
    
    // Khởi tạo Select2 cho nhà cung cấp
    $('#supplier_id').select2({
        placeholder: 'Tìm nhà cung cấp',
        dropdownParent: $('#payment-modal'),
        ajax: {
            url: '/quanlybanhang/ajax/payments_ajax.php',
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return { q: params.term, action: 'search_suppliers' };
            },
            processResults: function (data) { return { results: data.results }; }
        }
    });
    
    // Khởi tạo Select2 cho nhân viên
    $('#pay_to_user_id').select2({
        placeholder: 'Tìm nhân viên',
        dropdownParent: $('#payment-modal'),
        ajax: {
            url: '/quanlybanhang/ajax/payments_ajax.php',
            dataType: 'json',
            delay: 250,
             data: function (params) {
              return { q: params.term, action: 'search_users' };
            },
            processResults: function (data) { return { results: data.results }; }
        }
    });

    var table = $('#payments-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: '/quanlybanhang/ajax/payments_ajax.php',
            type: 'POST',
            data: function(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', render: function(data) {
                return data ? `<a href="/quanlybanhang/${data}" target="_blank"><img src="/quanlybanhang/${data}" width="50" /></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, render: function(data) {
                return `<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));
        }
    });

    $('#filter-form').on('submit', function(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');
        if (type == '1' || type == '3') {
            $('#supplier-group').show();
            $('#user-group').hide();
        } else if (type == '2') {
            $('#supplier-group').hide();
            $('#user-group').show();
        } else {
            $('#supplier-group').hide();
            $('#user-group').hide();
        }
    });

    $('#btn-add-payment').on('click', function() {
        $('#payment-form')[0].reset();
        $('#payment-id').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('');
        $('#payment-modal').modal('show');
    });

    $('#payment-form').on('submit', function(e) {
        e.preventDefault();
        var formData = new FormData(this);
        $.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(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" />` : '');
                $('#type_id_form').val(d.type_id).trigger('change');

                if (d.type_id == 1 || d.type_id == 3) {
                    if(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) {
                     if(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>