<?php
require_once __DIR__ . '/../../templates/header.php';
?>

<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:1px solid #e3e6f0; border-radius:0.75rem; transition:all .2s ease-in-out; box-shadow:0 .15rem 1.75rem 0 rgba(58,59,69,.15)!important; }
    .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; color:#3a3b45; }
    .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; }
    .filter-card { border-left:4px solid #4e73df; }
    .select2-container--bootstrap-5 .select2-selection { padding: .43rem 1rem; height: calc(1.5em + .75rem + 2px); }
    #supplierTable thead th { background-color:#4e73df !important; color:#ffffff !important; font-weight:bold; vertical-align: middle; }
    #supplierTable tbody tr:nth-child(even) { background-color: #f8f9fc; }
    #supplierTable tbody tr:hover { background-color: #eaecf4; }
</style>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800">Quản lý Nhà cung cấp</h1>
    
    <div class="row mb-4">
        <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ố NCC</div><div class="value" id="summary_total_suppliers">0</div></div>
                    <div class="icon-circle" style="background-color: #4e73df;"><i class="fas fa-dolly"></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;">NCC có nợ</div><div class="value" id="summary_debt_suppliers">0</div></div>
                    <div class="icon-circle" style="background-color: #f6c23e;"><i class="fas fa-truck-loading"></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 Nợ NCC</div><div class="value" id="summary_total_debt">0 ₫</div></div>
                    <div class="icon-circle" style="background-color: #e74a3b;"><i class="fas fa-file-invoice-dollar"></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 nhà cung cấp</h6>
            <button type="button" class="btn btn-primary btn-sm" id="btnOpenAddModal"><i class="fas fa-plus fa-sm"></i> Tạo NCC</button>
        </div>
        <div class="card-body">
            <div class="card mb-4 filter-card">
                <div class="card-body">
                    <form id="filterForm" class="row gx-3 align-items-center">
                        <div class="col-md-6"><input type="text" id="searchTerm" class="form-control" placeholder="Nhập tên, mã hoặc SĐT nhà cung cấp"></div>
                        <div class="col-md-4"><select class="form-control" id="debtStatus"><option value="">Tất cả tình trạng</option><option value="debt">NCC có nợ</option><option value="no_debt">NCC không nợ</option></select></div>
                        <div class="col-md-2"><button class="btn btn-primary w-100" type="submit"><i class="fas fa-search fa-sm"></i> Tìm</button></div>
                    </form>
                </div>
            </div>
            <div class="table-responsive">
                <table class="table table-hover" id="supplierTable" width="100%" cellspacing="0"></table>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="supplierModal" tabindex="-1" aria-labelledby="supplierModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="supplierModalLabel">Thêm Nhà cung cấp mới</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="supplierForm">
                    <input type="hidden" id="supplier_id" name="supplier_id">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="supplier_name" class="form-label">Tên nhà cung cấp <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="supplier_name" name="supplier_name" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="supplier_code" class="form-label">Mã nhà cung cấp</label>
                            <input type="text" class="form-control" id="supplier_code" name="supplier_code" placeholder="Tự động tạo nếu để trống">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="supplier_phone" class="form-label">Số điện thoại</label>
                            <input type="text" class="form-control" id="supplier_phone" name="supplier_phone">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="supplier_email" class="form-label">Email</label>
                            <input type="email" class="form-control" id="supplier_email" name="supplier_email">
                        </div>
                        <div class="col-12 mb-3">
                            <label for="supplier_address" class="form-label">Địa chỉ</label>
                            <input type="text" class="form-control" id="supplier_address" name="supplier_address">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="tax_code" class="form-label">Mã số thuế</label>
                            <input type="text" class="form-control" id="tax_code" name="tax_code">
                        </div>
                         <div class="col-md-6 mb-3">
                            <label for="note" class="form-label">Ghi chú</label>
                            <input type="text" class="form-control" id="note" name="note">
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Đóng</button>
                <button type="button" class="btn btn-primary" id="btnSaveSupplier">Lưu thay đổi</button>
            </div>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../../templates/footer.php'; ?>

<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
$(document).ready(function() {
    const formatCurrency = (num) => (parseFloat(num) || 0).toLocaleString('vi-VN');
    const supplierModal = new bootstrap.Modal(document.getElementById('supplierModal'));
    
    $('#debtStatus').select2({ theme: "bootstrap-5", minimumResultsForSearch: Infinity });

    var supplierTable = $('#supplierTable').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: "/quanlybanhang/ajax/suppliers_ajax.php",
            type: "POST",
            data: function(d) {
                d.action = 'get_suppliers';
                d.search_term = $('#searchTerm').val();
                d.debt_status = $('#debtStatus').val();
            },
            dataSrc: function(json) {
                if (json && json.summary) {
                    const s = json.summary;
                    $('#summary_total_suppliers').text(formatCurrency(s.total_suppliers));
                    $('#summary_debt_suppliers').text(formatCurrency(s.debt_suppliers));
                    $('#summary_total_debt').text(formatCurrency(s.total_debt) + ' ₫');
                }
                return json.data || [];
            }
        },
        columns: [
            { data: "supplier_code", title: "Mã NCC", render: (data, type, row) => `<a href="details.php?id=${row.ID}" class="fw-bold">${data}</a>` },
            { data: "supplier_name", title: "Tên NCC", render: (data, type, row) => `<a href="details.php?id=${row.ID}">${data}</a>` },
            { data: "supplier_phone", title: "Điện thoại" },
            { data: "tax_code", title: "Mã số thuế" },
            { data: "last_import_date", title: "Lần cuối nhập", render: data => data ? new Date(data).toLocaleDateString('vi-VN') : "<i>Chưa nhập</i>" },
            { data: "total_spent", title: "Tổng nhập", className: "text-end", render: data => formatCurrency(data) + ' ₫'},
            { data: "total_debt", title: "Tổng nợ", className: "text-end text-danger fw-bold", render: data => formatCurrency(data) + ' ₫'},
            { data: "ID", title: "Hành động", orderable: false, className: "text-center", render: function(data) { 
                return `<div class="btn-group btn-group-sm">
                           <button class="btn btn-warning btn-edit" data-id="${data}" title="Sửa"><i class="fas fa-edit"></i></button>
                           <button class="btn btn-danger btn-delete" data-id="${data}" title="Xóa"><i class="fas fa-trash"></i></button>
                        </div>`; 
            }}
        ],
        language: { "url": "/quanlybanhang/assets/libs/datatables/vietnamese.json" },
        pageLength: 10,
        searching: false,
        ordering: true,
        order: [[4, 'desc']],
        dom: "t<'d-flex justify-content-between align-items-center mt-3'<'#summary-info.py-2'>p>"
    });

    $('#filterForm').on('submit', (e) => { e.preventDefault(); supplierTable.ajax.reload(); });
    
    $('#btnOpenAddModal').on('click', function() {
        $('#supplierForm')[0].reset();
        $('#supplier_id').val('');
        $('#supplierModalLabel').text('Thêm Nhà cung cấp mới');
        supplierModal.show();
    });

    $('#supplierTable tbody').on('click', '.btn-edit', function() {
        const supplierId = $(this).data('id');
        $.ajax({
            url: '/quanlybanhang/ajax/suppliers_ajax.php',
            type: 'POST',
            data: { action: 'get_supplier_details', id: supplierId },
            dataType: 'json',
            success: function(response) {
                if(response.status === 'success') {
                    const supplier = response.data;
                    $('#supplier_id').val(supplier.ID);
                    $('#supplier_name').val(supplier.supplier_name);
                    $('#supplier_code').val(supplier.supplier_code);
                    $('#supplier_phone').val(supplier.supplier_phone);
                    $('#supplier_email').val(supplier.supplier_email);
                    $('#supplier_address').val(supplier.supplier_address);
                    $('#tax_code').val(supplier.tax_code);
                    $('#note').val(supplier.note);
                    $('#supplierModalLabel').text('Sửa thông tin Nhà cung cấp');
                    supplierModal.show();
                } else {
                    Swal.fire('Lỗi', response.message, 'error');
                }
            }
        });
    });
    
    $('#btnSaveSupplier').on('click', function() {
        if ($('#supplierForm')[0].checkValidity()) {
            const formData = $('#supplierForm').serialize();
            const action = $('#supplier_id').val() ? 'edit_supplier' : 'add_supplier';
            
            $.ajax({
                url: '/quanlybanhang/ajax/suppliers_ajax.php',
                type: 'POST',
                data: formData + '&action=' + action,
                dataType: 'json',
                success: function(response) {
                    if(response.status === 'success') {
                        supplierModal.hide();
                        supplierTable.ajax.reload(null, false);
                        Swal.fire('Thành công', response.message, 'success');
                    } else {
                        Swal.fire('Lỗi', response.message, 'error');
                    }
                }
            });
        } else {
            $('#supplierForm')[0].reportValidity();
        }
    });

    $('#supplierTable tbody').on('click', '.btn-delete', function() {
        const supplierId = $(this).data('id');
        Swal.fire({
            title: 'Bạn chắc chắn chứ?',
            text: "Bạn sẽ không thể hoàn tác hành động này!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Vâng, xóa nó!',
            cancelButtonText: 'Hủy'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '/quanlybanhang/ajax/suppliers_ajax.php',
                    type: 'POST',
                    data: { action: 'delete_supplier', id: supplierId },
                    dataType: 'json',
                    success: function(response) {
                        if(response.status === 'success') {
                            supplierTable.ajax.reload(null, false);
                            Swal.fire('Đã xóa!', response.message, 'success');
                        } else {
                            Swal.fire('Lỗi', response.message, 'error');
                        }
                    }
                });
            }
        });
    });
});
</script>