<?php
// ===== AJAX Handler (must be before any HTML output) =====
if (session_status() === PHP_SESSION_NONE)
    session_start();
date_default_timezone_set('Asia/Vientiane');

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'manager') {
    if (isset($_GET['ajax'])) {
        echo json_encode(['error' => 'unauthorized']);
        exit;
    }
    header('Location: ../../login.php');
    exit;
}

require_once dirname(__DIR__, 2) . '/include/con_data.php';
$shop_id = $_SESSION['shop_id'] ?? 0;

// Helper: build date condition for SQL
function buildDateCondition($date_from, $date_to, $alias = 'o')
{
    if ($date_from && $date_to && $date_from === $date_to) {
        return "DATE({$alias}.created_at) = " . "'{$date_from}'";
    } elseif ($date_from && $date_to) {
        return "DATE({$alias}.created_at) BETWEEN '{$date_from}' AND '{$date_to}'";
    } elseif ($date_from) {
        return "DATE({$alias}.created_at) >= '{$date_from}'";
    } elseif ($date_to) {
        return "DATE({$alias}.created_at) <= '{$date_to}'";
    }
    return "DATE({$alias}.created_at) = CURDATE()";
}

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

    $date_from = $_GET['date_from'] ?? date('Y-m-d');
    $date_to = $_GET['date_to'] ?? date('Y-m-d');
    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date_from))
        $date_from = date('Y-m-d');
    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date_to))
        $date_to = date('Y-m-d');

    // === AJAX: Daily Sales (Tab 1) ===
    if ($_GET['ajax'] === 'daily_sales') {
        $dc = buildDateCondition($date_from, $date_to, 'o');

        $stmt = $pdo->prepare("
            SELECT 
                COUNT(*) as total_orders,
                COALESCE(SUM(total_amount_lak), 0) as total_sales_lak,
                COALESCE(SUM(CASE WHEN currencys_id IS NULL OR currencys_id = 'LAK' THEN total_amount ELSE 0 END), 0) as lak_amount_total,
                COALESCE(SUM(CASE WHEN currencys_id IS NOT NULL AND currencys_id != 'LAK' THEN total_amount ELSE 0 END), 0) as foreign_amount_total,
                COALESCE(SUM(CASE WHEN currencys_id IS NOT NULL AND currencys_id != 'LAK' THEN total_amount_lak ELSE 0 END), 0) as foreign_amount_converted_lak,
                COALESCE(SUM(subtotal_lak), 0) as subtotal_lak,
                COALESCE(SUM(discount_lak), 0) as discount_lak,
                COALESCE(SUM(vat_amount_lak), 0) as tax_lak,
                MIN(created_at) as first_order,
                MAX(created_at) as last_order
            FROM orders o
            WHERE o.shop_id = ? AND $dc
        ");
        $stmt->execute([$shop_id]);
        $summary = $stmt->fetch();

        $stmt = $pdo->prepare("
            SELECT o.OR_id, o.bill_number, o.created_at, o.order_type, o.payment_status, 
                o.total_amount_lak, c.name as customer_name, u.name as user_name,
                o.currencys_id, cur.currencys_name, o.total_amount, o.currency_rate
            FROM orders o
            LEFT JOIN customers c ON o.customer_id = c.CU_id
            LEFT JOIN users u ON o.created_by = u.user_id
            LEFT JOIN currencys cur ON o.currencys_id = cur.currencys_id
            WHERE o.shop_id = ? AND $dc
            ORDER BY o.created_at DESC
        ");
        $stmt->execute([$shop_id]);
        $orders = $stmt->fetchAll();

        // Grouping foreign currency totals
        $stmt = $pdo->prepare("
            SELECT o.currencys_id, c.currencys_name,
                   SUM(o.total_amount) as amount_foreign, 
                   SUM(o.total_amount_lak) as amount_lak
            FROM orders o
            LEFT JOIN currencys c ON o.currencys_id = c.currencys_id
            WHERE o.shop_id = ? AND o.currencys_id IS NOT NULL AND o.currencys_id != 'LAK' AND $dc
            GROUP BY o.currencys_id, c.currencys_name
        ");
        $stmt->execute([$shop_id]);
        $foreign_breakdown = $stmt->fetchAll();

        echo json_encode(['summary' => $summary, 'orders' => $orders, 'foreign_breakdown' => $foreign_breakdown]);
        exit;
    }

    // === AJAX: User Sales (Tab 2) ===
    if ($_GET['ajax'] === 'user_sales') {
        $user_id = $_GET['user_id'] ?? '';
        $dc = buildDateCondition($date_from, $date_to, 'o');

        $stmt = $pdo->prepare("
            SELECT 
                COUNT(*) as total_orders,
                COALESCE(SUM(total_amount_lak), 0) as total_sales_lak,
                MIN(created_at) as first_order,
                MAX(created_at) as last_order
            FROM orders o
            WHERE o.shop_id = ? AND o.created_by = ? AND $dc
        ");
        $stmt->execute([$shop_id, $user_id]);
        $summary = $stmt->fetch();

        $stmt = $pdo->prepare("
            SELECT o.OR_id, o.bill_number, o.created_at, o.order_type, o.payment_status, 
                o.total_amount_lak, c.name as customer_name
            FROM orders o
            LEFT JOIN customers c ON o.customer_id = c.CU_id
            WHERE o.shop_id = ? AND o.created_by = ? AND $dc
            ORDER BY o.created_at DESC
        ");
        $stmt->execute([$shop_id, $user_id]);
        $orders = $stmt->fetchAll();

        echo json_encode(['summary' => $summary, 'orders' => $orders]);
        exit;
    }

    // === AJAX: Top Products (Tab 3) ===
    if ($_GET['ajax'] === 'top_products') {
        $range = $_GET['range'] ?? 'custom';

        if ($range === 'today') {
            $dateCondition = "DATE(o.created_at) = CURDATE()";
        } elseif ($range === '7days') {
            $dateCondition = "o.created_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)";
        } elseif ($range === '30days') {
            $dateCondition = "o.created_at >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)";
        } else {
            $dateCondition = buildDateCondition($date_from, $date_to, 'o');
        }

        $stmt = $pdo->prepare("
            SELECT oi.product_name, 
                SUM(oi.quantity) as total_qty,
                SUM(oi.total) as total_revenue
            FROM order_items oi
            JOIN orders o ON oi.order_id = o.id
            WHERE o.shop_id = ? AND $dateCondition
            GROUP BY oi.product_name
            ORDER BY total_qty DESC
            LIMIT 50
        ");
        $stmt->execute([$shop_id]);
        $products = $stmt->fetchAll();

        echo json_encode(['products' => $products]);
        exit;
    }

    echo json_encode(['error' => 'unknown']);
    exit;
}

// ===== Normal page load =====
$page_title = 'ລາຍງານຍອດຂາຍ';
require_once '../includes/header.php';

$today = date('Y-m-d');

// TAB 1: Today's Sales (initial)
$stmt = $pdo->prepare("
    SELECT COUNT(*) as total_orders,
        COALESCE(SUM(total_amount_lak), 0) as total_sales_lak,
        COALESCE(SUM(CASE WHEN currencys_id IS NULL OR currencys_id = 'LAK' THEN total_amount ELSE 0 END), 0) as lak_amount_total,
        COALESCE(SUM(CASE WHEN currencys_id IS NOT NULL AND currencys_id != 'LAK' THEN total_amount ELSE 0 END), 0) as foreign_amount_total,
        COALESCE(SUM(CASE WHEN currencys_id IS NOT NULL AND currencys_id != 'LAK' THEN total_amount_lak ELSE 0 END), 0) as foreign_amount_converted_lak,
        COALESCE(SUM(subtotal_lak), 0) as subtotal_lak,
        COALESCE(SUM(discount_lak), 0) as discount_lak,
        COALESCE(SUM(vat_amount_lak), 0) as tax_lak,
        MIN(created_at) as first_order,
        MAX(created_at) as last_order
    FROM orders WHERE shop_id = ? AND DATE(created_at) = CURDATE()
");
$stmt->execute([$shop_id]);
$todaySummary = $stmt->fetch();

$stmt = $pdo->prepare("
    SELECT o.*, c.name as customer_name, u.name as user_name, cur.currencys_name
    FROM orders o
    LEFT JOIN customers c ON o.customer_id = c.CU_id
    LEFT JOIN users u ON o.created_by = u.user_id
    LEFT JOIN currencys cur ON o.currencys_id = cur.currencys_id
    WHERE o.shop_id = ? AND DATE(o.created_at) = CURDATE()
    ORDER BY o.created_at DESC
");
$stmt->execute([$shop_id]);
$todayOrders = $stmt->fetchAll();

// Grouping foreign currency totals for today
$stmt = $pdo->prepare("
    SELECT o.currencys_id, c.currencys_name,
           SUM(o.total_amount) as amount_foreign, 
           SUM(o.total_amount_lak) as amount_lak
    FROM orders o
    LEFT JOIN currencys c ON o.currencys_id = c.currencys_id
    WHERE o.shop_id = ? AND o.currencys_id IS NOT NULL AND o.currencys_id != 'LAK' AND DATE(o.created_at) = CURDATE()
    GROUP BY o.currencys_id, c.currencys_name
");
$stmt->execute([$shop_id]);
$todayForeignBreakdown = $stmt->fetchAll();

// TAB 2: Users
$stmt = $pdo->prepare("
    SELECT user_id, name, username FROM users 
    WHERE (shop_id = ? OR role = 'superadmin') AND status = 1 ORDER BY name
");
$stmt->execute([$shop_id]);
$users = $stmt->fetchAll();

// TAB 4: Charts (30 days)
$stmt = $pdo->prepare("
    SELECT DATE(created_at) as sale_date, COUNT(*) as order_count,
        COALESCE(SUM(total_amount_lak), 0) as total_lak
    FROM orders WHERE shop_id = ? AND created_at >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
    GROUP BY DATE(created_at) ORDER BY sale_date ASC
");
$stmt->execute([$shop_id]);
$dailySales = $stmt->fetchAll();

$stmt = $pdo->prepare("
    SELECT oi.product_name, SUM(oi.quantity) as total_qty, SUM(oi.total) as total_revenue
    FROM order_items oi JOIN orders o ON oi.order_id = o.id
    WHERE o.shop_id = ? AND o.created_at >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
    GROUP BY oi.product_name ORDER BY total_qty DESC LIMIT 10
");
$stmt->execute([$shop_id]);
$topProducts = $stmt->fetchAll();

$stmt = $pdo->prepare("
    SELECT u.name as user_name, COUNT(*) as order_count,
        COALESCE(SUM(o.total_amount_lak), 0) as total_lak
    FROM orders o LEFT JOIN users u ON o.created_by = u.user_id
    WHERE o.shop_id = ? AND o.created_at >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
    GROUP BY o.created_by, u.name ORDER BY total_lak DESC
");
$stmt->execute([$shop_id]);
$salesByUser = $stmt->fetchAll();
?>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>

<style>
    .report-tabs {
        display: flex;
        gap: 5px;
        margin-bottom: 25px;
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 12px;
        padding: 5px;
        overflow-x: auto;
    }

    .report-tab {
        flex: 1;
        padding: 12px 18px;
        border: none;
        background: transparent;
        color: var(--text-secondary);
        font-family: inherit;
        font-size: 14px;
        font-weight: 500;
        border-radius: 8px;
        cursor: pointer;
        transition: all 0.3s ease;
        white-space: nowrap;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
    }

    .report-tab:hover {
        background: rgba(193, 153, 42, 0.1);
        color: var(--accent);
    }

    .report-tab.active {
        background: var(--accent);
        color: white;
        box-shadow: 0 4px 15px rgba(193, 153, 42, 0.3);
    }

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

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

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

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

    /* Summary Cards */
    .summary-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
        gap: 15px;
        margin-bottom: 25px;
    }

    .summary-card {
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 15px;
        padding: 20px;
        position: relative;
        overflow: hidden;
    }

    .summary-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 3px;
        border-radius: 15px 15px 0 0;
    }

    .summary-card.gold::before {
        background: #c1992a;
    }

    .summary-card.green::before {
        background: #28A745;
    }

    .summary-card.blue::before {
        background: #17A2B8;
    }

    .summary-card.orange::before {
        background: #FD7E14;
    }

    .summary-card.purple::before {
        background: #6C7AE0;
    }

    .summary-card.red::before {
        background: #DC3545;
    }

    .summary-card .sc-icon {
        width: 45px;
        height: 45px;
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 18px;
        color: white;
        margin-bottom: 12px;
    }

    .summary-card .sc-icon.gold {
        background: #c1992a;
    }

    .summary-card .sc-icon.green {
        background: linear-gradient(135deg, #28A745, #1E7B33);
    }

    .summary-card .sc-icon.blue {
        background: linear-gradient(135deg, #17A2B8, #138496);
    }

    .summary-card .sc-icon.orange {
        background: linear-gradient(135deg, #FD7E14, #E06B10);
    }

    .summary-card .sc-icon.purple {
        background: linear-gradient(135deg, #6C7AE0, #4A5BC7);
    }

    .summary-card .sc-icon.red {
        background: linear-gradient(135deg, #DC3545, #C42F3B);
    }

    .summary-card .sc-value {
        font-size: 24px;
        font-weight: 700;
        margin-bottom: 4px;
        line-height: 1.2;
    }

    .summary-card .sc-label {
        font-size: 13px;
        color: var(--text-secondary);
    }

    /* Table */
    .report-table-wrap {
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
    }

    .report-table {
        width: 100%;
        border-collapse: collapse;
        font-size: 14px;
    }

    .report-table thead th {
        padding: 12px 15px;
        text-align: left;
        font-weight: 600;
        color: var(--text-secondary);
        border-bottom: 2px solid var(--border-color);
        white-space: nowrap;
        font-size: 13px;
        text-transform: uppercase;
        letter-spacing: 0.3px;
    }

    .report-table tbody td {
        padding: 12px 15px;
        border-bottom: 1px solid var(--border-color);
        white-space: nowrap;
    }

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

    .report-table tbody tr:last-child td {
        border-bottom: none;
    }

    /* Badges */
    .badge {
        display: inline-flex;
        align-items: center;
        gap: 5px;
        padding: 4px 10px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 500;
    }

    .badge-success {
        background: rgba(40, 167, 69, 0.15);
        color: #28A745;
    }

    .badge-warning {
        background: rgba(255, 193, 7, 0.15);
        color: #FFC107;
    }

    .badge-pos {
        background: rgba(193, 153, 42, 0.15);
        color: var(--accent);
    }

    .badge-online {
        background: rgba(108, 122, 224, 0.15);
        color: #6C7AE0;
    }

    /* Date Range Filter */
    .date-range-bar {
        display: flex;
        align-items: center;
        gap: 10px;
        margin-bottom: 20px;
        flex-wrap: wrap;
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 12px;
        padding: 12px 18px;
    }

    .date-range-bar .filter-label {
        font-weight: 600;
        font-size: 14px;
        color: var(--text-primary);
        display: flex;
        align-items: center;
        gap: 6px;
        white-space: nowrap;
    }

    .date-range-bar .date-sep {
        color: var(--text-secondary);
        font-size: 14px;
        font-weight: 500;
        padding: 0 2px;
    }

    .date-input {
        padding: 9px 14px;
        background: var(--bg-secondary);
        border: 1px solid var(--border-color);
        border-radius: 8px;
        color: var(--text-primary);
        font-family: inherit;
        font-size: 14px;
        min-width: 155px;
        cursor: pointer;
        transition: all 0.3s ease;
        color-scheme: dark;
    }

    [data-theme="light"] .date-input {
        color-scheme: light;
    }

    .date-input:focus {
        outline: none;
        border-color: var(--accent);
        box-shadow: 0 0 0 3px rgba(193, 153, 42, 0.15);
    }

    .btn-search {
        padding: 9px 20px;
        background: var(--accent);
        color: white;
        border: none;
        border-radius: 8px;
        font-family: inherit;
        font-size: 14px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s ease;
        display: flex;
        align-items: center;
        gap: 6px;
    }

    .btn-search:hover {
        background: #a8841f;
        transform: translateY(-1px);
    }

    .btn-search:active {
        transform: translateY(0);
    }

    .btn-today {
        padding: 9px 16px;
        background: transparent;
        border: 1px solid var(--border-color);
        border-radius: 8px;
        color: var(--text-secondary);
        font-family: inherit;
        font-size: 13px;
        cursor: pointer;
        transition: all 0.3s ease;
        display: flex;
        align-items: center;
        gap: 5px;
    }

    .btn-today:hover {
        border-color: var(--accent);
        color: var(--accent);
    }

    .filter-separator {
        width: 1px;
        height: 30px;
        background: var(--border-color);
        margin: 0 5px;
    }

    /* User select */
    .user-select {
        padding: 9px 14px;
        background: var(--bg-secondary);
        border: 1px solid var(--border-color);
        border-radius: 8px;
        color: var(--text-primary);
        font-family: inherit;
        font-size: 14px;
        min-width: 220px;
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .user-select:focus {
        outline: none;
        border-color: var(--accent);
        box-shadow: 0 0 0 3px rgba(193, 153, 42, 0.15);
    }

    /* Quick filter buttons (Tab 3) */
    .quick-filters {
        display: flex;
        gap: 6px;
        flex-wrap: wrap;
    }

    .filter-btn {
        padding: 8px 14px;
        border: 1px solid var(--border-color);
        background: var(--card-bg);
        color: var(--text-secondary);
        border-radius: 8px;
        font-family: inherit;
        font-size: 13px;
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .filter-btn:hover {
        border-color: var(--accent);
        color: var(--accent);
    }

    .filter-btn.active {
        background: var(--accent);
        color: white;
        border-color: var(--accent);
    }

    /* Charts */
    .chart-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(450px, 1fr));
        gap: 20px;
    }

    .chart-card {
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 15px;
        padding: 20px;
    }

    .chart-card h4 {
        font-size: 16px;
        font-weight: 600;
        margin-bottom: 15px;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .chart-card canvas {
        width: 100% !important;
        max-height: 320px;
    }

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

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

    .user-summary-area {
        display: none;
    }

    .user-summary-area.show {
        display: block;
    }

    .rank-badge {
        width: 28px;
        height: 28px;
        border-radius: 50%;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        font-weight: 700;
        color: white;
    }

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

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

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

    .rank-other {
        background: var(--card-bg);
        color: var(--text-secondary);
        border: 1px solid var(--border-color);
    }

    @media (max-width: 768px) {
        .summary-grid {
            grid-template-columns: repeat(2, 1fr);
            gap: 10px;
        }

        .summary-card {
            padding: 15px;
        }

        .summary-card .sc-value {
            font-size: 18px;
        }

        .summary-card .sc-icon {
            width: 38px;
            height: 38px;
            font-size: 15px;
        }

        .report-tab {
            padding: 10px 12px;
            font-size: 12px;
        }

        .chart-grid {
            grid-template-columns: 1fr;
        }

        .date-range-bar {
            flex-direction: column;
            align-items: stretch;
        }

        .user-select,
        .date-input {
            min-width: 100%;
        }

        .filter-separator {
            display: none;
        }

        .btn-search,
        .btn-today {
            width: 100%;
            justify-content: center;
        }
    }

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

    /* Sales Report Pagination */
    .sr-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;
    }

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

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

    .sr-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;
    }

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

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

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

<!-- ===== TABS ===== -->
<div class="report-tabs">
    <button class="report-tab active" onclick="switchTab('tab1', this)">
        <i class="fas fa-chart-line"></i> <span>ຍອດຂາຍລາຍວັນ</span>
    </button>
    <button class="report-tab" onclick="switchTab('tab2', this)">
        <i class="fas fa-users"></i> <span>ຍອດຂາຍລາຍ User</span>
    </button>
    <button class="report-tab" onclick="switchTab('tab3', this)">
        <i class="fas fa-fire"></i> <span>ສິນຄ້າຂາຍດີ</span>
    </button>
    <button class="report-tab" onclick="switchTab('tab4', this)">
        <i class="fas fa-chart-bar"></i> <span>ກຣາບສະຫຼຸບ</span>
    </button>
</div>

<!-- ================================================================== -->
<!-- TAB 1: Daily Sales -->
<!-- ================================================================== -->
<div class="tab-content active" id="tab1">
    <div class="date-range-bar">
        <span class="filter-label"><i class="fas fa-calendar"></i> ວັນທີ:</span>
        <input type="date" class="date-input" id="tab1From" value="<?= $today ?>">
        <span class="date-sep">ຫາ</span>
        <input type="date" class="date-input" id="tab1To" value="<?= $today ?>">
        <button class="btn-search" onclick="loadDailySales()">
            <i class="fas fa-search"></i> ຄົ້ນຫາ
        </button>
        <button class="btn-today" onclick="setToday('tab1'); loadDailySales();">
            <i class="fas fa-redo"></i> ມື້ນີ້
        </button>
    </div>

    <div class="summary-grid" id="tab1SummaryCards">
        <div class="summary-card gold">
            <div class="sc-icon gold"><i class="fas fa-coins"></i></div>
            <div class="sc-value"><?= number_format($todaySummary['total_sales_lak'] ?? 0) ?> ₭</div>
            <div class="sc-label">ຍອດຂາຍລວມ (LAK)</div>
        </div>

        <div class="summary-card gold" style="border-left: 4px solid #c1992a;">
            <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 15px;">
                <div class="sc-icon gold" style="opacity: 0.8; margin-bottom: 0;"><i class="fas fa-globe-asia"></i>
                </div>
                <div style="font-weight: 600; font-size: 14px; color: var(--text-secondary);">ຍອດຮັບເງິນຕ່າງປະເທດ</div>
            </div>
            <div style="font-size: 14px;">
                <?php if (!empty($todayForeignBreakdown)): ?>
                    <?php foreach ($todayForeignBreakdown as $fb): ?>
                        <div
                            style="display: flex; justify-content: space-between; margin-bottom: 5px; border-bottom: 1px dotted rgba(255,255,255,0.1); padding-bottom: 3px;">
                            <span><strong><?= htmlspecialchars($fb['currencys_name'] ?? $fb['currencys_id']) ?></strong>:
                                <?= number_format($fb['amount_foreign']) ?></span>
                            <span style="color:var(--text-secondary);">(~<?= number_format($fb['amount_lak']) ?> ₭)</span>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="sc-value">0</div>
                    <div class="sc-label">ບໍ່ມີຍອດຮັບເງິນຕ່າງປະເທດ</div>
                <?php endif; ?>
            </div>
        </div>
        <div class="summary-card green">
            <div class="sc-icon green"><i class="fas fa-receipt"></i></div>
            <div class="sc-value"><?= number_format($todaySummary['total_orders'] ?? 0) ?></div>
            <div class="sc-label">ຈຳນວນ Orders</div>
        </div>
        <div class="summary-card blue">
            <div class="sc-icon blue"><i class="fas fa-calculator"></i></div>
            <div class="sc-value"><?= number_format($todaySummary['subtotal_lak'] ?? 0) ?> ₭</div>
            <div class="sc-label">Subtotal</div>
        </div>
        <div class="summary-card orange">
            <div class="sc-icon orange"><i class="fas fa-tags"></i></div>
            <div class="sc-value"><?= number_format($todaySummary['discount_lak'] ?? 0) ?> ₭</div>
            <div class="sc-label">ສ່ວນຫຼຸດ (Discount)</div>
        </div>
        <div class="summary-card purple">
            <div class="sc-icon purple"><i class="fas fa-percent"></i></div>
            <div class="sc-value"><?= number_format($todaySummary['tax_lak'] ?? 0) ?> ₭</div>
            <div class="sc-label">ພາສີ (Tax)</div>
        </div>
        <div class="summary-card red">
            <div class="sc-icon red"><i class="fas fa-clock"></i></div>
            <div class="sc-value"><?php
            if ($todaySummary['first_order']) {
                echo date('H:i', strtotime($todaySummary['first_order'])) . ' - ' . date('H:i', strtotime($todaySummary['last_order']));
            } else {
                echo '--:-- - --:--';
            }
            ?></div>
            <div class="sc-label">ຊ່ວງເວລາການຂາຍ</div>
        </div>
    </div>

    <div class="card">
        <div class="card-header">
            <h3 class="card-title"><i class="fas fa-list"></i> ລາຍການ Orders</h3>
            <span id="tab1DateLabel" style="font-size:13px;color:var(--text-secondary);"><?= date('d/m/Y') ?></span>
        </div>
        <div class="card-body">
            <div class="report-table-wrap" id="tab1OrdersTable">
                <?php if (count($todayOrders) > 0): ?>
                    <table class="report-table">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Order ID</th>
                                <th>Bill</th>
                                <th>ເວລາ</th>
                                <th>ປະເພດ</th>
                                <th>ລູກຄ້າ</th>
                                <th>ຜູ້ຂາຍ</th>
                                <th>ສະຖານະ</th>
                                <th style="text-align:right;">ຍອດລວມ (LAK)</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($todayOrders as $i => $order): ?>
                                <tr>
                                    <td><?= $i + 1 ?></td>
                                    <td><strong><?= htmlspecialchars($order['OR_id']) ?></strong></td>
                                    <td><?= htmlspecialchars($order['bill_number'] ?? '-') ?></td>
                                    <td><?= date('H:i', strtotime($order['created_at'])) ?></td>
                                    <td>
                                        <span
                                            class="badge <?= $order['order_type'] === 'pos' ? 'badge-pos' : 'badge-online' ?>">
                                            <i
                                                class="fas <?= $order['order_type'] === 'pos' ? 'fa-cash-register' : 'fa-globe' ?>"></i>
                                            <?= strtoupper($order['order_type']) ?>
                                        </span>
                                    </td>
                                    <td><?= htmlspecialchars($order['customer_name'] ?? 'Walk-in') ?></td>
                                    <td><?= htmlspecialchars($order['user_name'] ?? '-') ?></td>
                                    <td>
                                        <span
                                            class="badge <?= $order['payment_status'] === 'paid' ? 'badge-success' : 'badge-warning' ?>">
                                            <?= $order['payment_status'] === 'paid' ? 'ຈ່າຍແລ້ວ' : 'ລໍຖ້າ' ?>
                                        </span>
                                    </td>
                                    <td style="text-align:right;font-weight:600;">
                                        <?= number_format($order['total_amount_lak']) ?> ₭
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php else: ?>
                    <div class="empty-state"><i class="fas fa-inbox"></i>
                        <p>ຍັງບໍ່ມີ Order</p>
                    </div>
                <?php endif; ?>
            </div>
            <div class="sr-pagination-wrap" id="tab1PaginationWrap" style="display:none">
                <div class="sr-pagination-info" id="tab1PaginationInfo"></div>
                <div class="sr-pagination-btns" id="tab1PaginationBtns"></div>
            </div>
        </div>
    </div>
</div>

<!-- ================================================================== -->
<!-- TAB 2: Sales by User -->
<!-- ================================================================== -->
<div class="tab-content" id="tab2">
    <div class="date-range-bar">
        <span class="filter-label"><i class="fas fa-user"></i> User:</span>
        <select class="user-select" id="userSelect" onchange="loadUserSales()">
            <option value="">-- ເລືອກ User --</option>
            <?php foreach ($users as $u): ?>
                <option value="<?= htmlspecialchars($u['user_id']) ?>">
                    <?= htmlspecialchars($u['name']) ?> (<?= htmlspecialchars($u['username']) ?>)
                </option>
            <?php endforeach; ?>
        </select>

        <div class="filter-separator"></div>

        <span class="filter-label"><i class="fas fa-calendar"></i> ວັນທີ:</span>
        <input type="date" class="date-input" id="tab2From" value="<?= $today ?>">
        <span class="date-sep">ຫາ</span>
        <input type="date" class="date-input" id="tab2To" value="<?= $today ?>">
        <button class="btn-search" onclick="loadUserSales()">
            <i class="fas fa-search"></i> ຄົ້ນຫາ
        </button>
        <button class="btn-today" onclick="setToday('tab2'); loadUserSales();">
            <i class="fas fa-redo"></i> ມື້ນີ້
        </button>
    </div>

    <div class="user-summary-area" id="userSummaryArea">
        <div class="summary-grid" id="userSummaryCards"></div>
        <div class="card">
            <div class="card-header">
                <h3 class="card-title"><i class="fas fa-list"></i> ລາຍການ Orders ຂອງ User</h3>
                <span id="userDateLabel" style="font-size:13px;color:var(--text-secondary);"><?= date('d/m/Y') ?></span>
            </div>
            <div class="card-body">
                <div class="report-table-wrap" id="userOrdersTable"></div>
            </div>
        </div>
    </div>

    <div class="empty-state" id="userEmptyState">
        <i class="fas fa-user-circle"></i>
        <p>ກະລຸນາເລືອກ User ເພື່ອເບິ່ງລາຍງານ</p>
    </div>
</div>

<!-- ================================================================== -->
<!-- TAB 3: Best-selling Products -->
<!-- ================================================================== -->
<div class="tab-content" id="tab3">
    <div class="date-range-bar">
        <div class="quick-filters">
            <button class="filter-btn active" onclick="loadTopProducts('today', this)">
                <i class="fas fa-calendar-day"></i> ມື້ນີ້
            </button>
            <button class="filter-btn" onclick="loadTopProducts('7days', this)">
                <i class="fas fa-calendar-week"></i> 7 ວັນ
            </button>
            <button class="filter-btn" onclick="loadTopProducts('30days', this)">
                <i class="fas fa-calendar-alt"></i> 30 ວັນ
            </button>
        </div>

        <div class="filter-separator"></div>

        <span class="filter-label"><i class="fas fa-calendar-check"></i> ກຳນົດເອງ:</span>
        <input type="date" class="date-input" id="tab3From" value="<?= $today ?>">
        <span class="date-sep">ຫາ</span>
        <input type="date" class="date-input" id="tab3To" value="<?= $today ?>">
        <button class="btn-search" onclick="loadTopProductsCustom()">
            <i class="fas fa-search"></i> ຄົ້ນຫາ
        </button>
    </div>

    <div class="card">
        <div class="card-header">
            <h3 class="card-title"><i class="fas fa-fire"></i> ສິນຄ້າຂາຍດີ</h3>
        </div>
        <div class="card-body">
            <div class="report-table-wrap" id="topProductsTable">
                <div class="empty-state"><i class="fas fa-spinner fa-spin"></i>
                    <p>ກຳລັງໂຫຼດ...</p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ================================================================== -->
<!-- TAB 4: Charts -->
<!-- ================================================================== -->
<div class="tab-content" id="tab4">
    <div class="chart-grid">
        <div class="chart-card">
            <h4><i class="fas fa-chart-line" style="color:var(--accent);"></i> ຍອດຂາຍລາຍວັນ (30 ວັນ)</h4>
            <canvas id="dailySalesChart"></canvas>
        </div>
        <div class="chart-card">
            <h4><i class="fas fa-chart-bar" style="color:#6C7AE0;"></i> ປຽບທຽບຍອດຂາຍລາຍວັນ</h4>
            <canvas id="dailyCompareChart"></canvas>
        </div>
        <div class="chart-card">
            <h4><i class="fas fa-box" style="color:#28A745;"></i> ສິນຄ້າຂາຍດີ Top 10</h4>
            <canvas id="topProductsChart"></canvas>
        </div>
        <div class="chart-card">
            <h4><i class="fas fa-users" style="color:#FD7E14;"></i> ຍອດຂາຍແຍກຕາມ User</h4>
            <canvas id="userSalesChart"></canvas>
        </div>
    </div>
</div>

<script>
    const TODAY = '<?= $today ?>';
    let tab1Orders = []; // cached orders for pagination
    let tab1Page = 1;
    const TAB1_PAGE_SIZE = 50;

    function switchTab(tabId, btn) {
        document.querySelectorAll('.report-tab').forEach(t => t.classList.remove('active'));
        btn.classList.add('active');

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

        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 (tabId === 'tab4' && !window.chartsInitialized) { initCharts(); window.chartsInitialized = true; }
                if (tabId === 'tab3' && !window.topProductsLoaded) {
                    loadTopProducts('today', document.querySelector('#tab3 .filter-btn.active'));
                    window.topProductsLoaded = true;
                }
            }, 150);
        } else {
            next.classList.add('active');
            if (tabId === 'tab4' && !window.chartsInitialized) { initCharts(); window.chartsInitialized = true; }
            if (tabId === 'tab3' && !window.topProductsLoaded) {
                loadTopProducts('today', document.querySelector('#tab3 .filter-btn.active'));
                window.topProductsLoaded = true;
            }
        }
    }

    function formatNumber(n) { return new Intl.NumberFormat('en-US').format(Math.round(n)); }

    function formatDateDisplay(d1, d2) {
        const f = d => { const p = d.split('-'); return p[2] + '/' + p[1] + '/' + p[0]; };
        return d1 === d2 ? f(d1) : f(d1) + ' - ' + f(d2);
    }

    function setToday(tab) {
        document.getElementById(tab + 'From').value = TODAY;
        document.getElementById(tab + 'To').value = TODAY;
    }

    function buildDateParams(tab) {
        const from = document.getElementById(tab + 'From').value;
        const to = document.getElementById(tab + 'To').value;
        return 'date_from=' + encodeURIComponent(from) + '&date_to=' + encodeURIComponent(to);
    }

    // ===== TAB 1: Load Daily Sales =====
    function loadDailySales() {
        const from = document.getElementById('tab1From').value;
        const to = document.getElementById('tab1To').value;
        document.getElementById('tab1DateLabel').textContent = formatDateDisplay(from, to);
        const summaryEl = document.getElementById('tab1SummaryCards');
        const tableEl = document.getElementById('tab1OrdersTable');
        summaryEl.classList.add('sr-fade-out');
        tableEl.classList.add('sr-fade-out');

        fetch('?ajax=daily_sales&' + buildDateParams('tab1'))
            .then(r => r.json())
            .then(data => {
                const s = data.summary;
                const fBreakdown = data.foreign_breakdown || [];
                let t1 = s.first_order ? new Date(s.first_order).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' }) : '--:--';
                let t2 = s.last_order ? new Date(s.last_order).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' }) : '--:--';

                // Build foreign breakdown string
                let foreignHtml = '';
                if (fBreakdown.length > 0) {
                    fBreakdown.forEach(cur => {
                        let cName = cur.currencys_name ? cur.currencys_name : cur.currencys_id;
                        foreignHtml += `
                            <div style="display: flex; justify-content: space-between; margin-bottom: 5px; border-bottom: 1px dotted rgba(255,255,255,0.1); padding-bottom: 3px;">
                                <span><strong>${cName}</strong>: ${formatNumber(cur.amount_foreign)}</span>
                                <span style="color:var(--text-secondary);">(~ ${formatNumber(cur.amount_lak)} ₭)</span>
                            </div>
                        `;
                    });
                } else {
                    foreignHtml = `<div class="sc-value">0</div><div class="sc-label">ບໍ່ມີຍອດຮັບເງິນຕ່າງປະເທດ</div>`;
                }

                document.getElementById('tab1SummaryCards').innerHTML = `
                <div class="summary-card gold"><div class="sc-icon gold"><i class="fas fa-coins"></i></div>
                    <div class="sc-value">${formatNumber(s.total_sales_lak)} ₭</div><div class="sc-label">ຍອດຂາຍລວມ (LAK)</div></div>
                
                <div class="summary-card gold" style="border-left: 4px solid #c1992a;">
                    <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 15px;">
                        <div class="sc-icon gold" style="opacity: 0.8; margin-bottom: 0;"><i class="fas fa-globe-asia"></i></div>
                        <div style="font-weight: 600; font-size: 14px; color: var(--text-secondary);">ຍອດຮັບເງິນຕ່າງປະເທດ</div>
                    </div>
                    <div style="font-size: 14px;">${foreignHtml}</div>
                </div>
                <div class="summary-card green"><div class="sc-icon green"><i class="fas fa-receipt"></i></div>
                    <div class="sc-value">${formatNumber(s.total_orders)}</div><div class="sc-label">ຈຳນວນ Orders</div></div>
                <div class="summary-card blue"><div class="sc-icon blue"><i class="fas fa-calculator"></i></div>
                    <div class="sc-value">${formatNumber(s.subtotal_lak)} ₭</div><div class="sc-label">Subtotal</div></div>
                <div class="summary-card orange"><div class="sc-icon orange"><i class="fas fa-tags"></i></div>
                    <div class="sc-value">${formatNumber(s.discount_lak)} ₭</div><div class="sc-label">ສ່ວນຫຼຸດ (Discount)</div></div>
                <div class="summary-card purple"><div class="sc-icon purple"><i class="fas fa-percent"></i></div>
                    <div class="sc-value">${formatNumber(s.tax_lak)} ₭</div><div class="sc-label">ພາສີ (Tax)</div></div>
                <div class="summary-card red"><div class="sc-icon red"><i class="fas fa-clock"></i></div>
                    <div class="sc-value">${t1} - ${t2}</div><div class="sc-label">ຊ່ວງເວລາການຂາຍ</div></div>`;

                if (data.orders.length > 0) {
                    tab1Orders = data.orders;
                    tab1Page = 1;
                    renderTab1OrdersPage();
                } else {
                    tableEl.innerHTML =
                        '<div class="empty-state"><i class="fas fa-inbox"></i><p>ບໍ່ມີ Order ໃນຊ່ວງວັນທີ່ເລືອກ</p></div>';
                    document.getElementById('tab1PaginationWrap').style.display = 'none';
                }
                summaryEl.classList.remove('sr-fade-out');
                tableEl.classList.remove('sr-fade-out');
                summaryEl.classList.add('sr-fade-in');
                tableEl.classList.add('sr-fade-in');
                setTimeout(() => { summaryEl.classList.remove('sr-fade-in'); tableEl.classList.remove('sr-fade-in'); }, 250);
            });
    }

    // ===== Tab 1 Orders Pagination =====
    function renderTab1OrdersPage() {
        const tableEl = document.getElementById('tab1OrdersTable');
        const total = tab1Orders.length;
        const totalPages = Math.ceil(total / TAB1_PAGE_SIZE);
        if (tab1Page > totalPages) tab1Page = totalPages;
        const start = (tab1Page - 1) * TAB1_PAGE_SIZE;
        const end = Math.min(start + TAB1_PAGE_SIZE, total);
        const pageOrders = tab1Orders.slice(start, end);

        let h = `<table class="report-table"><thead><tr>
            <th>#</th><th>Order ID</th><th>Bill</th><th>ວັນທີ/ເວລາ</th><th>ປະເພດ</th>
            <th>ລູກຄ້າ</th><th>ຜູ້ຂາຍ</th><th>ສະຖານະ</th>
            <th style="text-align:center;">ສະກຸນເງິນ</th><th style="text-align:right;">ຈຳນວນເງິນ (ຕ່າງປະເທດ)</th><th style="text-align:right;">ເລດເງິນ</th>
            <th style="text-align:right;">ຍອດລວມ (LAK)</th></tr></thead><tbody>`;
        pageOrders.forEach((o, i) => {
            let dt = new Date(o.created_at);
            let timeStr = dt.toLocaleDateString('en-GB', { day: '2-digit', month: '2-digit' }) + ' ' + dt.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
            let tb = o.order_type === 'pos'
                ? '<span class="badge badge-pos"><i class="fas fa-cash-register"></i> POS</span>'
                : '<span class="badge badge-online"><i class="fas fa-globe"></i> ONLINE</span>';
            let sb = o.payment_status === 'paid'
                ? '<span class="badge badge-success">ຈ່າຍແລ້ວ</span>'
                : '<span class="badge badge-warning">ລໍຖ້າ</span>';
            let isForeign = o.currencys_id && o.currencys_id !== 'LAK';
            let currBadge = isForeign ? `<span class="badge badge-warning">${o.currencys_name || o.currencys_id}</span>` : `<span class="badge badge-success">LAK</span>`;
            let foreignAmt = isForeign ? formatNumber(o.total_amount) : '-';
            let rateAmt = isForeign ? formatNumber(o.currency_rate) : '-';

            h += `<tr><td>${start + i + 1}</td><td><strong>${o.OR_id}</strong></td><td>${o.bill_number || '-'}</td><td>${timeStr}</td>
                <td>${tb}</td><td>${o.customer_name || 'Walk-in'}</td><td>${o.user_name || '-'}</td>
                <td>${sb}</td>
                <td style="text-align:center;">${currBadge}</td>
                <td style="text-align:right;">${foreignAmt}</td>
                <td style="text-align:right;">${rateAmt}</td>
                <td style="text-align:right;font-weight:600;">${formatNumber(o.total_amount_lak)} ₭</td></tr>`;
        });
        h += '</tbody></table>';
        tableEl.innerHTML = h;

        // Pagination controls
        renderTab1Pagination(total, totalPages);
    }

    function renderTab1Pagination(total, totalPages) {
        const wrap = document.getElementById('tab1PaginationWrap');
        const info = document.getElementById('tab1PaginationInfo');
        const btns = document.getElementById('tab1PaginationBtns');
        if (totalPages <= 1) { wrap.style.display = 'none'; return; }
        wrap.style.display = 'flex';
        const from = (tab1Page - 1) * TAB1_PAGE_SIZE + 1;
        const to = Math.min(tab1Page * TAB1_PAGE_SIZE, total);
        info.textContent = `ສະແດງ ${from}-${to} ຈາກ ${total.toLocaleString()} ລາຍການ`;
        let html = `<button ${tab1Page === 1 ? 'disabled' : ''} onclick="goTab1Page(${tab1Page - 1})">&laquo;</button>`;
        let startP = Math.max(1, tab1Page - 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 === tab1Page ? 'active' : ''}" onclick="goTab1Page(${p})">${p}</button>`;
        }
        html += `<button ${tab1Page === totalPages ? 'disabled' : ''} onclick="goTab1Page(${tab1Page + 1})">&raquo;</button>`;
        btns.innerHTML = html;
    }

    function goTab1Page(page) {
        tab1Page = page;
        const tableEl = document.getElementById('tab1OrdersTable');
        tableEl.classList.add('sr-fade-out');
        setTimeout(() => {
            renderTab1OrdersPage();
            tableEl.classList.remove('sr-fade-out');
            tableEl.classList.add('sr-fade-in');
            setTimeout(() => tableEl.classList.remove('sr-fade-in'), 250);
            document.querySelector('#tab1 .card')?.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }, 150);
    }

    // ===== TAB 2: Load User Sales =====
    function loadUserSales() {
        const userId = document.getElementById('userSelect').value;
        if (!userId) {
            document.getElementById('userSummaryArea').classList.remove('show');
            document.getElementById('userEmptyState').style.display = '';
            return;
        }
        const from = document.getElementById('tab2From').value;
        const to = document.getElementById('tab2To').value;
        document.getElementById('userDateLabel').textContent = formatDateDisplay(from, to);

        const userSumCards = document.getElementById('userSummaryCards');
        const userOrdTable = document.getElementById('userOrdersTable');
        if (userSumCards) userSumCards.classList.add('sr-fade-out');
        if (userOrdTable) userOrdTable.classList.add('sr-fade-out');

        fetch('?ajax=user_sales&user_id=' + encodeURIComponent(userId) + '&' + buildDateParams('tab2'))
            .then(r => r.json())
            .then(data => {
                const s = data.summary;
                let t1 = s.first_order ? new Date(s.first_order).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' }) : '--:--';
                let t2 = s.last_order ? new Date(s.last_order).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' }) : '--:--';

                document.getElementById('userSummaryCards').innerHTML = `
                <div class="summary-card gold"><div class="sc-icon gold"><i class="fas fa-coins"></i></div>
                    <div class="sc-value">${formatNumber(s.total_sales_lak)} ₭</div><div class="sc-label">ຍອດຂາຍລວມ</div></div>
                <div class="summary-card green"><div class="sc-icon green"><i class="fas fa-receipt"></i></div>
                    <div class="sc-value">${formatNumber(s.total_orders)}</div><div class="sc-label">ຈຳນວນ Orders</div></div>
                <div class="summary-card blue"><div class="sc-icon blue"><i class="fas fa-clock"></i></div>
                    <div class="sc-value">${t1} - ${t2}</div><div class="sc-label">ເວລາເຮັດວຽກ (ເລີ່ມ - ສຸດທ້າຍ)</div></div>`;

                let h = '';
                if (data.orders.length > 0) {
                    h = `<table class="report-table"><thead><tr>
                    <th>#</th><th>Order ID</th><th>Bill</th><th>ວັນທີ/ເວລາ</th><th>ປະເພດ</th>
                    <th>ລູກຄ້າ</th><th>ສະຖານະ</th><th style="text-align:right;">ຍອດລວມ (LAK)</th>
                </tr></thead><tbody>`;
                    data.orders.forEach((o, i) => {
                        let dt = new Date(o.created_at);
                        let timeStr = dt.toLocaleDateString('en-GB', { day: '2-digit', month: '2-digit' }) + ' ' + dt.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
                        let tb = o.order_type === 'pos'
                            ? '<span class="badge badge-pos"><i class="fas fa-cash-register"></i> POS</span>'
                            : '<span class="badge badge-online"><i class="fas fa-globe"></i> ONLINE</span>';
                        let sb = o.payment_status === 'paid'
                            ? '<span class="badge badge-success">ຈ່າຍແລ້ວ</span>'
                            : '<span class="badge badge-warning">ລໍຖ້າ</span>';
                        h += `<tr><td>${i + 1}</td><td><strong>${o.OR_id}</strong></td><td>${o.bill_number || '-'}</td><td>${timeStr}</td>
                        <td>${tb}</td><td>${o.customer_name || 'Walk-in'}</td>
                        <td>${sb}</td><td style="text-align:right;font-weight:600;">${formatNumber(o.total_amount_lak)} ₭</td></tr>`;
                    });
                    h += '</tbody></table>';
                } else {
                    h = '<div class="empty-state"><i class="fas fa-inbox"></i><p>ບໍ່ມີ Order ໃນຊ່ວງວັນທີ່ເລືອກ</p></div>';
                }
                document.getElementById('userOrdersTable').innerHTML = h;
                document.getElementById('userSummaryArea').classList.add('show');
                document.getElementById('userEmptyState').style.display = 'none';

                if (userSumCards) { userSumCards.classList.remove('sr-fade-out'); userSumCards.classList.add('sr-fade-in'); }
                if (userOrdTable) { userOrdTable.classList.remove('sr-fade-out'); userOrdTable.classList.add('sr-fade-in'); }
                setTimeout(() => { if (userSumCards) userSumCards.classList.remove('sr-fade-in'); if (userOrdTable) userOrdTable.classList.remove('sr-fade-in'); }, 250);
            });
    }

    // ===== TAB 3: Load Top Products =====
    function loadTopProducts(range, btn) {
        document.querySelectorAll('#tab3 .filter-btn').forEach(b => b.classList.remove('active'));
        if (btn) btn.classList.add('active');
        const tpEl = document.getElementById('topProductsTable');
        tpEl.classList.add('sr-fade-out');
        fetch('?ajax=top_products&range=' + range)
            .then(r => r.json()).then(data => { renderTopProducts(data); tpEl.classList.remove('sr-fade-out'); tpEl.classList.add('sr-fade-in'); setTimeout(() => tpEl.classList.remove('sr-fade-in'), 250); });
    }

    function loadTopProductsCustom() {
        document.querySelectorAll('#tab3 .filter-btn').forEach(b => b.classList.remove('active'));
        const tpEl2 = document.getElementById('topProductsTable');
        tpEl2.classList.add('sr-fade-out');
        fetch('?ajax=top_products&range=custom&' + buildDateParams('tab3'))
            .then(r => r.json()).then(data => { renderTopProducts(data); tpEl2.classList.remove('sr-fade-out'); tpEl2.classList.add('sr-fade-in'); setTimeout(() => tpEl2.classList.remove('sr-fade-in'), 250); });
    }

    function renderTopProducts(data) {
        if (data.products.length === 0) {
            document.getElementById('topProductsTable').innerHTML =
                '<div class="empty-state"><i class="fas fa-inbox"></i><p>ບໍ່ມີຂໍ້ມູນ</p></div>';
            return;
        }
        let h = `<table class="report-table"><thead><tr>
        <th style="width:50px;">ອັນດັບ</th><th>ຊື່ສິນຄ້າ</th>
        <th style="text-align:right;">ຈຳນວນ</th><th style="text-align:right;">ຍອດລວມ</th>
    </tr></thead><tbody>`;
        data.products.forEach((p, i) => {
            let rc = i < 3 ? `rank-${i + 1}` : 'rank-other';
            h += `<tr><td><span class="rank-badge ${rc}">${i + 1}</span></td>
            <td>${p.product_name}</td>
            <td style="text-align:right;font-weight:600;">${formatNumber(p.total_qty)}</td>
            <td style="text-align:right;font-weight:600;">${formatNumber(p.total_revenue)}</td></tr>`;
        });
        h += '</tbody></table>';
        document.getElementById('topProductsTable').innerHTML = h;
    }

    // ===== TAB 4: Charts =====
    function initCharts() {
        const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
        const textColor = isDark ? 'rgba(255,255,255,0.7)' : '#5A6370';
        const gridColor = isDark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.06)';
        Chart.defaults.color = textColor;
        Chart.defaults.font.family = "'Noto Sans Lao', sans-serif";

        const dailyLabels = <?= json_encode(array_map(fn($d) => date('d/m', strtotime($d['sale_date'])), $dailySales)) ?>;
        const dailyValues = <?= json_encode(array_map(fn($d) => (float) $d['total_lak'], $dailySales)) ?>;
        const prodLabels = <?= json_encode(array_map(fn($p) => mb_strlen($p['product_name']) > 30 ? mb_substr($p['product_name'], 0, 30) . '...' : $p['product_name'], $topProducts)) ?>;
        const prodQty = <?= json_encode(array_map(fn($p) => (int) $p['total_qty'], $topProducts)) ?>;
        const userLabels = <?= json_encode(array_map(fn($u) => $u['user_name'] ?: 'ບໍ່ລະບຸ', $salesByUser)) ?>;
        const userValues = <?= json_encode(array_map(fn($u) => (float) $u['total_lak'], $salesByUser)) ?>;

        new Chart(document.getElementById('dailySalesChart'), {
            type: 'line', data: {
                labels: dailyLabels, datasets: [{
                    label: 'ຍອດຂາຍ (LAK)', data: dailyValues,
                    borderColor: '#c1992a', backgroundColor: 'rgba(193,153,42,0.15)', borderWidth: 2, fill: true, tension: 0.4,
                    pointRadius: 3, pointBackgroundColor: '#c1992a'
                }]
            },
            options: {
                responsive: true, plugins: { legend: { display: false } },
                scales: { x: { grid: { color: gridColor } }, y: { grid: { color: gridColor }, ticks: { callback: v => formatNumber(v) } } }
            }
        });

        const avg = dailyValues.length > 0 ? dailyValues.reduce((a, b) => a + b, 0) / dailyValues.length : 0;
        const bc = dailyValues.map(v => v >= avg ? 'rgba(40,167,69,0.7)' : 'rgba(220,53,69,0.7)');
        new Chart(document.getElementById('dailyCompareChart'), {
            type: 'bar', data: {
                labels: dailyLabels, datasets: [{
                    label: 'ຍອດຂາຍ (LAK)', data: dailyValues,
                    backgroundColor: bc, borderRadius: 6, borderSkipped: false
                }]
            },
            options: {
                responsive: true, plugins: { legend: { display: false } },
                scales: { x: { grid: { display: false } }, y: { grid: { color: gridColor }, ticks: { callback: v => formatNumber(v) } } }
            }
        });

        const pc = ['#c1992a', '#d4ac4a', '#FD7E14', '#28A745', '#17A2B8', '#6C7AE0', '#DC3545', '#FFC107', '#20c997', '#e83e8c'];
        new Chart(document.getElementById('topProductsChart'), {
            type: 'bar', data: {
                labels: prodLabels, datasets: [{
                    label: 'ຈຳນວນທີ່ຂາຍ', data: prodQty,
                    backgroundColor: pc, borderRadius: 6, borderSkipped: false
                }]
            },
            options: {
                indexAxis: 'y', responsive: true, plugins: { legend: { display: false } },
                scales: { x: { grid: { color: gridColor } }, y: { grid: { display: false } } }
            }
        });

        new Chart(document.getElementById('userSalesChart'), {
            type: 'doughnut', data: {
                labels: userLabels, datasets: [{
                    data: userValues,
                    backgroundColor: pc, borderWidth: 0, hoverOffset: 8
                }]
            },
            options: {
                responsive: true, cutout: '55%', plugins: {
                    legend: {
                        position: 'bottom',
                        labels: { padding: 15, usePointStyle: true, pointStyle: 'circle' }
                    }
                }
            }
        });
    }
</script>

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