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

// Lấy dữ liệu cho cả 2 tab
$customer_groups_data = $conn->query("SELECT ID, group_name FROM cms_customers_group ORDER BY group_name ASC")->fetch_all(MYSQLI_ASSOC);
?>

<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>
    .nav-tabs .nav-link { margin-bottom: -2px; border-top-left-radius: .5rem; border-top-right-radius: .5rem; }
    .nav-tabs .nav-link.active { font-weight: bold; color: #4e73df; border-color: #dee2e6 #dee2e6 #fff; }
    .tab-content > .tab-pane { padding: 1.5rem; }
    .tab-content { border: 1px solid #dee2e6; border-top: 0; border-bottom-left-radius: .5rem; border-bottom-right-radius: .5rem; }
    .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, #supplierTable thead th { background-color:#4e73df !important; color:#ffffff !important; font-weight:bold; vertical-align: middle; }
    #customerTable tbody tr:nth-child(even), #supplierTable tbody tr:nth-child(even) { background-color: #f8f9fc; }
    #customerTable tbody tr:hover, #supplierTable tbody tr:hover { background-color: #eaecf4; }
</style>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800">Quản lý Khách hàng & NCC</h1>

    <ul class="nav nav-tabs" id="partnerTab" role="tablist">
        <li class="nav-item" role="presentation">
            <button class="nav-link active" id="customers-tab" data-bs-toggle="tab" data-bs-target="#customers-tab-pane" type="button" role="tab" aria-controls="customers-tab-pane" aria-selected="true">
                <i class="fas fa-user me-2"></i>Khách hàng
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="suppliers-tab" data-bs-toggle="tab" data-bs-target="#suppliers-tab-pane" type="button" role="tab" aria-controls="suppliers-tab-pane" aria-selected="false">
                <i class="fas fa-truck me-2"></i>Nhà cung cấp
            </button>
        </li>
    </ul>

    <div class="tab-content" id="partnerTabContent">
        <div class="tab-pane fade show active" id="customers-tab-pane" role="tabpanel" aria-labelledby="customers-tab" tabindex="0">
            <div class="row pt-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="d-flex justify-content-between align-items-center mb-3">
                <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"><i class="fas fa-plus fa-sm"></i> Tạo KH</button>
            </div>
            <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" data-placeholder="Tất cả nhóm"><option value=""></option><?php foreach($customer_groups_data 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" data-placeholder="Tất cả tình trạng"><option value=""></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 class="tab-pane fade" id="suppliers-tab-pane" role="tabpanel" aria-labelledby="suppliers-tab" tabindex="0">
             <div class="row pt-4">
                <div class="col-xl-3 col-md-6 mb-4"><div class="card summary-card"><div class="card-body"><div class="text-content"><div class="label">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-clipboard-list"></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">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-3 col-md-6 mb-4"><div class="card summary-card"><div class="card-body"><div class="text-content"><div class="label">Tổng Nợ NCC</div><div class="value" id="summary-total-debt-supplier">0 ₫</div></div><div class="icon-circle" style="background-color:#e74a3b;"><i class="fas fa-hourglass-half"></i></div></div></div></div>
            </div>
            <div class="d-flex justify-content-between align-items-center mb-3">
                <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" data-bs-toggle="modal" data-bs-target="#supplierModal"><i class="fas fa-plus fa-sm"></i> Tạo NCC</button>
            </div>
             <div class="card mb-4 filter-card">
                <div class="card-body">
                    <form id="supplierFilterForm" class="row gx-3 align-items-center">
                        <div class="col-md-6"><input type="text" id="supplierSearchTerm" 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="supplierDebtStatus" data-placeholder="Tất cả tình trạng"><option value=""></option><option value="debt">NCC đang 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="customerModal"></div>
<div class="modal fade" id="supplierModal"></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() {
    // --- LOGIC CHO TAB KHÁCH HÀNG ---
    $('#customerFilterGroup, #customerDebtStatus').select2({ theme: "bootstrap-5", allowClear: true });
    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 s = json.summary;
                    const format = (num) => (num || 0).toLocaleString('vi-VN');
                    $('#summary_buying_customers').text(`${format(s.buying_customers)} / ${format(s.total_customers)}`);
                    $('#summary_debt_customers').text(format(s.debt_customers));
                    $('#summary_total_debt').text(format(s.total_debt) + ' ₫');
                }
                return json.data || [];
            }
        },
        columns: [
            { data: "notes", title: "Mã số thuế" },
            { data: "group_name", title: "Nhóm" },
            { data: "customer_code", title: "Mã KH", render: (data, type, row) => `<a href="../customers/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="../customers/chi_tiet_khach_hang.php?id=${row.ID}">${data}</a>` },
            { data: "customer_phone", title: "Điện thoại" },
            { data: "customer_addr", title: "Địa chỉ" },
            { 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: "total_revenue", title: "Tổng mua", className: "text-end", render: data => (data || 0).toLocaleString('vi-VN') + ' ₫'},
            { data: "total_debt", title: "Tổng nợ", className: "text-end text-danger fw-bold", render: data => (data || 0).toLocaleString('vi-VN') + ' ₫'},
            { 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" data-id="${data}" title="Sửa"><i class="fas fa-edit"></i></a> <a href="#" class="btn btn-danger" 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-customer.py-2'>p>",
    });
    $('#customerFilterForm').on('submit', (e) => { e.preventDefault(); customerTable.ajax.reload(); });

    // --- LOGIC CHO TAB NHÀ CUNG CẤP ---
    $('#supplierDebtStatus').select2({ theme: "bootstrap-5", allowClear: true });
    var supplierTable; // Khai báo biến ở đây
    
    // Chỉ khởi tạo bảng Nhà cung cấp khi tab được chọn lần đầu
    $('button[data-bs-target="#suppliers-tab-pane"]').one('shown.bs.tab', function(){
        if (!$.fn.DataTable.isDataTable('#supplierTable')) {
            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 = $('#supplierSearchTerm').val();
                        d.debt_status = $('#supplierDebtStatus').val();
                    },
                    dataSrc: function(json) {
                        if (json && json.summary) {
                            const s = json.summary;
                            const format = (num) => (num || 0).toLocaleString('vi-VN');
                            $('#summary-total-suppliers').text(format(s.total_suppliers));
                            $('#summary_debt_suppliers').text(format(s.debt_suppliers));
                            $('#summary-total-debt-supplier').text(format(s.total_debt) + ' ₫');
                        }
                        return json.data || [];
                    }
                },
                columns: [
                    { data: "supplier_code", title: "Mã NCC", render: (data, type, row) => `<a href="../suppliers/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="../suppliers/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: 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 => (data || 0).toLocaleString('vi-VN') + ' ₫'},
                    { data: "total_debt", title: "Tổng nợ", className: "text-end text-danger fw-bold", render: data => (data || 0).toLocaleString('vi-VN') + ' ₫'},
                    { 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" data-id="${data}" title="Sửa"><i class="fas fa-edit"></i></a> <a href="#" class="btn btn-danger" 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-supplier.py-2'>p>",
            });
        }
    });
    $('#supplierFilterForm').on('submit', (e) => { e.preventDefault(); if(supplierTable) { supplierTable.ajax.reload(); } });

    // Điều chỉnh lại cột của bảng khi chuyển tab để không bị xô lệch
    $('button[data-bs-toggle="tab"]').on('shown.bs.tab', function (e) {
        $($.fn.dataTable.tables(true)).DataTable().columns.adjust();
    });
});
</script>