<?php
require_once __DIR__ . '/../../core/init.php';

if (!isset($_GET['id']) || empty($_GET['id'])) { die('Không có khách hàng nào được chọn.'); }
$customer_id = intval($_GET['id']);

$stmt = $conn->prepare("SELECT c.*, g.group_name FROM cms_customers c LEFT JOIN cms_customers_group g ON c.customer_group = g.ID WHERE c.ID = ?");
$stmt->bind_param("i", $customer_id);
$stmt->execute();
$customer = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$customer) { die('Không tìm thấy khách hàng.'); }

$order_history_result = $conn->query("SELECT * FROM cms_orders WHERE customer_id = {$customer_id} ORDER BY sell_date DESC");
$order_history = $order_history_result ? $order_history_result->fetch_all(MYSQLI_ASSOC) : [];

$debt_orders = array_filter($order_history, function($order) { return isset($order['lack']) && $order['lack'] > 0; });
$total_invoices = count($order_history);
$total_spent = array_sum(array_column($order_history, 'total_money'));
$total_debt = array_sum(array_column($order_history, 'lack'));
$current_user_name = $_SESSION['display_name'] ?? 'Guest';
?>
<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chi tiết KH - <?php echo htmlspecialchars($customer['customer_name']); ?></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">
    <style>
	/* Thêm style để layout sidebar và content hoạt động tốt */
        #wrapper {
            display: flex;
        }
        #page-content-wrapper {
            width: 100%;
        }
        /* Style cơ bản cho sidebar (bạn có thể đã có trong file css chung) */
        #sidebar-wrapper {
            min-height: 100vh;
            width: 250px;
            background-color: #fff;
            border-right: 1px solid #dee2e6;
        }
        #sidebar-wrapper .list-group-item {
            border-radius: 0;
            border-left: 0;
            border-right: 0;
            border-top: 1px solid #dee2e6;
        }
        #sidebar-wrapper .list-group-item:first-child {
            border-top: 0;
        }
        #sidebar-wrapper .list-group-item.active {
            background-color: #f89021;
            color: white;
            border-color: #f89021;
        } 
		</style>
</head>
<body>
<div class="d-flex" id="wrapper">
    <?php require_once __DIR__ . '/../../templates/sidebar.php'; ?>
    <div id="page-content-wrapper" class="w-100">
        <div class="container-fluid p-4">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h2 class="mb-0">Thông tin khách hàng</h2>
                <div>
                    <button type="button" class="btn btn-warning" id="btnEditCustomer" data-id="<?php echo $customer_id; ?>"><i class="fas fa-edit me-1"></i> Sửa</button>
                    <a href="list.php" class="btn btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> Trở về</a>
                </div>
            </div>
            <div class="info-section p-4 mb-4">
                <div class="row">
                    <div class="col-md-6"><dl class="row info-dl mb-0">
    <dt class="col-sm-4">Mã khách hàng</dt><dd class="col-sm-8"><?php echo htmlspecialchars($customer['customer_code']); ?></dd>
    <dt class="col-sm-4">Email</dt><dd class="col-sm-8"><?php echo htmlspecialchars($customer['customer_email'] ?: '(chưa có)'); ?></dd>
    <dt class="col-sm-4">Ngày sinh</dt><dd class="col-sm-8"><?php echo !empty($customer['customer_birthday']) ? date('d/m/Y', strtotime($customer['customer_birthday'])) : '(chưa có)'; ?></dd>
    
    <dt class="col-sm-4">Mã số thuế</dt><dd class="col-sm-8"><?php echo htmlspecialchars($customer['notes'] ?: '(chưa có)'); ?></dd>

