<?php
// Session & Config
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
date_default_timezone_set('Asia/Vientiane');

require_once '../../include/con_data.php';

// Check Auth
if (!isset($_SESSION['user_id'])) {
    header('Location: ../../login.php');
    exit;
}

$shop_id = $_SESSION['shop_id'] ?? null;

// ==========================================
// AJAX HANDLERS
// ==========================================
if (isset($_GET['ajax'])) {
    header('Content-Type: application/json');
    $action = $_GET['ajax'];

    if (!$shop_id) {
        echo json_encode(['status' => 'error', 'message' => 'Shop ID not found']);
        exit;
    }

    try {
        // --- 1. Get All Customers with Stats ---
        if ($action === 'customers') {
            $search = trim($_GET['search'] ?? '');
            $sort = $_GET['sort'] ?? 'total_spend';
            $order = strtoupper($_GET['order'] ?? 'DESC') === 'ASC' ? 'ASC' : 'DESC';

            $sql = "SELECT c.id, c.CU_id, c.name, c.phone, c.created_at,
                           COUNT(DISTINCT o.id) as order_count,
                           COALESCE(SUM(o.total_amount_lak), 0) as total_spend,
                           MAX(o.created_at) as last_order_date
                    FROM customers c
                    LEFT JOIN orders o ON o.customer_id = c.CU_id 
                        AND o.shop_id = c.shop_id 
                        AND o.order_status != 'cancelled'
                    WHERE c.shop_id = ? AND c.is_active = 1";

            $params = [$shop_id];
            $types = "i";

            if ($search) {
                $sql .= " AND (c.name LIKE ? OR c.phone LIKE ?)";
                $s = "%$search%";
                array_push($params, $s, $s);
                $types .= "ss";
            }

            $sql .= " GROUP BY c.id, c.CU_id, c.name, c.phone, c.created_at";

            $orderCol = match ($sort) {
                'name' => 'c.name',
                'order_count' => 'order_count',
                'last_order' => 'last_order_date',
                default => 'total_spend'
            };
            $sql .= " ORDER BY $orderCol $order";

            $stmt = $conn->prepare($sql);
            $stmt->bind_param($types, ...$params);
            $stmt->execute();
            $result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

            // Summary stats
            $totalCustomers = count($result);
            $totalSpend = array_sum(array_column($result, 'total_spend'));
            $totalOrders = array_sum(array_column($result, 'order_count'));

            echo json_encode([
                'status' => 'success',
                'data' => $result,
                'summary' => [
                    'total_customers' => $totalCustomers,
                    'total_spend' => $totalSpend,
                    'total_orders' => $totalOrders
                ]
            ]);
            exit;
        }

        // --- 2. Customer Detail + Order History ---
        if ($action === 'customer_detail') {
            $cu_id = $_GET['cu_id'] ?? '';

            // Customer info
            $stmt = $conn->prepare("SELECT * FROM customers WHERE CU_id = ? AND shop_id = ?");
            $stmt->bind_param("si", $cu_id, $shop_id);
            $stmt->execute();
            $customer = $stmt->get_result()->fetch_assoc();

            if (!$customer) {
                echo json_encode(['status' => 'error', 'message' => 'Customer not found']);
                exit;
            }

            // Order history
            $stmt = $conn->prepare("SELECT o.*, cur.currencys_symbol
                    FROM orders o
                    LEFT JOIN currencys cur ON o.currencys_id = cur.currencys_id AND cur.shop_id = o.shop_id
                    WHERE o.customer_id = ? AND o.shop_id = ? AND o.order_status != 'cancelled'
                    ORDER BY o.created_at DESC");
            $stmt->bind_param("si", $cu_id, $shop_id);
            $stmt->execute();
            $orders = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

            // Get items for each order
            foreach ($orders as &$order) {
                $stmt = $conn->prepare("SELECT product_name, quantity, unit_price, total FROM order_items WHERE order_id = ?");
                $stmt->bind_param("i", $order['id']);
                $stmt->execute();
                $order['items'] = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
            }

            // Favorite products
            $stmt = $conn->prepare("SELECT oi.product_name, 
                           SUM(oi.quantity) as total_qty, 
                           COUNT(*) as times_ordered,
                           SUM(oi.total) as total_value
                    FROM order_items oi
                    JOIN orders o ON oi.order_id = o.id
                    WHERE o.customer_id = ? AND o.shop_id = ? AND o.order_status != 'cancelled'
                    GROUP BY oi.product_name
                    ORDER BY total_qty DESC
                    LIMIT 10");
            $stmt->bind_param("si", $cu_id, $shop_id);
            $stmt->execute();
            $favorites = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

            // Monthly stats
            $stmt = $conn->prepare("SELECT 
                           DATE_FORMAT(o.created_at, '%Y-%m') as month,
                           COUNT(*) as order_count,
                           SUM(o.total_amount_lak) as total_spend
                    FROM orders o
                    WHERE o.customer_id = ? AND o.shop_id = ? AND o.order_status != 'cancelled'
                    GROUP BY DATE_FORMAT(o.created_at, '%Y-%m')
                    ORDER BY month DESC
                    LIMIT 12");
            $stmt->bind_param("si", $cu_id, $shop_id);
            $stmt->execute();
            $monthly = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

            echo json_encode([
                'status' => 'success',
                'customer' => $customer,
                'orders' => $orders,
                'favorites' => $favorites,
                'monthly_stats' => $monthly
            ]);
            exit;
        }

        // --- 3. Customer Ranking ---
        if ($action === 'customer_ranking') {
            $rank_by = $_GET['rank_by'] ?? 'total_spend';
            $limit = min(50, max(5, intval($_GET['limit'] ?? 10)));

            $orderCol = $rank_by === 'order_count' ? 'order_count' : 'total_spend';

            $stmt = $conn->prepare("SELECT c.CU_id, c.name, c.phone,
                           COUNT(DISTINCT o.id) as order_count,
                           COALESCE(SUM(o.total_amount_lak), 0) as total_spend,
                           MAX(o.created_at) as last_order
                    FROM customers c
                    JOIN orders o ON o.customer_id = c.CU_id AND o.shop_id = c.shop_id AND o.order_status != 'cancelled'
                    WHERE c.shop_id = ? AND c.is_active = 1
                    GROUP BY c.CU_id, c.name, c.phone
                    ORDER BY $orderCol DESC
                    LIMIT ?");
            $stmt->bind_param("ii", $shop_id, $limit);
            $stmt->execute();
            $ranking = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

            echo json_encode(['status' => 'success', 'data' => $ranking]);
            exit;
        }

        // --- 4. Customer Behavior Analysis ---
        if ($action === 'customer_behavior') {
            $cu_id = $_GET['cu_id'] ?? '';

            // Monthly purchase pattern
            $stmt = $conn->prepare("SELECT 
                           MONTH(o.created_at) as month_num,
                           MONTHNAME(o.created_at) as month_name,
                           COUNT(*) as order_count,
                           SUM(o.total_amount_lak) as total_spend
                    FROM orders o
                    WHERE o.customer_id = ? AND o.shop_id = ? AND o.order_status != 'cancelled'
                    GROUP BY MONTH(o.created_at), MONTHNAME(o.created_at)
                    ORDER BY month_num");
            $stmt->bind_param("si", $cu_id, $shop_id);
            $stmt->execute();
            $monthly_pattern = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

            // Detect seasonal patterns
            $seasons = [];
            foreach ($monthly_pattern as $m) {
                $mn = intval($m['month_num']);
                if ($mn == 1)
                    $seasons[] = ['event' => 'ປີໃໝ່ສາກົນ (New Year)', 'month' => $mn, 'orders' => $m['order_count'], 'spend' => $m['total_spend']];
                if ($mn == 2)
                    $seasons[] = ['event' => 'ວັນວາເລນທາຍ (Valentine)', 'month' => $mn, 'orders' => $m['order_count'], 'spend' => $m['total_spend']];
                if ($mn == 3)
                    $seasons[] = ['event' => 'ວັນແມ່ຍິງສາກົນ (Women\'s Day)', 'month' => $mn, 'orders' => $m['order_count'], 'spend' => $m['total_spend']];
                if ($mn == 4)
                    $seasons[] = ['event' => 'ປີໃໝ່ລາວ (Lao New Year)', 'month' => $mn, 'orders' => $m['order_count'], 'spend' => $m['total_spend']];
                if ($mn == 8)
                    $seasons[] = ['event' => 'ວັນແມ່ (Mother\'s Day)', 'month' => $mn, 'orders' => $m['order_count'], 'spend' => $m['total_spend']];
                if ($mn == 10)
                    $seasons[] = ['event' => 'ບຸນອອກພັນສາ', 'month' => $mn, 'orders' => $m['order_count'], 'spend' => $m['total_spend']];
                if ($mn == 11)
                    $seasons[] = ['event' => 'ວັນຄ້າຍວັນເກີດ / 11.11', 'month' => $mn, 'orders' => $m['order_count'], 'spend' => $m['total_spend']];
                if ($mn == 12)
                    $seasons[] = ['event' => 'ຄຣິດສະມາດ / ປີໃໝ່ (Christmas)', 'month' => $mn, 'orders' => $m['order_count'], 'spend' => $m['total_spend']];
            }

            echo json_encode([
                'status' => 'success',
                'monthly_pattern' => $monthly_pattern,
                'seasonal_events' => $seasons
            ]);
            exit;
        }

    } catch (Exception $e) {
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
        exit;
    }
}

$page_title = 'ຂໍ້ມູນລູກຄ້າ - Customer Analytics';
require_once '../includes/header.php';
?>

<style>
    /* Page Layout */
    .page-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 24px;
        flex-wrap: wrap;
        gap: 16px;
    }

    .page-header h1 {
        font-size: 24px;
        font-weight: 600;
        display: flex;
        align-items: center;
        gap: 12px;
        margin: 0;
    }

    /* Stats Cards */
    .cust-stats {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
        gap: 16px;
        margin-bottom: 24px;
    }

    .cust-stat-card {
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 16px;
        padding: 20px;
        display: flex;
        align-items: center;
        gap: 15px;
        transition: transform .2s;
    }

    .cust-stat-card:hover {
        transform: translateY(-3px);
    }

    .cust-stat-icon {
        width: 55px;
        height: 55px;
        border-radius: 14px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 22px;
        color: #fff;
        flex-shrink: 0;
    }

    .cust-stat-icon.gold {
        background: linear-gradient(135deg, #c1992a, #d4ac4a);
    }

    .cust-stat-icon.blue {
        background: linear-gradient(135deg, #4a90e2, #357abd);
    }

    .cust-stat-icon.green {
        background: linear-gradient(135deg, #28a745, #20c997);
    }

    .cust-stat-icon.purple {
        background: linear-gradient(135deg, #6f42c1, #9b59b6);
    }

    .cust-stat-info h3 {
        font-size: 26px;
        font-weight: 700;
        margin: 0;
    }

    .cust-stat-info p {
        font-size: 14px;
        color: var(--text-secondary);
        margin: 4px 0 0;
    }

    /* Tab Navigation */
    .tab-nav {
        display: flex;
        gap: 4px;
        margin-bottom: 20px;
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 14px;
        padding: 6px;
        overflow-x: auto;
    }

    .tab-btn {
        padding: 12px 24px;
        border: none;
        background: transparent;
        color: var(--text-secondary);
        font-size: 15px;
        font-weight: 500;
        border-radius: 10px;
        cursor: pointer;
        transition: all .2s;
        white-space: nowrap;
        font-family: inherit;
    }

    .tab-btn.active {
        background: var(--accent);
        color: #fff;
        font-weight: 600;
    }

    .tab-btn:hover:not(.active) {
        background: rgba(193, 153, 42, .1);
        color: var(--accent);
    }

    .tab-content {
        display: none;
        opacity: 0;
        transition: opacity .25s ease;
    }

    .tab-content.active {
        display: block;
        opacity: 1;
    }

    .fade-out {
        opacity: 0 !important;
        transition: opacity .15s ease;
    }

    .fade-in {
        opacity: 1 !important;
        transition: opacity .2s ease;
    }

    /* Filter Card */
    .filter-card {
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 16px;
        padding: 20px;
        margin-bottom: 20px;
    }

    .filter-row {
        display: flex;
        gap: 12px;
        flex-wrap: wrap;
        align-items: center;
    }

    .search-box-cu {
        display: flex;
        align-items: center;
        gap: 8px;
        background: var(--bg-secondary);
        border: 1px solid var(--border-color);
        border-radius: 10px;
        padding: 12px 16px;
        flex: 1;
        min-width: 250px;
    }

    .search-box-cu input {
        border: none;
        background: transparent;
        outline: none;
        color: var(--text-primary);
        width: 100%;
        font-size: 16px;
        font-family: inherit;
    }

    .sort-select {
        padding: 12px 16px;
        border: 1px solid var(--border-color);
        border-radius: 10px;
        background: var(--bg-secondary);
        color: var(--text-primary);
        font-size: 15px;
        font-family: inherit;
        cursor: pointer;
    }

    .sort-select:focus {
        border-color: var(--accent);
        outline: none;
    }

    /* Data Table */
    .data-card {
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 16px;
        overflow: hidden;
    }

    .table-wrap {
        overflow-x: auto;
    }

    .cu-table {
        width: 100%;
        border-collapse: collapse;
    }

    .cu-table th {
        padding: 14px 16px;
        text-align: left;
        font-size: 14px;
        font-weight: 600;
        color: var(--text-secondary);
        border-bottom: 1px solid var(--border-color);
        background: var(--bg-secondary);
        white-space: nowrap;
    }

    .cu-table td {
        padding: 14px 16px;
        border-bottom: 1px solid var(--border-color);
        font-size: 15px;
    }

    .cu-table tr {
        cursor: pointer;
        transition: background .15s;
    }

    .cu-table tbody tr:hover {
        background: rgba(193, 153, 42, .06);
    }

    .cu-table .rank-badge {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        font-weight: 700;
        font-size: 14px;
    }

    .rank-1 {
        background: linear-gradient(135deg, #FFD700, #FFA500);
        color: #000;
    }

    .rank-2 {
        background: linear-gradient(135deg, #C0C0C0, #A0A0A0);
        color: #000;
    }

    .rank-3 {
        background: linear-gradient(135deg, #CD7F32, #A0522D);
        color: #fff;
    }

    .rank-other {
        background: var(--bg-secondary);
        color: var(--text-secondary);
    }

    .amount-gold {
        color: var(--accent);
        font-weight: 700;
    }

    .empty-state {
        text-align: center;
        padding: 40px;
        color: var(--text-secondary);
    }

    .empty-state i {
        font-size: 48px;
        opacity: .3;
        display: block;
        margin-bottom: 15px;
    }

    /* Modal */
    .cu-modal {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0);
        backdrop-filter: blur(0);
        z-index: 2000;
        display: flex;
        align-items: center;
        justify-content: center;
        opacity: 0;
        visibility: hidden;
        transition: all .3s;
    }

    .cu-modal.show {
        opacity: 1;
        visibility: visible;
        background: rgba(0, 0, 0, .6);
        backdrop-filter: blur(8px);
    }

    .cu-modal-content {
        background: var(--bg-primary);
        border-radius: 20px;
        width: 95%;
        max-width: 900px;
        max-height: 90vh;
        overflow-y: auto;
        border: 1px solid var(--border-color);
        box-shadow: 0 25px 50px rgba(0, 0, 0, .3);
        transform: scale(.9) translateY(-20px);
        opacity: 0;
        transition: all .35s cubic-bezier(.34, 1.56, .64, 1);
    }

    .cu-modal.show .cu-modal-content {
        transform: scale(1) translateY(0);
        opacity: 1;
    }

    .cu-modal-header {
        padding: 20px 24px;
        border-bottom: 1px solid var(--border-color);
        display: flex;
        justify-content: space-between;
        align-items: center;
        position: sticky;
        top: 0;
        background: var(--bg-primary);
        z-index: 10;
        border-radius: 20px 20px 0 0;
    }

    .cu-modal-header h2 {
        font-size: 20px;
        display: flex;
        align-items: center;
        gap: 10px;
        margin: 0;
    }

    .cu-modal-close {
        background: none;
        border: none;
        font-size: 24px;
        color: var(--text-secondary);
        cursor: pointer;
        padding: 5px;
    }

    .cu-modal-close:hover {
        color: var(--accent);
    }

    .cu-modal-body {
        padding: 24px;
    }

    /* Detail Sections */
    .detail-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 16px;
        margin-bottom: 20px;
    }

    .detail-box {
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 14px;
        padding: 16px;
    }

    .detail-box h4 {
        font-size: 15px;
        color: var(--text-secondary);
        margin: 0 0 12px;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .detail-box .val {
        font-size: 22px;
        font-weight: 700;
        color: var(--accent);
    }

    .detail-box .sub {
        font-size: 13px;
        color: var(--text-secondary);
        margin-top: 4px;
    }

    /* Inner Tabs */
    .inner-tabs {
        display: flex;
        gap: 4px;
        margin-bottom: 16px;
        border-bottom: 2px solid var(--border-color);
        padding-bottom: 0;
    }

    .inner-tab {
        padding: 10px 20px;
        border: none;
        background: transparent;
        color: var(--text-secondary);
        font-size: 14px;
        font-weight: 500;
        cursor: pointer;
        border-bottom: 2px solid transparent;
        margin-bottom: -2px;
        transition: all .2s;
        font-family: inherit;
    }

    .inner-tab.active {
        color: var(--accent);
        border-bottom-color: var(--accent);
        font-weight: 600;
    }

    .inner-panel {
        display: none;
    }

    .inner-panel.active {
        display: block;
    }

    /* Favorite Products */
    .fav-list {
        list-style: none;
        padding: 0;
    }

    .fav-item {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 10px 0;
        border-bottom: 1px solid var(--border-color);
    }

    .fav-item:last-child {
        border-bottom: none;
    }

    .fav-rank {
        width: 28px;
        height: 28px;
        border-radius: 50%;
        background: var(--accent);
        color: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 13px;
        font-weight: 700;
        flex-shrink: 0;
    }

    .fav-info {
        flex: 1;
    }

    .fav-name {
        font-weight: 600;
        font-size: 14px;
    }

    .fav-meta {
        font-size: 13px;
        color: var(--text-secondary);
    }

    .fav-bar-wrap {
        width: 100px;
        height: 8px;
        background: var(--border-color);
        border-radius: 4px;
        overflow: hidden;
    }

    .fav-bar {
        height: 100%;
        background: var(--accent);
        border-radius: 4px;
        transition: width .5s;
    }

    /* Monthly Chart (CSS bars) */
    .month-chart {
        display: flex;
        align-items: flex-end;
        gap: 8px;
        height: 160px;
        padding: 10px 0;
    }

    .month-bar-wrap {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 4px;
    }

    .month-bar {
        width: 100%;
        min-width: 24px;
        border-radius: 6px 6px 0 0;
        background: linear-gradient(180deg, var(--accent), #8b6914);
        transition: height .5s;
    }

    .month-label {
        font-size: 11px;
        color: var(--text-secondary);
    }

    .month-val {
        font-size: 11px;
        font-weight: 600;
        color: var(--text-primary);
    }

    /* Season Tags */
    .season-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
    }

    .season-tag {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 8px 14px;
        background: rgba(193, 153, 42, .1);
        border: 1px solid rgba(193, 153, 42, .2);
        border-radius: 20px;
        font-size: 13px;
        color: var(--accent);
        font-weight: 500;
    }

    .season-tag i {
        font-size: 14px;
    }

    /* Order history mini table */
    .order-hist-table {
        width: 100%;
        border-collapse: collapse;
        font-size: 14px;
    }

    .order-hist-table th {
        padding: 10px 12px;
        text-align: left;
        font-size: 13px;
        color: var(--text-secondary);
        border-bottom: 1px solid var(--border-color);
        background: var(--bg-secondary);
    }

    .order-hist-table td {
        padding: 10px 12px;
        border-bottom: 1px solid var(--border-color);
    }

    /* Ranking radio */
    .rank-options {
        display: flex;
        gap: 8px;
    }

    .rank-opt {
        padding: 8px 16px;
        border: 1px solid var(--border-color);
        border-radius: 8px;
        background: var(--bg-secondary);
        color: var(--text-primary);
        font-size: 14px;
        cursor: pointer;
        transition: all .2s;
        font-family: inherit;
    }

    .rank-opt.active {
        background: var(--accent);
        color: #fff;
        border-color: var(--accent);
    }

    .rank-limit {
        padding: 8px 12px;
        border: 1px solid var(--border-color);
        border-radius: 8px;
        background: var(--bg-secondary);
        color: var(--text-primary);
        font-size: 14px;
        width: 70px;
        font-family: inherit;
    }

    /* Loading spinner */
    .cu-loading {
        text-align: center;
        padding: 40px;
        color: var(--text-secondary);
    }

    .cu-loading i {
        font-size: 32px;
        animation: spin 1s linear infinite;
    }

    @keyframes spin {
        to {
            transform: rotate(360deg);
        }
    }

    @media(max-width:768px) {
        .detail-grid {
            grid-template-columns: 1fr;
        }

        .cust-stats {
            grid-template-columns: 1fr 1fr;
        }

        .tab-nav {
            overflow-x: auto;
        }
    }

    /* Pagination */
    .cu-pagination-wrap {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 15px 20px;
        border-top: 1px solid var(--border-color);
        flex-wrap: wrap;
        gap: 10px;
    }

    .cu-pagination-info {
        font-size: 14px;
        color: var(--text-secondary);
    }

    .cu-pagination-btns {
        display: flex;
        gap: 4px;
    }

    .cu-pagination-btns button {
        min-width: 36px;
        height: 36px;
        border: 1px solid var(--border-color);
        background: var(--card-bg);
        color: var(--text-primary);
        border-radius: 8px;
        cursor: pointer;
        font-size: 13px;
        transition: all .2s;
        font-family: inherit;
    }

    .cu-pagination-btns button:hover {
        border-color: var(--accent);
        color: var(--accent);
    }

    .cu-pagination-btns button.active {
        background: var(--accent);
        color: #fff;
        border-color: var(--accent);
    }

    .cu-pagination-btns button:disabled {
        opacity: .4;
        cursor: not-allowed;
    }
</style>

<div class="content">
    <div class="page-header">
        <h1><i class="fas fa-users"></i> ຂໍ້ມູນລູກຄ້າ</h1>
    </div>

    <!-- Summary Stats -->
    <div class="cust-stats" id="summaryStats">
        <div class="cust-stat-card">
            <div class="cust-stat-icon gold"><i class="fas fa-users"></i></div>
            <div class="cust-stat-info">
                <h3 id="statCustomers">0</h3>
                <p>ລູກຄ້າທັງໝົດ</p>
            </div>
        </div>
        <div class="cust-stat-card">
            <div class="cust-stat-icon blue"><i class="fas fa-shopping-bag"></i></div>
            <div class="cust-stat-info">
                <h3 id="statOrders">0</h3>
                <p>ຍອດສັ່ງຊື້ທັງໝົດ</p>
            </div>
        </div>
        <div class="cust-stat-card">
            <div class="cust-stat-icon green"><i class="fas fa-coins"></i></div>
            <div class="cust-stat-info">
                <h3 id="statSpend">0 ₭</h3>
                <p>ຍອດຂາຍລວມ</p>
            </div>
        </div>
        <div class="cust-stat-card">
            <div class="cust-stat-icon purple"><i class="fas fa-chart-line"></i></div>
            <div class="cust-stat-info">
                <h3 id="statAvg">0 ₭</h3>
                <p>ສະເລ່ຍ/ລູກຄ້າ</p>
            </div>
        </div>
    </div>

    <!-- Tab Navigation -->
    <div class="tab-nav">
        <button class="tab-btn active" onclick="switchTab('list')"><i class="fas fa-list"></i> ລາຍຊື່ລູກຄ້າ</button>
        <button class="tab-btn" onclick="switchTab('ranking')"><i class="fas fa-trophy"></i> ອັນດັບລູກຄ້າ</button>
    </div>

    <!-- Tab: Customer List -->
    <div class="tab-content active" id="tab-list">
        <div class="filter-card">
            <div class="filter-row">
                <div class="search-box-cu">
                    <i class="fas fa-search" style="color:var(--text-secondary)"></i>
                    <input type="text" id="searchInput" placeholder="ຄົ້ນຫາ ຊື່ ຫຼື ເບີໂທ..."
                        oninput="debounceSearch()">
                </div>
                <select class="sort-select" id="sortSelect" onchange="onSortChange()">
                    <option value="total_spend">ຍອດສູງສຸດ</option>
                    <option value="order_count">ສັ່ງເລື້ອຍສຸດ</option>
                    <option value="name">ຕາມຊື່</option>
                    <option value="last_order">ສັ່ງຫຼ້າສຸດ</option>
                </select>
            </div>
        </div>
        <div class="data-card">
            <div class="table-wrap">
                <table class="cu-table">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>ຊື່ລູກຄ້າ</th>
                            <th>ເບີໂທ</th>
                            <th>ຈຳນວນຄັ້ງ</th>
                            <th>ຍອດລວມ (₭)</th>
                            <th>ສັ່ງຫຼ້າສຸດ</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody id="customerTableBody">
                        <tr>
                            <td colspan="7" class="cu-loading"><i class="fas fa-spinner"></i><br>ກຳລັງໂຫຼດ...</td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <div class="cu-pagination-wrap" id="cuPaginationWrap" style="display:none">
                <div class="cu-pagination-info" id="cuPaginationInfo"></div>
                <div class="cu-pagination-btns" id="cuPaginationBtns"></div>
            </div>
        </div>
    </div>

    <!-- Tab: Ranking -->
    <div class="tab-content" id="tab-ranking">
        <div class="filter-card">
            <div class="filter-row">
                <span style="font-weight:600;margin-right:8px;">ຈັດອັນດັບຕາມ:</span>
                <div class="rank-options">
                    <button class="rank-opt active" onclick="setRankBy('total_spend',this)">ຍອດເງິນ</button>
                    <button class="rank-opt" onclick="setRankBy('order_count',this)">ຈຳນວນຄັ້ງ</button>
                </div>
                <span style="margin-left:16px;font-weight:500;">Top</span>
                <input type="number" class="rank-limit" id="rankLimit" value="10" min="5" max="50"
                    onchange="loadRanking()">
            </div>
        </div>
        <div class="data-card">
            <div class="table-wrap">
                <table class="cu-table">
                    <thead>
                        <tr>
                            <th style="width:60px">ອັນດັບ</th>
                            <th>ຊື່ລູກຄ້າ</th>
                            <th>ເບີໂທ</th>
                            <th>ຈຳນວນຄັ້ງ</th>
                            <th>ຍອດລວມ (₭)</th>
                            <th>ສັ່ງຫຼ້າສຸດ</th>
                        </tr>
                    </thead>
                    <tbody id="rankingTableBody">
                        <tr>
                            <td colspan="6" class="cu-loading"><i class="fas fa-spinner"></i><br>ກຳລັງໂຫຼດ...</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Customer Detail Modal -->
<div class="cu-modal" id="customerModal">
    <div class="cu-modal-content">
        <div class="cu-modal-header">
            <h2><i class="fas fa-user-circle" style="color:var(--accent)"></i> <span id="modalCuName">ລູກຄ້າ</span></h2>
            <button class="cu-modal-close" onclick="closeModal()">&times;</button>
        </div>
        <div class="cu-modal-body" id="modalBody">
            <div class="cu-loading"><i class="fas fa-spinner"></i><br>ກຳລັງໂຫຼດ...</div>
        </div>
    </div>
</div>

<script>
    let searchTimer = null;
    let currentRankBy = 'total_spend';
    let cachedCustomers = null;
    let rankingLoaded = false;
    let cachedRanking = null;
    let currentPage = 1;
    const PAGE_SIZE = 50;

    // ===== Tab Switch =====
    function switchTab(tab) {
        document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
        event.target.closest('.tab-btn').classList.add('active');

        const currentActive = document.querySelector('.tab-content.active');
        const next = document.getElementById('tab-' + tab);

        if (currentActive === next) return;

        if (currentActive) {
            currentActive.style.opacity = '0';
            setTimeout(() => {
                currentActive.classList.remove('active');
                currentActive.style.opacity = '';
                next.classList.add('active');
                next.style.opacity = '0';
                requestAnimationFrame(() => {
                    next.style.opacity = '1';
                });
                if (tab === 'ranking' && !rankingLoaded) loadRanking();
            }, 150);
        } else {
            next.classList.add('active');
            if (tab === 'ranking' && !rankingLoaded) loadRanking();
        }
    }

    // ===== Sort cached data on the client side =====
    function sortCustomers(data, sort) {
        const sorted = [...data];
        sorted.sort((a, b) => {
            switch (sort) {
                case 'name':
                    return (a.name || '').localeCompare(b.name || '');
                case 'order_count':
                    return Number(b.order_count) - Number(a.order_count);
                case 'last_order':
                    return (b.last_order_date || '').localeCompare(a.last_order_date || '');
                default: // total_spend
                    return Number(b.total_spend) - Number(a.total_spend);
            }
        });
        return sorted;
    }

    // ===== Render customer table from data (with pagination) =====
    function renderCustomerTable(data) {
        const tbody = document.getElementById('customerTableBody');
        if (!data.length) {
            tbody.innerHTML = '<tr><td colspan="7" class="empty-state"><i class="fas fa-users"></i>ບໍ່ພົບລູກຄ້າ</td></tr>';
            document.getElementById('cuPaginationWrap').style.display = 'none';
            return;
        }

        const totalPages = Math.ceil(data.length / PAGE_SIZE);
        if (currentPage > totalPages) currentPage = totalPages;
        const start = (currentPage - 1) * PAGE_SIZE;
        const end = Math.min(start + PAGE_SIZE, data.length);
        const pageData = data.slice(start, end);

        tbody.innerHTML = pageData.map((c, i) => `<tr onclick="openCustomerDetail('${c.CU_id}')">
            <td>${start + i + 1}</td>
            <td><strong>${esc(c.name)}</strong></td>
            <td>${esc(c.phone || '-')}</td>
            <td>${Number(c.order_count).toLocaleString()}</td>
            <td class="amount-gold">${Number(c.total_spend).toLocaleString()}</td>
            <td>${c.last_order_date ? formatDate(c.last_order_date) : '-'}</td>
            <td><button class="btn-secondary" style="padding:6px 12px;font-size:13px;border-radius:8px;border:1px solid var(--border-color);background:var(--bg-secondary);color:var(--accent);cursor:pointer" onclick="event.stopPropagation();openCustomerDetail('${c.CU_id}')"><i class="fas fa-eye"></i></button></td>
        </tr>`).join('');

        // Render pagination
        renderCustomerPagination(data.length, totalPages);
    }

    // ===== Render pagination controls =====
    function renderCustomerPagination(total, totalPages) {
        const wrap = document.getElementById('cuPaginationWrap');
        const info = document.getElementById('cuPaginationInfo');
        const btns = document.getElementById('cuPaginationBtns');

        if (totalPages <= 1) {
            wrap.style.display = 'none';
            return;
        }

        wrap.style.display = 'flex';
        const from = (currentPage - 1) * PAGE_SIZE + 1;
        const to = Math.min(currentPage * PAGE_SIZE, total);
        info.textContent = `ສະແດງ ${from}-${to} ຈາກ ${total.toLocaleString()} ລາຍການ`;

        let html = '';
        html += `<button ${currentPage === 1 ? 'disabled' : ''} onclick="goToCustomerPage(${currentPage - 1})">&laquo;</button>`;

        let startP = Math.max(1, currentPage - 2);
        let endP = Math.min(totalPages, startP + 4);
        if (endP - startP < 4) startP = Math.max(1, endP - 4);

        for (let p = startP; p <= endP; p++) {
            html += `<button class="${p === currentPage ? 'active' : ''}" onclick="goToCustomerPage(${p})">${p}</button>`;
        }

        html += `<button ${currentPage === totalPages ? 'disabled' : ''} onclick="goToCustomerPage(${currentPage + 1})">&raquo;</button>`;
        btns.innerHTML = html;
    }

    function goToCustomerPage(page) {
        currentPage = page;
        const sort = document.getElementById('sortSelect').value;
        const sorted = sortCustomers(cachedCustomers, sort);
        const tbody = document.getElementById('customerTableBody');
        tbody.classList.add('fade-out');
        setTimeout(() => {
            renderCustomerTable(sorted);
            tbody.classList.remove('fade-out');
            tbody.classList.add('fade-in');
            setTimeout(() => tbody.classList.remove('fade-in'), 250);
            // Scroll to top of table
            document.querySelector('.data-card')?.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }, 150);
    }

    // ===== Handle sort change (client-side, no fetch) =====
    function onSortChange() {
        if (!cachedCustomers) { loadCustomers(); return; }
        currentPage = 1;
        const sort = document.getElementById('sortSelect').value;
        const sorted = sortCustomers(cachedCustomers, sort);
        const tbody = document.getElementById('customerTableBody');
        tbody.classList.add('fade-out');
        setTimeout(() => {
            renderCustomerTable(sorted);
            tbody.classList.remove('fade-out');
            tbody.classList.add('fade-in');
            setTimeout(() => tbody.classList.remove('fade-in'), 250);
        }, 150);
    }

    // ===== Load Customers (fetch from server) =====
    function loadCustomers() {
        const search = document.getElementById('searchInput').value;
        const sort = document.getElementById('sortSelect').value;
        const tbody = document.getElementById('customerTableBody');

        // Reset to page 1 on new fetch
        currentPage = 1;
        tbody.classList.add('fade-out');

        fetch(`?ajax=customers&search=${encodeURIComponent(search)}&sort=${sort}`)
            .then(r => r.json())
            .then(res => {
                if (res.status !== 'success') { tbody.innerHTML = '<tr><td colspan="7" class="empty-state">ເກີດຂໍ້ຜິດພາດ</td></tr>'; tbody.classList.remove('fade-out'); return; }
                // Cache the raw data
                cachedCustomers = res.data;
                // Also invalidate ranking cache since data may have changed
                cachedRanking = null;
                rankingLoaded = false;

                // Update summary
                document.getElementById('statCustomers').textContent = res.summary.total_customers.toLocaleString();
                document.getElementById('statOrders').textContent = res.summary.total_orders.toLocaleString();
                document.getElementById('statSpend').textContent = Number(res.summary.total_spend).toLocaleString() + ' ₭';
                const avg = res.summary.total_customers > 0 ? Math.round(res.summary.total_spend / res.summary.total_customers) : 0;
                document.getElementById('statAvg').textContent = avg.toLocaleString() + ' ₭';

                const sorted = sortCustomers(res.data, sort);
                renderCustomerTable(sorted);
                // Fade in
                tbody.classList.remove('fade-out');
                tbody.classList.add('fade-in');
                setTimeout(() => tbody.classList.remove('fade-in'), 250);
            }).catch(() => { tbody.innerHTML = '<tr><td colspan="7" class="empty-state">ເກີດຂໍ້ຜິດພາດ</td></tr>'; tbody.classList.remove('fade-out'); });
    }

    // ===== Load Ranking (use cached data when possible) =====
    function loadRanking() {
        const limit = parseInt(document.getElementById('rankLimit').value);
        const tbody = document.getElementById('rankingTableBody');

        // If we have cached customers, build ranking from that (instant!)
        if (cachedCustomers && cachedCustomers.length) {
            const rankCol = currentRankBy === 'order_count' ? 'order_count' : 'total_spend';
            const sorted = [...cachedCustomers]
                .filter(c => Number(c.order_count) > 0)
                .sort((a, b) => Number(b[rankCol]) - Number(a[rankCol]))
                .slice(0, limit);
            renderRankingTable(sorted, tbody);
            rankingLoaded = true;
            return;
        }

        // Fallback: fetch from server
        tbody.classList.add('fade-out');

        fetch(`?ajax=customer_ranking&rank_by=${currentRankBy}&limit=${limit}`)
            .then(r => r.json())
            .then(res => {
                if (res.status !== 'success' || !res.data.length) { tbody.innerHTML = '<tr><td colspan="6" class="empty-state">ບໍ່ມີຂໍ້ມູນ</td></tr>'; } else {
                    cachedRanking = res.data;
                    renderRankingTable(res.data, tbody);
                }
                rankingLoaded = true;
                tbody.classList.remove('fade-out');
                tbody.classList.add('fade-in');
                setTimeout(() => tbody.classList.remove('fade-in'), 250);
            });
    }

    function setRankBy(val, btn) {
        currentRankBy = val;
        document.querySelectorAll('.rank-opt').forEach(b => b.classList.remove('active'));
        btn.classList.add('active');
        loadRanking();
    }

    // ===== Render ranking table =====
    function renderRankingTable(data, tbody) {
        if (!data.length) {
            tbody.innerHTML = '<tr><td colspan="6" class="empty-state">ບໍ່ມີຂໍ້ມູນ</td></tr>';
            return;
        }
        tbody.classList.add('fade-out');
        setTimeout(() => {
            tbody.innerHTML = data.map((c, i) => {
                const rc = i < 3 ? `rank-${i + 1}` : 'rank-other';
                return `<tr onclick="openCustomerDetail('${c.CU_id}')" style="cursor:pointer">
                    <td><span class="rank-badge ${rc}">${i + 1}</span></td>
                    <td><strong>${esc(c.name)}</strong></td>
                    <td>${esc(c.phone || '-')}</td>
                    <td>${Number(c.order_count).toLocaleString()}</td>
                    <td class="amount-gold">${Number(c.total_spend).toLocaleString()} ₭</td>
                    <td>${(c.last_order || c.last_order_date) ? formatDate(c.last_order || c.last_order_date) : '-'}</td>
                </tr>`;
            }).join('');
            tbody.classList.remove('fade-out');
            tbody.classList.add('fade-in');
            setTimeout(() => tbody.classList.remove('fade-in'), 250);
        }, 100);
    }

    // ===== Customer Detail Modal =====
    function openCustomerDetail(cuId) {
        const modal = document.getElementById('customerModal');
        const body = document.getElementById('modalBody');
        document.getElementById('modalCuName').textContent = 'ກຳລັງໂຫຼດ...';
        body.innerHTML = '<div class="cu-loading"><i class="fas fa-spinner"></i><br>ກຳລັງໂຫຼດ...</div>';
        modal.classList.add('show');

        Promise.all([
            fetch(`?ajax=customer_detail&cu_id=${cuId}`).then(r => r.json()),
            fetch(`?ajax=customer_behavior&cu_id=${cuId}`).then(r => r.json())
        ]).then(([detail, behavior]) => {
            if (detail.status !== 'success') { body.innerHTML = '<div class="empty-state">ບໍ່ພົບຂໍ້ມູນ</div>'; return; }
            const c = detail.customer;
            const totalSpend = detail.orders.reduce((s, o) => s + parseFloat(o.total_amount_lak || 0), 0);
            document.getElementById('modalCuName').textContent = c.name;

            // Build detail HTML
            let html = `
        <div class="detail-grid">
            <div class="detail-box"><h4><i class="fas fa-user"></i> ຂໍ້ມູນ</h4><div><strong>ຊື່:</strong> ${esc(c.name)}<br><strong>ເບີໂທ:</strong> ${esc(c.phone || '-')}<br><strong>ລົງທະບຽນ:</strong> ${formatDate(c.created_at)}</div></div>
            <div class="detail-box"><h4><i class="fas fa-chart-bar"></i> ສະຖິຕິ</h4><div class="val">${totalSpend.toLocaleString()} ₭</div><div class="sub">${detail.orders.length} ຄັ້ງ ສັ່ງທັງໝົດ</div></div>
        </div>
        <div class="inner-tabs">
            <button class="inner-tab active" onclick="switchInner('orders',this)"><i class="fas fa-history"></i> ປະຫວັດສັ່ງຊື້</button>
            <button class="inner-tab" onclick="switchInner('favorites',this)"><i class="fas fa-heart"></i> ສິນຄ້ານິຍົມ</button>
            <button class="inner-tab" onclick="switchInner('monthly',this)"><i class="fas fa-calendar-alt"></i> ລາຍເດືອນ</button>
            <button class="inner-tab" onclick="switchInner('season',this)"><i class="fas fa-gift"></i> ເທດສະການ</button>
        </div>`;

            // Orders panel
            html += `<div class="inner-panel active" id="panel-orders">`;
            if (detail.orders.length) {
                html += `<div style="display:flex;justify-content:flex-end;margin-bottom:12px"><a href="history_pos.php?customer_id=${encodeURIComponent(c.CU_id)}" style="display:inline-flex;align-items:center;gap:6px;padding:8px 16px;background:var(--accent);color:#fff;border-radius:8px;text-decoration:none;font-size:14px;font-weight:500;transition:all .2s" onmouseover="this.style.opacity='0.85'" onmouseout="this.style.opacity='1'"><i class="fas fa-external-link-alt"></i> ເບິ່ງທັງໝົດໃນໜ້າປະຫວັດ</a></div>`;
                html += '<table class="order-hist-table"><thead><tr><th>ເລກບິນ</th><th>ວັນທີ</th><th>ປະເພດ</th><th>ສິນຄ້າ</th><th style="text-align:right">ຍອດ (₭)</th></tr></thead><tbody>';
                detail.orders.forEach(o => {
                    const items = (o.items || []).map(it => esc(it.product_name) + ' x' + it.quantity).join(', ');
                    const sym = o.currencys_symbol || '₭';
                    html += `<tr><td>${o.OR_id}</td><td>${formatDate(o.created_at)}</td><td>${o.order_type === 'pos' ? 'ໜ້າຮ້ານ' : 'ອອນລາຍ'}</td><td style="max-width:300px;white-space:normal;font-size:13px">${items || '-'}</td><td style="text-align:right" class="amount-gold">${Number(o.total_amount_lak).toLocaleString()}</td></tr>`;
                });
                html += '</tbody></table>';
            } else html += '<div class="empty-state">ບໍ່ມີປະຫວັດ</div>';
            html += '</div>';

            // Favorites panel
            html += `<div class="inner-panel" id="panel-favorites">`;
            if (detail.favorites.length) {
                const maxQty = Math.max(...detail.favorites.map(f => parseInt(f.total_qty)));
                html += '<ul class="fav-list">';
                detail.favorites.forEach((f, i) => {
                    const pct = Math.round((parseInt(f.total_qty) / maxQty) * 100);
                    html += `<li class="fav-item"><span class="fav-rank">${i + 1}</span><div class="fav-info"><div class="fav-name">${esc(f.product_name)}</div><div class="fav-meta">ສັ່ງ ${f.times_ordered} ຄັ້ງ · ${Number(f.total_qty).toLocaleString()} ຊິ້ນ</div></div><div class="fav-bar-wrap"><div class="fav-bar" style="width:${pct}%"></div></div></li>`;
                });
                html += '</ul>';
            } else html += '<div class="empty-state">ບໍ່ມີຂໍ້ມູນ</div>';
            html += '</div>';

            // Monthly panel
            html += `<div class="inner-panel" id="panel-monthly">`;
            if (detail.monthly_stats.length) {
                const maxSpend = Math.max(...detail.monthly_stats.map(m => parseFloat(m.total_spend)));
                const monthNames = ['', 'ມ.ກ.', 'ກ.ພ.', 'ມີ.ນ.', 'ເມ.ສ.', 'ພ.ພ.', 'ມິ.ຖ.', 'ກ.ກ.', 'ສ.ຫ.', 'ກ.ຍ.', 'ຕ.ລ.', 'ພ.ຈ.', 'ທ.ວ.'];
                const totalMonthlySpend = detail.monthly_stats.reduce((s, m) => s + parseFloat(m.total_spend), 0);
                const totalMonthlyOrders = detail.monthly_stats.reduce((s, m) => s + parseInt(m.order_count), 0);

                html += `<div style="display:flex;gap:12px;margin-bottom:16px;flex-wrap:wrap">
                    <div style="padding:12px 18px;background:rgba(193,153,42,.1);border-radius:12px;flex:1;min-width:140px;text-align:left;">
                        <div style="font-size:13px;color:var(--text-secondary)">ຍອດລວມ</div>
                        <div style="font-size:20px;font-weight:700;color:var(--accent)">${totalMonthlySpend.toLocaleString()} ₭</div>
                    </div>
                    <div style="padding:12px 18px;background:rgba(74,144,226,.1);border-radius:12px;flex:1;min-width:140px;text-align:left;">
                        <div style="font-size:13px;color:var(--text-secondary)">ສັ່ງທັງໝົດ</div>
                        <div style="font-size:20px;font-weight:700;color:#4a90e2">${totalMonthlyOrders} ຄັ້ງ</div>
                    </div>
                </div>`;

                html += '<table class="order-hist-table"><thead><tr><th>ເດືອນ</th><th>ຈຳນວນຄັ້ງ</th><th>ຍອດເງິນ (₭)</th><th style="width:35%">ສັດສ່ວນ</th></tr></thead><tbody>';
                detail.monthly_stats.reverse().forEach(m => {
                    const spend = parseFloat(m.total_spend);
                    const pct = Math.max(3, Math.round((spend / maxSpend) * 100));
                    const monthNum = parseInt(m.month.substring(5));
                    const monthLabel = monthNames[monthNum] || m.month.substring(5);
                    const yearMonth = m.month.substring(0, 4) + '/' + monthLabel;
                    html += `<tr>
                        <td style="font-weight:600;white-space:nowrap">${yearMonth}</td>
                        <td style="text-align:center">${Number(m.order_count)}</td>
                        <td style="text-align:right;font-weight:600;color:var(--accent)">${spend.toLocaleString()}</td>
                        <td><div style="background:var(--border-color);border-radius:6px;height:14px;overflow:hidden"><div style="height:100%;width:${pct}%;background:linear-gradient(90deg,var(--accent),#d4ac4a);border-radius:6px;transition:width .5s"></div></div></td>
                    </tr>`;
                });
                html += '</tbody></table>';
            } else html += '<div class="empty-state">ບໍ່ມີຂໍ້ມູນ</div>';
            html += '</div>';

            // Season panel
            html += `<div class="inner-panel" id="panel-season">`;
            if (behavior.status === 'success' && behavior.seasonal_events.length) {
                html += '<div class="season-tags">';
                const icons = { 1: 'fa-champagne-glasses', 2: 'fa-heart', 3: 'fa-venus', 4: 'fa-water', 8: 'fa-hand-holding-heart', 10: 'fa-moon', 11: 'fa-tags', 12: 'fa-tree' };
                behavior.seasonal_events.forEach(s => {
                    const ic = icons[s.month] || 'fa-calendar';
                    html += `<div class="season-tag"><i class="fas ${ic}"></i> ${esc(s.event)} (${s.orders} ຄັ້ງ)</div>`;
                });
                html += '</div>';
                if (behavior.monthly_pattern.length) {
                    const mp = behavior.monthly_pattern;
                    const peakMonth = mp.reduce((a, b) => parseFloat(a.total_spend) > parseFloat(b.total_spend) ? a : b);
                    html += `<div style="margin-top:16px;padding:14px;background:rgba(193,153,42,.08);border-radius:12px;font-size:14px"><i class="fas fa-lightbulb" style="color:var(--accent)"></i> <strong>ເດືອນທີ່ຊື້ເລື້ອຍສຸດ:</strong> ເດືອນ ${peakMonth.month_num} (${peakMonth.month_name}) — ${Number(peakMonth.order_count)} ຄັ້ງ, ຍອດ ${Number(peakMonth.total_spend).toLocaleString()} ₭</div>`;
                }
            } else html += '<div class="empty-state"><i class="fas fa-calendar-times"></i>ບໍ່ມີຂໍ້ມູນເທດສະການ</div>';
            html += '</div>';

            body.innerHTML = html;
        }).catch(e => { body.innerHTML = '<div class="empty-state">ເກີດຂໍ້ຜິດພາດ</div>'; console.error(e); });
    }

    function closeModal() { document.getElementById('customerModal').classList.remove('show'); }
    document.getElementById('customerModal').addEventListener('click', function (e) { if (e.target === this) closeModal(); });

    function switchInner(panel, btn) {
        document.querySelectorAll('.inner-tab').forEach(t => t.classList.remove('active'));
        document.querySelectorAll('.inner-panel').forEach(p => p.classList.remove('active'));
        btn.classList.add('active');
        document.getElementById('panel-' + panel).classList.add('active');
    }

    // ===== Utilities =====
    function debounceSearch() { clearTimeout(searchTimer); searchTimer = setTimeout(loadCustomers, 350); }
    function esc(s) { const d = document.createElement('div'); d.textContent = s; return d.innerHTML; }
    function formatDate(d) { if (!d) return '-'; const dt = new Date(d); return dt.toLocaleDateString('en-GB'); }

    // ===== Initial Load =====
    loadCustomers();
</script>

<?php require_once '../includes/footer.php'; ?>