<?php
require_once __DIR__ . '/../../core/init.php';
// Lấy danh sách nhóm khách hàng
$customer_groups_result = $conn->query("SELECT ID, group_name FROM cms_customers_group ORDER BY group_name ASC");
$customer_groups = $customer_groups_result ? $customer_groups_result->fetch_all(MYSQLI_ASSOC) : [];
?>
<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Khách hàng - Nhà cung cấp</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/2.0.8/css/dataTables.bootstrap5.css">
</head>
<body>
    <div class="d-flex" id="wrapper">
        <?php require_once __DIR__ . '/../../templates/sidebar.php'; ?>
        
        <div id="page-content-wrapper" class="w-100 p-4">
            <div class="main-container">
                <ul class="nav nav-tabs" id="myTab" 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"><i class="fas fa-users me-1"></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"><i class="fas fa-truck-moving me-1"></i> Nhà cung cấp</button></li>
                </ul>
                <div class="tab-content" id="myTabContent">
                    <div class="tab-pane fade show active" id="customers-tab-pane" role="tabpanel">
                        
                        <div class="row mt-4">
                            <div class="col-md-4 mb-3">
                                <div class="card border-left-primary shadow-sm h-100">
                                    <div class="card-body p-3">
                                        <div class="row no-gutters align-items-center">
                                            <div class="col mr-2">
                                                <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">KH Mua / Tổng số</div>
                                                <div class="h5 mb-0 font-weight-bold text-gray-800" id="summary_buying_customers">0 / 0</div>
                                            </div>
                                            <div class="col-auto"><i class="fas fa-users fa-2x text-gray-300"></i></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4 mb-3">
                                <div class="card border-left-danger shadow-sm h-100">
                                    <div class="card-body p-3">
                                        <div class="row no-gutters align-items-center">
                                            <div class="col mr-2">
                                                <div class="text-xs font-weight-bold text-danger text-uppercase mb-1">KH Nợ / KH Mua</div>
                                                <div class="h5 mb-0 font-weight-bold text-gray-800" id="summary_debt_customers">0 / 0</div>
                                            </div>
                                            <div class="col-auto"><i class="fas fa-user-clock fa-2x text-gray-300"></i></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4 mb-3">
                                <div class="card border-left-warning shadow-sm h-100">
                                    <div class="card-body p-3">
                                        <div class="row no-gutters align-items-center">
                                            <div class="col mr-2">
                                                <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Tổng Nợ / Tổng Mua</div>
                                                <div class="h5 mb-0 font-weight-bold text-gray-800" id="summary_debt_amount">0 / 0</div>
                                            </div>
                                            <div class="col-auto"><i class="fas fa-dollar-sign fa-2x text-gray-300"></i></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="card shadow-sm mt-3">
                            <div class="card-header bg-white d-flex justify-content-between align-items-center">
                                <div><a href="#" class="btn btn-outline-secondary btn-sm"><i class="fas fa-file-alt me-1"></i> File mẫu</a></div>
                                <div><button type="button" id="btnExportCustomers" class="btn btn-success btn-sm"><i class="fas fa-file-excel me-1"></i> Xuất Excel</button><button type="button" class="btn btn-primary btn-sm ms-2" id="btnOpenAddCustomerModal"><i class="fas fa-plus me-1"></i> Tạo KH</button></div>
                            </div>
                            <div class="card-body">
                                <form id="customerFilterForm" class="row g-2 mb-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-select" id="customerFilterGroup">
                                            <option value="">Tất cả nhóm</option>
                                            <option value="1">Khách lẻ</option>
                                            <option value="0">Khách sỉ</option>
                                        </select>
                                    </div>
                                    <div class="col-md-3">
                                        <select class="form-select" id="customerDebtStatus">
                                            <option value="">Tất cả tình trạng</option>
                                            <option value="debt">Khách hàng đang nợ</option>
                                        </select>
                                    </div>
                                    <div class="col-auto"><button class="btn btn-light border" type="submit"><i class="fas fa-search"></i> Tìm kiếm</button></div>
                                </form>
                                <div class="table-responsive">
                                    <table class="table table-bordered table-hover align-middle" id="customerTable" style="width:100%;">
                                        <thead class="table-light">
                                            <tr>
                                                <th>Mã số thuế</th> <th>Nhóm</th> <th>Mã KH</th> <th>Tên KH</th>
                                                <th>Điện thoại</th> <th>Địa chỉ</th> <th>Lần cuối mua</th>
                                                <th class="text-end">Tổng tiền</th> <th class="text-end">Nợ</th>
                                                <th class="text-center">Hành động</th>
                                            </tr>
                                        </thead>
                                        <tbody></tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                    </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.datatables.net/2.0.8/js/dataTables.js"></script>
    <script src="https://cdn.datatables.net/2.0.8/js/dataTables.bootstrap5.js"></script>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.datatables.net/2.0.8/js/dataTables.js"></script>