</dl></div>

                </div>
            </div>
            <div id="historyView">
                <div class="info-section">
                    <div class="p-3 d-flex justify-content-between align-items-center"><h4 class="mb-0">Lịch sử mua hàng</h4><?php if ($total_debt > 0): ?><button class="btn btn-success" id="btnShowCollectDebt"><i class="fas fa-hand-holding-usd me-1"></i> Thu nợ</button><?php endif; ?></div>
                    <div class="table-responsive">
                        <table class="table table-hover mb-0" id="orderHistoryTable">
                            <thead class="table-light"><tr><th class="text-center expand-cell"></th><th>Mã đơn hàng</th><th>Ngày bán</th><th>Thu ngân</th><th>Trạng thái</th><th class="text-end">Tổng tiền</th><th class="text-end">Khách trả</th><th class="text-end">Nợ</th><th class="text-center">Hành động</th></tr></thead>
                            <tbody>
                                <?php if (!empty($order_history)): foreach ($order_history as $order): ?>
                                    <tr data-order-id="<?php echo $order['ID']; ?>">
                                        <td class="text-center expand-cell"><button class="btn btn-sm btn-outline-primary btn-expand-details">+</button></td>
                                        <td><a href="#"><?php echo htmlspecialchars($order['output_code']); ?></a></td>
                                        <td><?php echo date('d/m/Y H:i', strtotime($order['sell_date'])); ?></td><td></td><td><span class="badge bg-success">Hoàn thành</span></td>
                                        <td class="text-end"><?php echo number_format($order['total_money']); ?></td><td class="text-end"><?php echo number_format($order['customer_pay']); ?></td>
                                        <td class="text-end text-danger fw-bold"><?php echo number_format($order['lack']); ?></td>
                                        <td class="text-center"><a href="#" title="In phiếu"><i class="fas fa-print"></i></a></td>
                                    </tr>
                                <?php endforeach; else: ?><tr><td colspan="9" class="text-center p-4">Chưa có lịch sử mua hàng.</td></tr><?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                    <div class="card-footer d-flex justify-content-end fw-bold"><span>Tổng số hóa đơn: <span class="text-primary"><?php echo $total_invoices; ?></span></span><span class="ms-4">Tổng tiền: <span class="text-primary"><?php echo number_format($total_spent); ?></span></span><span class="ms-4">Tổng nợ: <span class="text-danger"><?php echo number_format($total_debt); ?></span></span></div>
                </div>
            </div>
            <div id="collectDebtView" style="display: none;">
                <div class="info-section"><div class="p-3">
                    <h4 class="mb-3">Thu nợ</h4>
                    <div class="table-responsive"><table class="table"><thead class="table-light"><tr><th>Mã đơn hàng</th><th>Ngày bán</th><th class="text-end">Nợ</th><th style="width: 180px;">Thu nợ</th><th style="width: 100px;"></th></tr></thead><tbody>
                        <?php if (!empty($debt_orders)): foreach ($debt_orders as $order): ?>
                        <tr class="debt-row" data-order-id="<?php echo $order['ID']; ?>"><<td><a href="#"><?php echo htmlspecialchars($order['output_code']); ?></a></td><td><?php echo date('d/m/Y', strtotime($order['sell_date'])); ?></td><td class="text-end text-danger fw-bold"><?php echo number_format($order['lack']); ?></td><td><input type="number" class="form-control form-control-sm amount-to-collect" placeholder="Số tiền thu" max="<?php echo $order['lack']; ?>"></td><td><button class="btn btn-sm btn-primary btn-collect-single">Thu</button></td></tr>
                        <?php endforeach; else: ?><tr><td colspan="5" class="text-center">Khách hàng không có công nợ.</td></tr><?php endif; ?>
                    </tbody></table></div><hr><button class="btn btn-secondary" id="btnBackToHistory">Quay lại lịch sử</button>
                </div></div>
            </div>
        </div>
    </div>
