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

$customer_groups = [
    ['ID' => '0', 'group_name' => 'Khách sỉ'],
    ['ID' => '1', 'group_name' => 'Khách lẻ']
];
?>

<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); }
    
    #customerTable thead th { background-color:#4e73df !important; color:#ffffff !important; font-weight:bold; vertical-align: middle; }
    #customerTable tbody tr:nth-child(even) { background-color: #f8f9fc; }
    #customerTable tbody tr:hover { background-color: #eaecf4; }

    #customerModal .modal-content { border: none; border-radius: 0.75rem; }
    #customerModal .modal-header { background-color: #f8f9fc; border-bottom: 1px solid #e3e6f0; padding: 1rem 1.5rem; }
    #customerModal .modal-title { font-weight: 600; font-size: 1.2rem; color: #3a3b45; }
    #customerModal .modal-body { padding: 1.5rem; }
    #customerModal .form-label { font-weight: 500; color: #6c757d; margin-bottom: 0.5rem; }
    #customerModal .form-control, #customerModal .form-select, #customerModal .select2-selection { border-radius: 0.5rem !important; }
    #customerModal .modal-footer { background-color: #f8f9fc; border-top: 1px solid #e3e6f0; padding: 1rem 1.5rem; }
</style>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800">Quản lý Khách hàng</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;">KH Đã Mua / Tổng Số</div><div class="value" id="summary_buying_customers">0 / 0</div></div><div class="icon-circle" style="background-color: #4e73df;"><i class="fas fa-users"></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;">Khách Hàng Nợ</div><div class="value" id="summary_debt_customers">0</div></div><div class="icon-circle" style="background-color: #f6c23e;"><i class="fas fa-user-clock"></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 Nợ</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 khách hàng</h6>
            <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#customerModal" id="btnOpenAddCustomerModal"><i class="fas fa-plus fa-sm"></i> Tạo KH</button>
        </div>
        <div class="card-body">
            <div class="card mb-4 filter-card">
                <div class="card-body">
                    <form id="customerFilterForm" class="row gx-3 align-items-center">
                        <div class="col-md-4"><input type="text" id="customerSearchTerm" class="form-control" placeholder="Nhập tên, mã hoặc SĐT khách hàng"></div>
                        <div class="col-md-3"><select class="form-control" id="customerFilterGroup"><option value="">Tất cả nhóm</option><?php foreach($customer_groups as $group) { echo "<option value='{$group['ID']}'>".htmlspecialchars($group['group_name'])."</option>"; } ?></select></div>
                        <div class="col-md-3"><select class="form-control" id="customerDebtStatus"><option value="">Tất cả tình trạng</option><option value="debt">Khách hàng đang nợ</option><option value="no_debt">Khách hàng 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="customerTable" width="100%" cellspacing="0"></table>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="customerModal" tabindex="-1" aria-labelledby="customerModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form id="customerForm">
                <input type="hidden" name="customer_id" id="customer_id">
                <div class="modal-header">
                    <h5 class="modal-title" id="customerModalLabel">Tạo mới khách hàng</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6 mb-3"><label class="form-label">Nhóm KH</label><select name="customer_group" id="customer_group" class="form-select" style="width: 100%;"><?php foreach($customer_groups as $group) { echo "<option value='{$group['ID']}'>".htmlspecialchars($group['group_name'])."</option>"; } ?></select></div>
                        <div class="col-md-6 mb-3"><label class="form-label">Mã khách hàng</label><input type="text" name="customer_code" id="customer_code" class="form-control" placeholder="Tự sinh nếu bỏ trống"></div>
                        <div class="col-md-6 mb-3"><label class="form-label">Tên khách hàng <span class="text-danger">*</span></label><input type="text" name="customer_name" id="customer_name" class="form-control" required></div>
                        <div class="col-md-6 mb-3"><label class="form-label">Số điện thoại</label><input type="text" name="customer_phone" id="customer_phone" class="form-control"></div>
                        <div class="col-md-12 mb-3"><label class="form-label">Địa chỉ</label><input type="text" name="customer_addr" id="customer_addr" class="form-control"></div>
                        <div class="col-md-12 mb-3"><label class="form-label">Mã số thuế</label><input type="text" name="notes" id="notes" class="form-control"></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/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.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 customerGroupsMap = <?php echo json_encode(array_column($customer_groups, 'group_name', 'ID')); ?>;

    $('#customerFilterGroup, #customerDebtStatus').select2({ theme: "bootstrap-5", minimumResultsForSearch: Infinity });

    $('#customer_group').select2({
        theme: "bootstrap-5",
        dropdownParent: $('#customerModal'),
        minimumResultsForSearch: Infinity
    });

    var customerTable = $('#customerTable').DataTable({
        processing: true, serverSide: true,
        ajax: {
            url: "/quanlybanhang/ajax/customers_ajax.php",
            type: "POST",
            data: function(d) {
                d.action = 'get_customers';
                d.search_term = $('#customerSearchTerm').val();
                d.group_id = $('#customerFilterGroup').val();
                d.debt_status = $('#customerDebtStatus').val();
            },
            dataSrc: function(json) {
                if (json && json.summary) {
                    const summary = json.summary;
                    const format = (num) => (parseFloat(num) || 0).toLocaleString('vi-VN');
                    $('#summary_total_customers').text(format(summary.total_customers));
                    $('#summary_debt_customers').text(format(summary.debt_customers));
                    $('#summary_total_debt').text(format(summary.total_debt) + ' ₫');
                    $('#summary_buying_customers').text(`${format(summary.buying_customers)} / ${format(summary.total_customers)}`);
                }
                if (json && json.error) { alert('Đã có lỗi xảy ra: ' + json.error); }
                return json.data || [];
            }
        },
        columns: [
            { data: "customer_code", title: "Mã KH", render: (data, type, row) => `<a href="chi_tiet_khach_hang.php?id=${row.ID}" class="fw-bold">${data}</a>` },
            { data: "customer_name", title: "Tên KH", render: (data, type, row) => `<a href="chi_tiet_khach_hang.php?id=${row.ID}">${data}</a>` },
            { data: "customer_group", title: "Nhóm", render: (data) => customerGroupsMap[data] || 'N/A' },
            { data: "customer_phone", title: "Điện thoại" },
            { data: "customer_addr", title: "Địa chỉ" },
            { data: "total_revenue", title: "Tổng mua", className: "text-end", render: data => (parseFloat(data) || 0).toLocaleString('vi-VN') + ' ₫'},
            { data: "total_debt", title: "Tổng nợ", className: "text-end text-danger fw-bold", render: data => (parseFloat(data) || 0).toLocaleString('vi-VN') + ' ₫'},
            { data: "last_purchase_date", title: "Lần cuối mua", render: data => data ? new Date(data).toLocaleDateString('vi-VN') : "<i>Chưa mua</i>" },
            { data: "notes", title: "Mã số thuế" },
            { data: "ID", title: "Hành động", orderable: false, className: "text-center", render: function(data) { return `<div class="btn-group btn-group-sm"><a href="#" class="btn btn-warning btn-edit-customer" data-id="${data}" title="Sửa"><i class="fas fa-edit"></i></a> <a href="#" class="btn btn-danger btn-delete-customer" data-id="${data}" title="Xóa"><i class="fas fa-trash"></i></a></div>`; }}
        ],
        language: { "url": "/quanlybanhang/assets/libs/datatables/vietnamese.json" },
        pageLength: 10, searching: false, ordering: false,
        dom: "t<'d-flex justify-content-between align-items-center mt-3'<'#summary-info.py-2'>p>",
    });

    $('#customerFilterForm').on('submit', (e) => { e.preventDefault(); customerTable.ajax.reload(); });
    
    $('#btnOpenAddCustomerModal').on('click', function() {
        $('#customerForm')[0].reset();
        $('#customer_id').val('');
        $('#customer_group').val('1').trigger('change');
        $('#customerModalLabel').text('Tạo mới khách hàng');
    });

    $('#customerTable tbody').on('click', '.btn-edit-customer', function(e) {
        e.preventDefault();
        var customerId = $(this).data('id');
        $.get('/quanlybanhang/ajax/customers_ajax.php', { action: 'get_customer_details', id: customerId }, function(response) {
            if (response.status === 'success') {
                var c = response.data;
                $('#customer_id').val(c.ID);
                $('#customerModalLabel').text('Chỉnh sửa khách hàng: ' + c.customer_name);
                $('#customerForm [name="customer_group"]').val(c.customer_group).trigger('change');
                $('#customerForm [name="customer_code"]').val(c.customer_code);
                $('#customerForm [name="customer_name"]').val(c.customer_name);
                $('#customerForm [name="customer_phone"]').val(c.customer_phone);
                $('#customerForm [name="customer_addr"]').val(c.customer_addr);
                $('#customerForm [name="notes"]').val(c.notes);
                var customerModal = new bootstrap.Modal(document.getElementById('customerModal'));
                customerModal.show();
            } else { alert(response.message); }
        }, 'json');
    });
    
    $('#customerForm').on('submit', function(e) {
        e.preventDefault();
        var formData = $(this).serialize() + '&action=save_customer';
        $.post('/quanlybanhang/ajax/customers_ajax.php', formData, function(response) {
            alert(response.message);
            if (response.status === 'success') {
                var customerModal = bootstrap.Modal.getInstance(document.getElementById('customerModal'));
                customerModal.hide();
                customerTable.ajax.reload(null, false);
            }
        }, 'json');
    });
    
    $('#customerTable tbody').on('click', '.btn-delete-customer', function(e) {
        e.preventDefault();
        var customerId = $(this).data('id');
        if (confirm('Bạn có chắc muốn XÓA VĨNH VIỄN khách hàng này?')) {
            $.post('/quanlybanhang/ajax/customers_ajax.php', { action: 'delete_customer', id: customerId }, function(response) {
                alert(response.message);
                if (response.status === 'success') customerTable.ajax.reload(null, false);
            }, 'json');
        }
    });
});
</script>