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

$customer_groups = [
    ['ID' => '0', 'group_name' => 'Khách sỉ'],
    ['ID' => '1', 'group_name' => 'Khách lẻ']
];
?>
<div class="container-fluid">
    <h1 class="h3 mb-2 text-gray-800">Quản lý Khách hàng</h1>
    
    <div class="row">
        <div class="col-xl-4 col-md-6 mb-4">
            <div class="card border-left-primary shadow h-100 py-2">
                <div class="card-body">
                    <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-xl-4 col-md-6 mb-4">
            <div class="card border-left-danger shadow h-100 py-2">
                <div class="card-body">
                    <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ách Hàng Nợ</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800" id="summary_debt_customers">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-xl-4 col-md-6 mb-4">
            <div class="card border-left-warning shadow h-100 py-2">
                <div class="card-body">
                    <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 Tiền Nợ</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800" id="summary_total_debt">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 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>
            <div>
                <button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#customerModal" id="btnOpenAddCustomerModal">
                    <i class="fas fa-plus fa-sm"></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-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-auto"><button class="btn btn-primary" type="submit"><i class="fas fa-search"></i> Tìm</button></div>
            </form>

            <div class="table-responsive">
                <table class="table table-bordered table-hover" id="customerTable" width="100%" cellspacing="0">
                    <thead>
                        <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 mua</th>
                            <th class="text-end">Tổng nợ</th>
                            <th class="text-center">Hành động</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="customerModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <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="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6 form-group">
                            <label>Nhóm KH</label>
                            <select name="customers_group" id="customers_group" class="form-control">
                                <?php foreach($customer_groups as $group) { echo "<option value='{$group['ID']}'>".htmlspecialchars($group['group_name'])."</option>"; } ?>
                            </select>
                        </div>
                        <div class="col-md-6 form-group"><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 form-group"><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 form-group"><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 form-group"><label>Địa chỉ</label><input type="text" name="customer_addr" id="customer_addr" class="form-control"></div>
                        <div class="col-md-12 form-group"><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-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>
$(document).ready(function() {
    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) => new Intl.NumberFormat('vi-VN').format(num || 0);
                    $('#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: "notes" },
            { data: "group_name" },
            { data: "customer_code", render: (data, type, row) => `<a href="chi_tiet_khach_hang.php?id=${row.ID}" class="fw-bold">${data}</a>` },
            { data: "customer_name", render: (data, type, row) => `<a href="chi_tiet_khach_hang.php?id=${row.ID}">${data}</a>` },
            { data: "customer_phone" },
            { data: "customer_addr" },
            { data: "last_purchase_date", render: data => data ? new Date(data).toLocaleDateString('vi-VN') : "<i>Chưa mua</i>" },
            { data: "total_revenue", className: "text-end", render: $.fn.dataTable.render.number(',', '.', 0, '', ' đ') },
            { data: "total_debt", className: "text-end text-danger", render: $.fn.dataTable.render.number(',', '.', 0, '', ' đ') },
            { data: "ID", orderable: false, className: "text-center", render: function(data) { return `<a href="#" class="btn btn-warning btn-sm btn-edit-customer" data-id="${data}" title="Sửa"><i class="fas fa-edit"></i></a> <a href="#" class="btn btn-danger btn-sm btn-delete-customer ms-1" data-id="${data}" title="Xóa"><i class="fas fa-trash"></i></a>`; }}
        ],
        language: { "url": "/quanlybanhang/assets/libs/datatables/vietnamese.json" },
        pageLength: 10, searching: false, ordering: false,
        columnDefs: [ { "defaultContent": "", "targets": "_all" } ]
    });

    $('#customerFilterForm').on('submit', (e) => { e.preventDefault(); customerTable.ajax.reload(); });
    
    $('#btnOpenAddCustomerModal').on('click', function() {
        $('#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');
        $.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');
                $('#customerForm [name="customers_group"]').val(c.customers_group);
                $('#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_email"]').val(c.customer_email);
                $('#customerForm [name="customer_addr"]').val(c.customer_addr);
                $('#customerForm [name="notes"]').val(c.notes);
                $('#customerModal').modal('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') {
                $('#customerModal').modal('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>