<script src="https://cdn.datatables.net/2.0.8/js/dataTables.bootstrap5.js"></script>
<script>
        $(document).ready(function() {
            var customerTable = $('#customerTable').DataTable({
                processing: true,
                serverSide: true,
                ajax: {
                    url: "/quanlybanhang/ajax/customers_ajax.php",
                    type: "POST",
                    data: function(d) {
                        d.search_term = $('#customerSearchTerm').val();
                        d.group_id = $('#customerFilterGroup').val();
                    }
                },
                // SỬA LẠI CÁC CỘT ĐỂ HIỂN THỊ MST
                columns: [{
                    data: "notes", // Lấy dữ liệu từ cột 'notes'
                    defaultContent: "<i>(chưa có)</i>"
                }, {
                    data: "group_name",
                    defaultContent: ""
                }, {
                    data: "customer_code",
                    render: (data, type, row) => `<a class="fw-bold text-decoration-none" href="chi_tiet_khach_hang.php?id=${row.ID}">${data}</a>`
                }, {
                    data: "customer_name",
                    render: (data, type, row) => `<a class="text-decoration-none" href="chi_tiet_khach_hang.php?id=${row.ID}">${data}</a>`
                }, {
                    data: "customer_phone",
                    defaultContent: ""
                }, {
                    data: "customer_addr",
                    defaultContent: ""
                }, {
                    data: "last_purchase_date",
                    render: data => data ? new Date(data).toLocaleDateString('vi-VN') : "<i>Chưa mua</i>"
                }, {
                    data: "total_revenue",
                    className: "text-end fw-bold",
                    render: $.fn.dataTable.render.number(',', '.', 0, '')
                }, {
                    data: "total_debt",
                    className: "text-end text-danger",
                    render: $.fn.dataTable.render.number(',', '.', 0, '')
                }, {
                    data: null,
                    orderable: false,
                    className: "text-center",
                    render: function(data, type, row) {
                        return `<a href="chi_tiet_khach_hang.php?id=${row.ID}" class="text-primary action-icons" title="Xem"><i class="fas fa-eye"></i></a><a href="#" class="text-warning ms-2 btn-edit-customer" data-id="${row.ID}" title="Sửa"><i class="fas fa-edit"></i></a><a href="#" class="text-danger ms-2 btn-delete-customer" data-id="${row.ID}" title="Xóa"><i class="fas fa-trash"></i></a>`;
                    }
                }],
                language: { url: "/quanlybanhang/assets/libs/datatables/vietnamese.json" },
                pageLength: 10,
                searching: false,
                ordering: false
            });

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

            $('#customerTable tbody').on('click', '.btn-edit-customer', function(e) {
                e.preventDefault();
                var customerId = $(this).data('id');
                $.ajax({
                    url: '/quanlybanhang/ajax/customers_ajax.php', type: 'GET', dataType: 'json',
                    data: { action: 'get_customer_details', id: customerId },
                    success: 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');
                            $('select[name="customer_group"]').val(c.customer_group);
                            $('input[name="customer_code"]').val(c.customer_code);
                            $('input[name="customer_name"]').val(c.customer_name);
                            $('input[name="customer_phone"]').val(c.customer_phone);
                            $('input[name="customer_email"]').val(c.customer_email);
                            $('input[name="customer_addr"]').val(c.customer_addr);
                            $('input[name="customer_birthday"]').val(c.customer_birthday);
                            // SỬA LẠI: Lấy MST từ cột 'notes' và điền vào form
                            $('input[name="notes"]').val(c.notes);
                            if (c.customer_gender == 1) { $('#genderMale').prop('checked', true); }
                            else { $('#genderFemale').prop('checked', true); }
                            $('#customerModal').modal('show');
                        } else { alert(response.message); }
                    }
                });
            });

            $('#customerForm').on('submit', function(e) {
                e.preventDefault();
                // Thay đổi quan trọng: Lấy giá trị từ ô MST và gán vào `notes` trong FormData
                var formData = new FormData(this);
                formData.append('action', 'save_customer');

                var $btn = $(this).find('button[type="submit"]');
                $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span> Đang lưu...');
                $.ajax({
                    url: '/quanlybanhang/ajax/customers_ajax.php', type: 'POST', data: formData, processData: false, contentType: false, dataType: 'json',
                    success: function(response) {
                        alert(response.message);
                        if (response.status === 'success') {
                            $('#customerModal').modal('hide');
                            customerTable.ajax.reload();
                        }
                    },
                    error: () => alert('Lỗi! Không thể gửi yêu cầu.'),
                    complete: () => $btn.prop('disabled', false).html('Lưu')
                });
            });
            
            // Các hàm xóa, export giữ nguyên
            $('#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();
                    }, 'json');
                }
            });
             $('#btnExportCustomers').on('click', function() {
                const term = $('#customerSearchTerm').val(), group = $('#customerFilterGroup').val();
                window.location.href = `export_customers_csv.php?search_term=${encodeURIComponent(term)}&group_id=${encodeURIComponent(group)}`;
            });
        });
    </script>
</body>
</html>