</div>
    <div class="modal fade modal-lg" id="customerModal" tabindex="-1"><div class="modal-dialog modal-dialog-scrollable"><div class="modal-content">
        <form id="customerForm" enctype="multipart/form-data">
            <input type="hidden" name="customer_id" id="customer_id"><input type="hidden" name="existing_image_url" id="existing_image_url">
            <div class="modal-header"><h5 class="modal-title" id="customerModalLabel"></h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body"><div class="row">
                <div class="col-md-12 mb-3"><label class="form-label">Nhóm KH</label><select name="customer_group" class="form-select"><option value="1">Khách lẻ</option><option value="0">Khách sỉ</option></select></div>
                <div class="col-md-6 mb-3"><label class="form-label">Mã KH</label><input type="text" name="customer_code" class="form-control" placeholder="Tự sinh nếu trống"></div>
                <div class="col-md-6 mb-3"><label class="form-label">Tên KH <span class="text-danger">*</span></label><input type="text" name="customer_name" class="form-control" required></div>
                <div class="col-md-6 mb-3"><label class="form-label">SĐT</label><input type="text" name="customer_phone" class="form-control"></div>
                <div class="col-md-6 mb-3"><label class="form-label">Email</label><input type="email" name="customer_email" class="form-control"></div>
                <div class="col-md-12 mb-3"><label class="form-label">MST</label><input type="text" name="customer_tax" class="form-control"></div>
                <div class="col-md-12 mb-3"><label class="form-label">Địa chỉ</label><input type="text" name="customer_addr" class="form-control"></div>
                <div class="col-md-6 mb-3"><label class="form-label">Ngày sinh</label><input type="date" name="customer_birthday" class="form-control"></div>
                <div class="col-md-6 mb-3"><label class="form-label">Giới tính</label><div><div class="form-check form-check-inline"><input class="form-check-input" type="radio" name="customer_gender" id="genderMale" value="1" checked><label class="form-check-label" for="genderMale">Nam</label></div><div class="form-check form-check-inline"><input class="form-check-input" type="radio" name="customer_gender" id="genderFemale" value="0"><label class="form-check-label" for="genderFemale">Nữ</label></div></div></div>
                <div class="col-md-12 mb-3"><label class="form-label">Ảnh</label><input class="form-control" type="file" name="customer_image"></div>
                <div class="col-md-12 mb-3"><label class="form-label">Ghi chú</label><textarea name="notes" class="form-control" rows="2"></textarea></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>
    <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>
    $(document).ready(function() {
        $('#orderHistoryTable tbody').on('click', '.btn-expand-details', function() {
            var $button = $(this); var $row = $button.closest('tr'); var orderId = $row.data('order-id'); var detailRow = $row.next('.detail-row');
            if (detailRow.length) { detailRow.remove(); $button.text('+');
            } else {
                $button.html('<span class="spinner-border spinner-border-sm"></span>');
                $.ajax({
                    url: '/quanlybanhang/ajax/customers_ajax.php', type: 'GET', dataType: 'json', data: { action: 'get_order_details', order_id: orderId },
                    success: function(response) {
                        if (response.status === 'success') {
                            var detailsHtml = '<div class="p-3"><table class="table table-sm detail-table"><thead><tr class="table-secondary"><th>STT</th><th>Mã SP</th><th>Tên sản phẩm</th><th class="text-end">SL</th><th class="text-end">Giá bán</th><th class="text-end">Thành tiền</th></tr></thead><tbody>';
                            if(response.data && response.data.length > 0) {
                                response.data.forEach((item, index) => {
                                    detailsHtml += `<tr><td>${index + 1}</td><td>${item.prd_code || ''}</td><td>${item.prd_name || '(Không có tên)'}</td><td class="text-end">${item.quantity || 0}</td><td class="text-end">${(item.price || 0).toLocaleString('vi-VN')}</td><td class="text-end">${((item.quantity || 0) * (item.price || 0)).toLocaleString('vi-VN')}</td></tr>`;
                                });
                            } else { detailsHtml += '<tr><td colspan="6" class="text-center">Không có chi tiết sản phẩm.</td></tr>'; }
                            detailsHtml += '</tbody></table></div>';
                            var newRow = '<tr class="detail-row"><td colspan="9">' + detailsHtml + '</td></tr>';
                            $row.after(newRow); $button.text('-');
                        } else { alert(response.message); $button.text('+'); }
                    },
                    error: function() { alert('Lỗi khi tải chi tiết đơn hàng.'); $button.text('+'); }
                });
            }
        });
        $('#btnShowCollectDebt').on('click', function() { $('#historyView').hide(); $('#collectDebtView').show(); });
        $('#btnBackToHistory').on('click', function() { $('#collectDebtView').hide(); $('#historyView').show(); });
        $('#collectDebtView').on('click', '.btn-collect-single', function() {
            var $button = $(this), $row = $button.closest('tr'), orderId = $row.data('order-id'), amount = $row.find('.amount-to-collect').val();
            if (!amount || parseInt(amount) <= 0) { alert('Vui lòng nhập số tiền hợp lệ.'); return; }
            if (confirm(`Bạn có chắc muốn thu nợ ${parseInt(amount).toLocaleString('vi-VN')} cho đơn hàng này?`)) {
                $button.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span>');
                $.ajax({
                    url: '/quanlybanhang/ajax/customers_ajax.php', type: 'POST', dataType: 'json', data: { action: 'collect_debt', order_id: orderId, amount: amount, receipt_date: new Date().toISOString().slice(0, 19).replace('T', ' ') },
                    success: function(response) { alert(response.message); if (response.status === 'success') { location.reload(); } else { $button.prop('disabled', false).text('Thu'); } },
                    error: function() { alert('Lỗi khi gửi yêu cầu thu nợ.'); $button.prop('disabled', false).text('Thu'); }
                });
            }
        });
        $('#btnEditCustomer').on('click', function() {
            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 customer = response.data;
                        $('#customer_id').val(customer.ID); $('#customerModalLabel').text('Chỉnh sửa khách hàng');
                        $('select[name="customer_group"]').val(customer.customer_group);
                        $('input[name="customer_code"]').val(customer.customer_code);
                        $('input[name="customer_name"]').val(customer.customer_name);
                        $('input[name="customer_phone"]').val(customer.customer_phone);
                        $('input[name="customer_email"]').val(customer.customer_email);
                        $('input[name="customer_tax"]').val(customer.customer_tax);
                        $('input[name="customer_addr"]').val(customer.customer_addr);
                        $('input[name="customer_birthday"]').val(customer.customer_birthday);
                        $('input[name="notes"]').val(customer.notes);
                        $('#existing_image_url').val(customer.customer_image);
                        if(customer.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();
            var formData = new FormData(this);
            formData.append('action', 'save_customer');
            var $submitButton = $(this).find('button[type="submit"]');
            $submitButton.prop('disabled', true);
            $.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') { location.reload(); }
                },
                error: () => alert('Đã xảy ra lỗi khi gửi yêu cầu.'),
                complete: () => $submitButton.prop('disabled', false)
            });
        });
    });
    </script>
</body>
</html>