<?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; }
    #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">
    <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"></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 class="form-label">Tên NCC <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 class="form-label">Mã NCC</label><input type="text" class="form-control" id="supplier_code" name="supplier_code"></div>
                        <div class="col-md-6 mb-3"><label 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 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 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 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 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</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) {
                    $('#summary_total_suppliers').text(formatCurrency(json.summary.total_suppliers));
                    $('#summary_debt_suppliers').text(formatCurrency(json.summary.debt_suppliers));
                    $('#summary_total_debt').text(formatCurrency(json.summary.total_debt) + ' ₫');
                }
                return json.data || [];
            }
        },
        columns: [
            { data: "supplier_code", title: "Mã NCC", render: (data, type, row) => `<a href="chi_tiet_nha_cung_cap.php?id=${row.ID}" class="fw-bold">${data}</a>` },
            { data: "supplier_name", title: "Tên NCC", render: (data, type, row) => `<a href="chi_tiet_nha_cung_cap.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: function(data) {
                // Sửa lỗi hiển thị ngày nếu data trả về null hoặc format lạ
                if (!data) return "<i>Chưa nhập</i>";
                return new Date(data).toLocaleDateString('vi-VN'); 
            }},
            { 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}"><i class="fas fa-edit"></i></button><button class="btn btn-danger btn-delete" data-id="${data}"><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']]
    });

    $('#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 id = $(this).data('id');
        $.post('/quanlybanhang/ajax/suppliers_ajax.php', { action: 'get_supplier_details', id: id }, function(res) {
            if(res.status === 'success') {
                const d = res.data;
                $('#supplier_id').val(d.ID); $('#supplier_name').val(d.supplier_name); $('#supplier_code').val(d.supplier_code);
                $('#supplier_phone').val(d.supplier_phone); $('#supplier_email').val(d.supplier_email);
                $('#supplier_address').val(d.supplier_addr); $('#tax_code').val(d.tax_code); $('#note').val(d.notes);
                $('#supplierModalLabel').text('Sửa thông tin Nhà cung cấp'); supplierModal.show();
            } else Swal.fire('Lỗi', res.message, 'error');
        }, 'json');
    });
    
    $('#btnSaveSupplier').on('click', function() {
        if ($('#supplierForm')[0].checkValidity()) {
            const action = $('#supplier_id').val() ? 'edit_supplier' : 'add_supplier';
            $.post('/quanlybanhang/ajax/suppliers_ajax.php', $('#supplierForm').serialize() + '&action=' + action, function(res) {
                if(res.status === 'success') { supplierModal.hide(); supplierTable.ajax.reload(null, false); Swal.fire('Thành công', res.message, 'success'); } 
                else Swal.fire('Lỗi', res.message, 'error');
            }, 'json');
        } else $('#supplierForm')[0].reportValidity();
    });

    $('#supplierTable tbody').on('click', '.btn-delete', function() {
        const id = $(this).data('id');
        Swal.fire({ title: 'Xác nhận xóa?', text: "Không thể hoàn tác!", icon: 'warning', showCancelButton: true, confirmButtonText: 'Xóa' }).then((res) => {
            if (res.isConfirmed) {
                $.post('/quanlybanhang/ajax/suppliers_ajax.php', { action: 'delete_supplier', id: id }, function(r) {
                    if(r.status === 'success') { supplierTable.ajax.reload(null, false); Swal.fire('Đã xóa!', r.message, 'success'); } 
                    else Swal.fire('Lỗi', r.message, 'error');
                }, 'json');
            }
        });
    });
});
</script>