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

// 1. Lấy ID khách hàng từ URL
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']);

// 2. Lấy thông tin chi tiết của khách hàng
$stmt = $conn->prepare("SELECT c.*, cg.group_name FROM cms_customers c LEFT JOIN cms_customer_groups cg ON c.customer_group = cg.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.');
}

// 3. Lấy lịch sử mua hàng của khách hàng này
$order_history_result = $conn->query("SELECT * FROM cms_orders WHERE customer_id = {$customer_id} AND deleted = 0 ORDER BY sell_date DESC");
$order_history = $order_history_result ? $order_history_result->fetch_all(MYSQLI_ASSOC) : [];

// 4. Lấy danh sách nhóm khách hàng để hiển thị trong modal
$groups_result = $conn->query("SELECT ID, group_name FROM cms_customer_groups");
$customer_groups = $groups_result ? $groups_result->fetch_all(MYSQLI_ASSOC) : [];

// 5. Tính toán các chỉ số tổng hợp
$total_orders = count($order_history);
$total_revenue = array_sum(array_column($order_history, 'total_money'));
$total_debt = array_sum(array_column($order_history, 'lack'));

?>
<!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">
    <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>
        body { background-color: #f8f9fa; }
        #wrapper { display: flex; }
        #page-content-wrapper { width: 100%; }
        .card { border: none; border-radius: 0.75rem; box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.1); }
        .card-header { background-color: #fff; border-bottom: 1px solid #dee2e6; padding: 1.25rem 1.5rem; font-weight: 600; }
        .table td, .table th { vertical-align: middle; }
        .debt-amount { color: #dc3545; font-weight: 600; }
        .info-section dt { font-weight: 500; color: #6c757d; }
        .info-section dd { font-weight: 600; color: #212529; }
        .table tfoot { font-weight: bold; background-color: #f8f9fa; }
    </style>
</head>

<body>
    <div class="d-flex" id="wrapper">
        <?php require_once __DIR__ . '/../../templates/sidebar.php'; ?>
        <div id="page-content-wrapper">
            <div class="container-fluid p-4">
                
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2 class="mb-0 h3">Chi tiết khách hàng: <?php echo htmlspecialchars($customer['customer_name']); ?></h2>
                    <div>
                        <button type="button" class="btn btn-warning" id="btnEditCustomer"><i class="fas fa-edit me-1"></i> Sửa thông tin</button>
                        <a href="list.php" class="btn btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> Quay lại danh sách</a>
                    </div>
                </div>

                <div class="card mb-4">
                    <div class="card-header">Thông tin cá nhân</div>
                    <div class="card-body p-4">
                        <div class="row">
                            <div class="col-md-6 info-section">
                                <dl class="row 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">Nhóm</dt>
                                    <dd class="col-sm-8"><?php echo htmlspecialchars($customer['group_name'] ?: 'Chưa có'); ?></dd>
                                    <dt class="col-sm-4">Địa chỉ</dt>
                                    <dd class="col-sm-8"><?php echo htmlspecialchars($customer['customer_addr'] ?: '(chưa có)'); ?></dd>
                                </dl>
                            </div>
                            <div class="col-md-6 info-section">
                                <dl class="row mb-0">
                                    <dt class="col-sm-4">Số điện thoại</dt>
                                    <dd class="col-sm-8"><?php echo htmlspecialchars($customer['customer_phone'] ?: '(chưa có)'); ?></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">Mã số thuế</dt>
                                    <dd class="col-sm-8"><?php echo htmlspecialchars($customer['tax_code'] ?: '(chưa có)'); ?></dd>
                                </dl>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header">Lịch sử mua hàng</div>
                    <div class="table-responsive">
                        <table class="table table-hover mb-0">
                            <thead class="table-light">
                                <tr>
                                    <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">Đã trả</th>
                                    <th class="text-end">Nợ</th>
                                    <th>Hành động</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (!empty($order_history)): foreach ($order_history as $order): ?>
                                <tr>
                                    <td><a href="/quanlybanhang/modules/orders/edit.php?id=<?php echo $order['ID']; ?>"><?php echo htmlspecialchars($order['order_code']); ?></a></td>
                                    <td><?php echo date('d/m/Y H:i', strtotime($order['sell_date'])); ?></td>
                                    <td><?php echo htmlspecialchars($order['user_init']); ?></td>
                                    <td><?php echo ($order['lack'] > 0) ? '<span class="badge bg-warning text-dark">Còn nợ</span>' : '<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 debt-amount"><?php echo number_format($order['lack']); ?></td>
                                    <td class="text-center"><a href="#" class="btn btn-sm btn-outline-primary" title="In phiếu"><i class="fas fa-print"></i></a></td>
                                </tr>
                                <?php endforeach; else: ?>
                                <tr><td colspan="8" class="text-center p-4">Chưa có lịch sử mua hàng.</td></tr>
                                <?php endif; ?>
                            </tbody>
                            <tfoot>
                                <tr>
                                    <td colspan="4" class="fw-bold">Tổng cộng</td>
                                    <td class="text-end fw-bold"><?php echo number_format($total_revenue); ?> đ</td>
                                    <td class="text-end fw-bold"><?php echo number_format($total_revenue - $total_debt); ?> đ</td>
                                    <td class="text-end debt-amount fw-bold"><?php echo number_format($total_debt); ?> đ</td>
                                    <td></td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </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">Chỉnh sửa 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="tax_code" id="tax_code" 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() {
        $('#customer_group').select2({
            theme: "bootstrap-5",
            dropdownParent: $('#customerModal'),
            minimumResultsForSearch: Infinity
        });

        // Mở modal và tải dữ liệu khi nhấn nút "Sửa thông tin"
        $('#btnEditCustomer').on('click', function() {
            var customerId = <?php echo $customer_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="tax_code"]').val(c.tax_code);
                    
                    var customerModal = new bootstrap.Modal(document.getElementById('customerModal'));
                    customerModal.show();
                } else { 
                    alert(response.message); 
                }
            }, 'json').fail(function() {
                alert('Không thể tải dữ liệu khách hàng. Vui lòng kiểm tra lại đường dẫn AJAX.');
            });
        });

        // Xử lý lưu thông tin khách hàng từ modal
        $('#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') {
                    location.reload(); // Tải lại trang chi tiết để cập nhật thông tin
                }
            }, 'json').fail(function() {
                alert('Đã xảy ra lỗi khi gửi dữ liệu. Vui lòng kiểm tra lại.');
            });
        });
    });
    </script>
</body>
</html>