<?php
// modules/dashboard.php
require_once '../includes/auth.php';
checkLogin();
require_once '../config/db.php';
require_once '../includes/functions.php';

$userId = $_SESSION['user_id'];
$isAdmin = isAdmin();
$msg = '';

// ==========================================
// API نمودار پیشرفته اصلی (AJAX) 
// ==========================================
if (isset($_GET['ajax_chart'])) {
    header('Content-Type: application/json');
    $filter_start = $_GET['start_date'] ?? '';
    $filter_end   = $_GET['end_date'] ?? '';

    $chartConditions = [];
    $chartParams = [];
    if (!$isAdmin) {
        $chartConditions[] = "t.user_id = :user_id";
        $chartParams[':user_id'] = $userId;
    }
    if (!empty($filter_start)) {
        $chartConditions[] = "t.date_shamsi >= :start";
        $chartParams[':start'] = $filter_start;
    } else {
        $chartConditions[] = "t.created_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)";
    }
    if (!empty($filter_end)) {
        $chartConditions[] = "t.date_shamsi <= :end";
        $chartParams[':end'] = $filter_end;
    }

    $chartWhereSQL = (!empty($chartConditions)) ? "WHERE " . implode(" AND ", $chartConditions) : "";
// مقداردهی اولیه برای جلوگیری از خطا در لود اول
$todayNewCount = 0;
$todayRenewCount = 0;

// محاسبه آمار فروش امروز برای باکس رادار
$stmtToday = $pdo->prepare("SELECT 
    SUM(CASE WHEN tx_type = 'new' THEN 1 ELSE 0 END) as new_count,
    SUM(CASE WHEN tx_type = 'recharge' THEN 1 ELSE 0 END) as renew_count
    FROM transactions 
    WHERE DATE(created_at) = CURDATE() " . (!$isAdmin ? "AND user_id = ?" : ""));

if (!$isAdmin) {
    $stmtToday->execute([$userId]);
} else {
    $stmtToday->execute();
}

$todayStats = $stmtToday->fetch();
$todayNewCount = $todayStats['new_count'] ?? 0;
$todayRenewCount = $todayStats['renew_count'] ?? 0;
    $sqlTrend = "SELECT date_shamsi, SUM(profit) as daily_profit, SUM(admin_profit) as daily_admin_profit, COUNT(id) as daily_count, SUM(volume) as daily_volume
                 FROM transactions t $chartWhereSQL GROUP BY date_shamsi ORDER BY date_shamsi ASC LIMIT 30";
    $stmtTrend = $pdo->prepare($sqlTrend);
    $stmtTrend->execute($chartParams);
    $trendRows = $stmtTrend->fetchAll();

    $trendLabels = []; $trendDataProfit = []; $trendDataCount = []; $trendDataVolume = [];
    foreach($trendRows as $row) {
        $trendLabels[] = $row['date_shamsi'];
        $trendDataProfit[] = $isAdmin ? $row['daily_admin_profit'] : $row['daily_profit'];
        $trendDataCount[] = $row['daily_count'];
        $trendDataVolume[] = $row['daily_volume'];
    }

    echo json_encode([
        'labels' => $trendLabels,
        'profit' => $trendDataProfit,
        'count'  => $trendDataCount,
        'volume' => $trendDataVolume
    ]);
    exit;
}

// ==========================================
// API نمودار جدید: مقایسه نمایندگان (AJAX)
// ==========================================
if (isset($_GET['ajax_op_chart'])) {
    header('Content-Type: application/json');
    $time_filter = $_GET['time_filter'] ?? 'today';
    $ops = isset($_GET['ops']) ? $_GET['ops'] : [];
    $sd = $_GET['start'] ?? '';
    $ed = $_GET['end'] ?? '';

    $where = ["1=1"];
    $params = [];

    if ($time_filter == 'today') { $where[] = "DATE(t.created_at) = CURDATE()"; }
    elseif ($time_filter == 'yesterday') { $where[] = "DATE(t.created_at) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)"; }
    elseif ($time_filter == 'week') { $where[] = "t.created_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)"; }
    elseif ($time_filter == 'month') { $where[] = "t.created_at >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)"; }
    elseif ($time_filter == 'custom') {
        if(!empty($sd)){ $where[] = "t.date_shamsi >= ?"; $params[] = $sd; }
        if(!empty($ed)){ $where[] = "t.date_shamsi <= ?"; $params[] = $ed; }
    }

    if (!empty($ops) && !in_array('all', $ops)) {
        $opsInt = array_map('intval', $ops);
        $inClause = implode(',', $opsInt);
        $where[] = "t.user_id IN ($inClause)";
    }

    $whereSql = implode(" AND ", $where);
    $sql = "SELECT COALESCE(u.fullname, u.username, 'نامشخص') as op_name, 
                   SUM(t.paid_amount) as total_sales, 
                   SUM(t.profit) as op_profit, 
                   SUM(t.admin_profit) as admin_profit, 
                   SUM(t.volume) as total_vol 
            FROM transactions t 
            LEFT JOIN users u ON t.user_id = u.id 
            WHERE $whereSql 
            GROUP BY t.user_id";
            
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $labels = []; $sales = []; $op_profit = []; $ad_profit = []; $vol = [];
    foreach($data as $row) {
        $labels[] = $row['op_name'];
        $sales[] = $row['total_sales'];
        $op_profit[] = $row['op_profit'];
        $ad_profit[] = $row['admin_profit'];
        $vol[] = $row['total_vol'];
    }

    echo json_encode([
        'labels' => $labels,
        'sales' => $sales,
        'op_profit' => $op_profit,
        'ad_profit' => $ad_profit,
        'vol' => $vol
    ]);
    exit;
}

// ==========================================
// API مانیتورینگ زنده (AJAX) - بدون رفرش صفحه
// ==========================================
if (isset($_GET['ajax_live'])) {
    header('Content-Type: application/json');
    $lastTime = $_GET['last_time'] ?? date('Y-m-d H:i:s', time() - 60);
    $lastTimeSafe = date('Y-m-d H:i:s', strtotime($lastTime));
    
    $liveStats = [];
    $liveRadar = []; 

    if ($isAdmin) {
        $liveStats['pending_count'] = $pdo->query("SELECT COUNT(*) FROM settlements WHERE status='pending'")->fetchColumn() ?: 0;
        $liveStats['pending_list'] = $pdo->query("SELECT s.amount, COALESCE(u.fullname, u.username, 'نامشخص') as op_name FROM settlements s LEFT JOIN users u ON s.user_id = u.id WHERE s.status='pending' ORDER BY s.id DESC LIMIT 4")->fetchAll(PDO::FETCH_ASSOC);
        
        $stockData = $pdo->query("SELECT plan_name, volume, SUM(CASE WHEN status='available' THEN 1 ELSE 0 END) as qty FROM inventory GROUP BY plan_name, volume HAVING qty < 5 ORDER BY qty ASC")->fetchAll(PDO::FETCH_ASSOC);
        $liveStats['stock_count'] = count($stockData);
        $liveStats['stock_list'] = array_slice($stockData, 0, 4);

        $liveStats['profit'] = $pdo->query("SELECT SUM(admin_profit) FROM transactions WHERE created_at >= CURDATE()")->fetchColumn() ?: 0;
        $liveStats['sales'] = $pdo->query("SELECT COUNT(id) FROM transactions WHERE created_at >= CURDATE()")->fetchColumn() ?: 0;
        $liveStats['volume'] = $pdo->query("SELECT SUM(volume) FROM transactions WHERE created_at >= CURDATE()")->fetchColumn() ?: 0;

        $liveRadar['totalWalletBalance'] = $pdo->query("SELECT SUM(wallet_balance) FROM users WHERE role='operator'")->fetchColumn() ?: 0;
        $liveRadar['totalCreditDebt'] = $pdo->query("SELECT SUM(credit_debt) FROM users WHERE role='operator'")->fetchColumn() ?: 0;
        $liveRadar['totalSystemMoney'] = $liveRadar['totalWalletBalance'] + $liveRadar['totalCreditDebt'];
        $liveRadar['debtPercentage'] = ($liveRadar['totalSystemMoney'] > 0) ? round(($liveRadar['totalCreditDebt'] / $liveRadar['totalSystemMoney']) * 100) : 0;
        $liveRadar['walletPercentage'] = ($liveRadar['totalSystemMoney'] > 0) ? 100 - $liveRadar['debtPercentage'] : 0;
        
        $liveRadar['totalGBSold'] = $pdo->query("SELECT SUM(volume) FROM transactions")->fetchColumn() ?: 0;
        $totalAdminCost = $pdo->query("SELECT SUM(paid_amount - profit - admin_profit) FROM transactions")->fetchColumn() ?: 0;
        $totalProviderSettled = $pdo->query("SELECT SUM(paid_amount) FROM provider_settlements")->fetchColumn() ?: 0;
        $liveRadar['providerDebt'] = max(0, $totalAdminCost - $totalProviderSettled);
        $liveRadar['radarPendingAmount'] = $pdo->query("SELECT SUM(amount) FROM settlements WHERE status='pending'")->fetchColumn() ?: 0;

    } else {
        $stmtProf = $pdo->prepare("SELECT SUM(profit) FROM transactions WHERE user_id=? AND created_at >= CURDATE()");
        $stmtProf->execute([$userId]); $liveStats['profit'] = $stmtProf->fetchColumn() ?: 0;
        
        $stmtSales = $pdo->prepare("SELECT COUNT(id) FROM transactions WHERE user_id=? AND created_at >= CURDATE()");
        $stmtSales->execute([$userId]); $liveStats['sales'] = $stmtSales->fetchColumn() ?: 0;
        
        $stmtVol = $pdo->prepare("SELECT SUM(volume) FROM transactions WHERE user_id=? AND created_at >= CURDATE()");
        $stmtVol->execute([$userId]); $liveStats['volume'] = $stmtVol->fetchColumn() ?: 0;

        $stmtRadar = $pdo->prepare("SELECT SUM(paid_amount) as total_spent, COUNT(id) as total_buys FROM transactions WHERE user_id = ?");
        $stmtRadar->execute([$userId]);
        $radarStats = $stmtRadar->fetch();
        $liveRadar['radarTotalSpent'] = $radarStats['total_spent'] ?: 0;
        $liveRadar['radarTotalBuys'] = $radarStats['total_buys'] ?: 0;

        $stmtTodaySales = $pdo->prepare("SELECT SUM(CASE WHEN type='new' THEN 1 ELSE 0 END) as new_count, SUM(CASE WHEN type='recharge' THEN 1 ELSE 0 END) as renew_count FROM transactions WHERE user_id = ? AND created_at >= CURDATE()");
        $stmtTodaySales->execute([$userId]);
        $todaySales = $stmtTodaySales->fetch();
        $liveRadar['todayNewCount'] = $todaySales['new_count'] ?: 0;
        $liveRadar['todayRenewCount'] = $todaySales['renew_count'] ?: 0;
    }

    $opFilter = $isAdmin ? "" : "AND user_id = $userId";
    $opFilterS = $isAdmin ? "" : "AND s.user_id = $userId";
    $opFilterW = $isAdmin ? "" : "AND w.user_id = $userId";

    $stmtActs = $pdo->prepare("
        SELECT * FROM (
            (SELECT 'sale' as act_type, t.id as ref_id, t.created_at, CAST(t.plan AS CHAR) as plan, t.volume, CAST(u.username AS CHAR) as username, CAST(u.fullname AS CHAR) as fullname, t.paid_amount as amount, CAST(NULL AS CHAR) as extra, t.profit as op_profit, t.admin_profit as ad_profit 
             FROM transactions t LEFT JOIN users u ON t.user_id = u.id WHERE t.created_at > ? $opFilter)
            UNION ALL
            (SELECT 'receipt' as act_type, s.id as ref_id, s.created_at, CAST(NULL AS CHAR) as plan, 0 as volume, CAST(u.username AS CHAR) as username, CAST(u.fullname AS CHAR) as fullname, s.amount as amount, CAST(NULL AS CHAR) as extra, 0 as op_profit, 0 as ad_profit 
             FROM settlements s LEFT JOIN users u ON s.user_id = u.id WHERE s.status='pending' AND s.created_at > ? $opFilterS)
            UNION ALL
            (SELECT 'wallet' as act_type, w.id as ref_id, w.created_at, CAST(w.type AS CHAR) as plan, 0 as volume, CAST(u.username AS CHAR) as username, CAST(u.fullname AS CHAR) as fullname, w.amount as amount, CAST(w.description AS CHAR) as extra, 0 as op_profit, 0 as ad_profit 
             FROM wallet_logs w LEFT JOIN users u ON w.user_id = u.id WHERE w.created_at > ? $opFilterW)
        ) as combined
        ORDER BY created_at ASC
    ");
    $stmtActs->execute([$lastTimeSafe, $lastTimeSafe, $lastTimeSafe]);
    $newActivity = $stmtActs->fetchAll(PDO::FETCH_ASSOC);

    foreach($newActivity as &$act) {
        $ts = strtotime($act['created_at']);
        $act['time_shamsi'] = date('H:i', $ts);
        $act['op_name'] = !empty($act['fullname']) ? $act['fullname'] : (!empty($act['username']) ? $act['username'] : 'سیستم');
        $act['uid'] = $act['act_type'] . '_' . $act['ref_id'];
    }

    echo json_encode([
        'stats' => $liveStats,
        'radar' => $liveRadar,
        'activities' => $newActivity,
        'current_time' => date('Y-m-d H:i:s')
    ]);
    exit;
}

// ==========================================
// ارتقای دیتابیس
// ==========================================
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `global_settings` (
      `setting_key` varchar(50) NOT NULL, `setting_value` text DEFAULT NULL, PRIMARY KEY (`setting_key`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
    $pdo->exec("INSERT IGNORE INTO `global_settings` (`setting_key`, `setting_value`) VALUES ('dashboard_announcement', '')");
    $pdo->exec("CREATE TABLE IF NOT EXISTS `provider_settlements` (
      `id` int(11) NOT NULL AUTO_INCREMENT, `gb_amount` int(11) NOT NULL, `paid_amount` bigint(20) NOT NULL, `description` varchar(255) DEFAULT NULL, `created_at` timestamp NOT NULL DEFAULT current_timestamp(), PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;");
} catch (PDOException $e) {}

if ($isAdmin && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_announcement') {
    $announcement = trim($_POST['announcement_text']);
    $pdo->prepare("UPDATE global_settings SET setting_value = ? WHERE setting_key = 'dashboard_announcement'")->execute([$announcement]);
    $msg = "اطلاعیه سراسری بروزرسانی شد.";
}

$globalAnnouncement = $pdo->query("SELECT setting_value FROM global_settings WHERE setting_key = 'dashboard_announcement'")->fetchColumn() ?: '';

$stmtUser = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmtUser->execute([$userId]);
$currentUser = $stmtUser->fetch();
$displayName = !empty($currentUser['fullname']) ? $currentUser['fullname'] : $currentUser['username'];

// ==========================================
// محاسبات نمودار پیشرفته داشبورد (رندر اولیه)
// ==========================================
$filter_start = $_GET['start_date'] ?? '';
$filter_end   = $_GET['end_date'] ?? '';

$chartConditions = [];
$chartParams = [];
if (!$isAdmin) {
    $chartConditions[] = "t.user_id = :user_id";
    $chartParams[':user_id'] = $userId;
}
if (!empty($filter_start)) {
    $chartConditions[] = "t.date_shamsi >= :start";
    $chartParams[':start'] = $filter_start;
} else {
    $chartConditions[] = "t.created_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)";
}
if (!empty($filter_end)) {
    $chartConditions[] = "t.date_shamsi <= :end";
    $chartParams[':end'] = $filter_end;
}

$chartWhereSQL = (!empty($chartConditions)) ? "WHERE " . implode(" AND ", $chartConditions) : "";

$sqlTrend = "SELECT date_shamsi, SUM(profit) as daily_profit, SUM(admin_profit) as daily_admin_profit, COUNT(id) as daily_count, SUM(volume) as daily_volume
             FROM transactions t $chartWhereSQL GROUP BY date_shamsi ORDER BY date_shamsi ASC LIMIT 30";
$stmtTrend = $pdo->prepare($sqlTrend);
$stmtTrend->execute($chartParams);
$trendRows = $stmtTrend->fetchAll();

$trendLabels = []; $trendDataProfit = []; $trendDataCount = []; $trendDataVolume = [];
foreach($trendRows as $row) {
    $trendLabels[] = $row['date_shamsi'];
    $trendDataProfit[] = $isAdmin ? $row['daily_admin_profit'] : $row['daily_profit'];
    $trendDataCount[] = $row['daily_count'];
    $trendDataVolume[] = $row['daily_volume'];
}

// ==========================================
// پردازش داده‌های اولیه داشبورد (رندر نخست)
// ==========================================
if ($isAdmin) {
    $pendingReceipts = $pdo->query("SELECT COUNT(*) FROM settlements WHERE status='pending'")->fetchColumn() ?: 0;
    $initPend = $pdo->query("SELECT s.amount, COALESCE(u.fullname, u.username, 'نامشخص') as op_name FROM settlements s LEFT JOIN users u ON s.user_id = u.id WHERE s.status='pending' ORDER BY s.id DESC LIMIT 4")->fetchAll(PDO::FETCH_ASSOC);

    $initStockRaw = $pdo->query("SELECT plan_name, volume, SUM(CASE WHEN status='available' THEN 1 ELSE 0 END) as qty FROM inventory GROUP BY plan_name, volume HAVING qty < 5 ORDER BY qty ASC")->fetchAll(PDO::FETCH_ASSOC);
    $lowStockCount = count($initStockRaw);
    $initStock = array_slice($initStockRaw, 0, 4);

    $todayProfit = $pdo->query("SELECT SUM(admin_profit) FROM transactions WHERE created_at >= CURDATE()")->fetchColumn() ?: 0;
    $todaySalesData = $pdo->query("SELECT COUNT(id) as cnt, SUM(volume) as vol FROM transactions WHERE created_at >= CURDATE()")->fetch();
    $todaySalesCount = $todaySalesData['cnt'] ?: 0;
    $todayVolume = $todaySalesData['vol'] ?: 0;
    
    $totalWalletBalance = $pdo->query("SELECT SUM(wallet_balance) FROM users WHERE role='operator'")->fetchColumn() ?: 0;
    $totalCreditDebt = $pdo->query("SELECT SUM(credit_debt) FROM users WHERE role='operator'")->fetchColumn() ?: 0;
    $totalSystemMoney = $totalWalletBalance + $totalCreditDebt;
    $debtPercentage = ($totalSystemMoney > 0) ? round(($totalCreditDebt / $totalSystemMoney) * 100) : 0;
    $walletPercentage = ($totalSystemMoney > 0) ? 100 - $debtPercentage : 0;
    
    $radarTotalInventory = $pdo->query("SELECT SUM(available_count) FROM (SELECT SUM(CASE WHEN status='available' THEN 1 ELSE 0 END) as available_count FROM inventory GROUP BY plan_name, volume) as t")->fetchColumn() ?: 0;
    $radarPendingAmount = $pdo->query("SELECT SUM(amount) FROM settlements WHERE status='pending'")->fetchColumn() ?: 0;
    $totalGBSold = $pdo->query("SELECT SUM(volume) FROM transactions")->fetchColumn() ?: 0;
    $totalAdminCost = $pdo->query("SELECT SUM(paid_amount - profit - admin_profit) FROM transactions")->fetchColumn() ?: 0;
    $totalProviderSettled = $pdo->query("SELECT SUM(paid_amount) FROM provider_settlements")->fetchColumn() ?: 0;
    $providerDebt = max(0, $totalAdminCost - $totalProviderSettled);

    $recentActivity = $pdo->query("
        (SELECT 'sale' as act_type, t.id as ref_id, t.created_at, CAST(t.plan AS CHAR) as plan, t.volume, CAST(u.username AS CHAR) as username, CAST(u.fullname AS CHAR) as fullname, t.paid_amount as amount, CAST(NULL AS CHAR) as extra, t.profit as op_profit, t.admin_profit as ad_profit 
         FROM transactions t LEFT JOIN users u ON t.user_id = u.id ORDER BY t.id DESC LIMIT 15)
        UNION ALL
        (SELECT 'receipt' as act_type, s.id as ref_id, s.created_at, CAST(NULL AS CHAR) as plan, 0 as volume, CAST(u.username AS CHAR) as username, CAST(u.fullname AS CHAR) as fullname, s.amount as amount, CAST(NULL AS CHAR) as extra, 0 as op_profit, 0 as ad_profit 
         FROM settlements s LEFT JOIN users u ON s.user_id = u.id WHERE s.status='pending' ORDER BY s.id DESC LIMIT 10)
        UNION ALL
        (SELECT 'wallet' as act_type, w.id as ref_id, w.created_at, CAST(w.type AS CHAR) as plan, 0 as volume, CAST(u.username AS CHAR) as username, CAST(u.fullname AS CHAR) as fullname, w.amount as amount, CAST(w.description AS CHAR) as extra, 0 as op_profit, 0 as ad_profit 
         FROM wallet_logs w LEFT JOIN users u ON w.user_id = u.id ORDER BY w.id DESC LIMIT 10)
        ORDER BY created_at DESC LIMIT 30
    ")->fetchAll();

} else {
    $walletBalance = $currentUser['wallet_balance'] ?? 0;
    $creditDebt = $currentUser['credit_debt'] ?? 0;
    
    $activeSubsCount = $pdo->prepare("SELECT COUNT(*) FROM inventory WHERE operator_id = ? AND status='sold'");
    $activeSubsCount->execute([$userId]);
    $activeSubsCount = $activeSubsCount->fetchColumn();
    
    $stmtTodaySales = $pdo->prepare("SELECT SUM(profit) as total_profit, SUM(volume) as vol, COUNT(id) as cnt FROM transactions WHERE user_id = ? AND created_at >= CURDATE()");
    $stmtTodaySales->execute([$userId]);
    $todaySales = $stmtTodaySales->fetch();
    $todayProfit = $todaySales['total_profit'] ?: 0;
    $todaySalesCount = $todaySales['cnt'] ?: 0;
    $todayVolume = $todaySales['vol'] ?: 0;

    $radarTotalSpentStmt = $pdo->prepare("SELECT SUM(paid_amount) as total_spent, COUNT(id) as total_buys FROM transactions WHERE user_id = ?");
    $radarTotalSpentStmt->execute([$userId]);
    $radarStats = $radarTotalSpentStmt->fetch();
    $radarTotalSpent = $radarStats['total_spent'] ?: 0;
    $radarTotalBuys = $radarStats['total_buys'] ?: 0;

    $isBonusActive = $pdo->query("SELECT setting_value FROM global_settings WHERE setting_key = 'bonus_system_status'")->fetchColumn() === '1';

    $isBonusActive = $pdo->query("SELECT setting_value FROM global_settings WHERE setting_key = 'bonus_system_status'")->fetchColumn() === '1';

    // --- شرط سلب بونوس از نماینده دارای قیمت ویژه (نسخه ۱۰۰٪ ایمن) ---
    if ($isBonusActive) {
        $stmtSpecial = $pdo->prepare("SELECT allow_bonus FROM user_prices WHERE user_id = ?");
        $stmtSpecial->execute([$userId]);
        $userBonusPermissions = $stmtSpecial->fetchAll(PDO::FETCH_COLUMN);

        // اگر نماینده قیمت اختصاصی دارد، بررسی می‌کنیم آیا حداقل در یکی از آن‌ها تیک بونوس زده شده یا خیر
        if (count($userBonusPermissions) > 0) {
            $hasBonusPermission = false;
            foreach ($userBonusPermissions as $ab) {
                if ($ab == 1) { $hasBonusPermission = true; break; }
            }
            if (!$hasBonusPermission) {
                $isBonusActive = false; 
            }
        }
    }

    $nextBonusTier = null;
    $bonusProgress = 0;
    if ($isBonusActive) {
        $stmtBonus = $pdo->prepare("SELECT tier_name, min_amount, bonus_percent FROM bonus_settings WHERE is_active = 1 AND min_amount > ? ORDER BY min_amount ASC LIMIT 1");
        $stmtBonus->execute([$walletBalance]);
        $nextBonusTier = $stmtBonus->fetch();
        if ($nextBonusTier) {
            $bonusProgress = ($walletBalance / $nextBonusTier['min_amount']) * 100;
        }
    }
    
    $opFilter = "AND user_id = $userId";
    $opFilterS = "AND s.user_id = $userId";
    $opFilterW = "AND w.user_id = $userId";
    $recentActivity = $pdo->query("
        (SELECT 'sale' as act_type, t.id as ref_id, t.created_at, CAST(t.plan AS CHAR) as plan, t.volume, CAST(u.username AS CHAR) as username, CAST(u.fullname AS CHAR) as fullname, t.paid_amount as amount, CAST(NULL AS CHAR) as extra, t.profit as op_profit, t.admin_profit as ad_profit 
         FROM transactions t LEFT JOIN users u ON t.user_id = u.id WHERE 1=1 $opFilter ORDER BY t.id DESC LIMIT 15)
        UNION ALL
        (SELECT 'receipt' as act_type, s.id as ref_id, s.created_at, CAST(NULL AS CHAR) as plan, 0 as volume, CAST(u.username AS CHAR) as username, CAST(u.fullname AS CHAR) as fullname, s.amount as amount, CAST(NULL AS CHAR) as extra, 0 as op_profit, 0 as ad_profit 
         FROM settlements s LEFT JOIN users u ON s.user_id = u.id WHERE s.status='pending' $opFilterS ORDER BY s.id DESC LIMIT 5)
        UNION ALL
        (SELECT 'wallet' as act_type, w.id as ref_id, w.created_at, CAST(w.type AS CHAR) as plan, 0 as volume, CAST(u.username AS CHAR) as username, CAST(u.fullname AS CHAR) as fullname, w.amount as amount, CAST(w.description AS CHAR) as extra, 0 as op_profit, 0 as ad_profit 
         FROM wallet_logs w LEFT JOIN users u ON w.user_id = u.id WHERE 1=1 $opFilterW ORDER BY w.id DESC LIMIT 5)
        ORDER BY created_at DESC LIMIT 30
    ")->fetchAll();
}

$initLastTime = date('Y-m-d H:i:s');
require_once '../includes/header.php';
?>

<link rel="stylesheet" href="https://unpkg.com/persian-datepicker@1.2.0/dist/css/persian-datepicker.min.css"/>

<style>
    /* انیمیشن رکوردهای جدید */
    @keyframes superAlertGlow {
        0% { box-shadow: 0 0 0 0px rgba(16, 185, 129, 0.9); background-color: rgba(16, 185, 129, 0.2); border-color: #10b981; transform: scale(0.98); }
        20% { box-shadow: 0 0 20px 5px rgba(16, 185, 129, 0.6); background-color: rgba(16, 185, 129, 0.1); border-color: #10b981; transform: scale(1.02); }
        100% { box-shadow: 0 0 0 0px rgba(16, 185, 129, 0); background-color: transparent; border-color: rgba(51, 65, 85, 0.5); transform: scale(1); }
    }
    .super-new-item { animation: superAlertGlow 6s ease-out forwards; border: 1px solid transparent; }
    
    @keyframes superEmergencyGlow {
        0% { box-shadow: 0 0 0 0px rgba(225, 29, 72, 0.9); background-color: rgba(225, 29, 72, 0.2); border-color: #e11d48; transform: scale(0.98); }
        20% { box-shadow: 0 0 30px 10px rgba(225, 29, 72, 0.6); background-color: rgba(225, 29, 72, 0.15); border-color: #e11d48; transform: scale(1.02); }
        100% { box-shadow: 0 0 0 0px rgba(225, 29, 72, 0); background-color: rgba(225, 29, 72, 0.05); border-color: rgba(225, 29, 72, 0.3); transform: scale(1); }
    }
    .super-emergency-item { animation: superEmergencyGlow 6s infinite alternate; border: 1px solid #e11d48 !important; }
    
    .datepicker-plot-area { font-family: 'Vazirmatn', sans-serif !important; border-radius: 12px; border: 1px solid #e2e8f0; box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1); }
    html.dark .datepicker-plot-area { background-color: #1e293b; border-color: #334155; color: #f8fafc; }
    html.dark .datepicker-plot-area .datepicker-day-view .table-days td span { color: #cbd5e1; }
    html.dark .datepicker-plot-area .datepicker-day-view .table-days td span:hover { background-color: #334155; }
    html.dark .datepicker-plot-area .datepicker-day-view .table-days td.selected span { background-color: #3b82f6; color: white; }
    .custom-scrollbar::-webkit-scrollbar { height: 6px; width: 6px; }
    .custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
    .custom-scrollbar::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 10px; }
    html.dark .custom-scrollbar::-webkit-scrollbar-thumb { background: #475569; }
</style>

<?php if($msg): ?><div class="bg-green-100 border border-green-400 text-green-800 px-5 py-4 rounded-xl mb-6 font-bold shadow-sm">✅ <?php echo $msg; ?></div><?php endif; ?>

<?php if ($isAdmin): ?>
    <div class="flex flex-col md:flex-row justify-between items-center bg-white dark:bg-slate-800 rounded-2xl p-4 shadow-sm border border-gray-100 dark:border-slate-700 mb-6 gap-4">
        <div class="flex items-center gap-3 w-full md:w-auto">
             <div class="w-10 h-10 bg-blue-100 dark:bg-blue-900/50 text-blue-600 dark:text-blue-400 rounded-full flex items-center justify-center text-xl shrink-0">👨‍💻</div>
             <div class="flex-1">
                 <h1 class="text-sm font-black text-gray-800 dark:text-white mb-0.5">سلام <?php echo htmlspecialchars($displayName); ?></h1>
                 <div class="flex items-center gap-1.5">
                     <span class="relative flex h-2 w-2"><span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-red-400 opacity-75"></span><span class="relative inline-flex rounded-full h-2 w-2 bg-red-500"></span></span>
                     <span class="text-[10px] text-gray-500 dark:text-gray-400 font-bold tracking-widest uppercase">اتاق فرمان و مانیتورینگ زنده</span>
                 </div>
             </div>
        </div>
        <form method="POST" class="flex w-full md:w-auto items-center gap-2">
            <input type="hidden" name="action" value="save_announcement">
            <input type="text" name="announcement_text" class="w-full md:w-96 bg-gray-50 dark:bg-slate-700 border border-gray-200 dark:border-slate-600 outline-none focus:border-amber-500 text-xs py-2.5 px-3 rounded-xl dark:text-white transition" placeholder="ثبت اطلاعیه سراسری سیستم..." value="<?php echo htmlspecialchars($globalAnnouncement); ?>">
            <button type="submit" class="bg-amber-500 hover:bg-amber-600 text-white font-bold py-2.5 px-4 rounded-xl text-xs transition shadow-sm shrink-0">ثبت اطلاعیه</button>
        </form>
    </div>
<?php else: ?>
    <?php if(!empty($globalAnnouncement)): ?>
    <div class="bg-gradient-to-r from-amber-500 to-orange-600 rounded-2xl p-4 mb-6 shadow-md flex items-start gap-4 text-white relative overflow-hidden">
        <div class="absolute -right-4 -top-4 opacity-20 text-6xl">📢</div>
        <div class="text-3xl relative z-10 hidden sm:block">📢</div>
        <div class="relative z-10 w-full">
            <div class="text-xs font-black text-amber-100 uppercase tracking-wider mb-1">اطلاعیه سراسری</div>
            <div class="text-sm font-bold leading-relaxed whitespace-pre-line"><?php echo nl2br($globalAnnouncement); ?></div>
        </div>
    </div>
    <?php endif; ?>
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
        <div class="lg:col-span-2 bg-gradient-to-l from-blue-700 to-indigo-800 rounded-3xl p-8 text-white relative overflow-hidden shadow-lg h-full flex flex-col justify-center">
            <div class="absolute -right-10 -bottom-10 opacity-10 text-9xl">🚀</div>
            <div class="relative z-10">
                <h1 class="text-3xl font-black mb-2">سلام <?php echo htmlspecialchars($displayName); ?>، خوش آمدید!</h1>
                <p class="text-indigo-200 font-bold text-sm">از طریق این داشبورد می‌توانید به ابزارهای شبکه دسترسی سریع داشته باشید.</p>
            </div>
        </div>
        <?php if($isBonusActive && $nextBonusTier): ?>
        <div class="lg:col-span-1 w-full bg-white dark:bg-slate-800 rounded-3xl p-6 shadow-sm border border-gray-100 dark:border-slate-700 border-t-8 border-t-fuchsia-500 flex flex-col justify-center relative overflow-hidden">
            <h3 class="text-sm font-black text-gray-800 dark:text-white mb-2 flex items-center gap-2">
                <span class="text-xl">🎁</span> جایزه بعدی شما!
            </h3>
            <p class="text-[11px] text-gray-500 dark:text-gray-400 font-bold mb-4 leading-relaxed">
                برای رسیدن به سطح <span class="text-fuchsia-600 dark:text-fuchsia-400 font-black">«<?php echo $nextBonusTier['tier_name']; ?>»</span> و دریافت <span class="font-black bg-fuchsia-100 dark:bg-fuchsia-900/30 text-fuchsia-700 dark:text-fuchsia-400 px-1 rounded"><?php echo $nextBonusTier['bonus_percent']; ?>٪</span> اعتبار هدیه، موجودی خود را افزایش دهید.
            </p>
            <div class="relative pt-1">
                <div class="flex justify-between items-end mb-1">
                    <span class="text-[10px] font-bold text-fuchsia-600 dark:text-fuchsia-400">پیشرفت: <?php echo round($bonusProgress); ?>٪</span>
                    <span class="text-[10px] font-mono text-gray-400" dir="ltr"><?php echo number_format($walletBalance); ?> / <?php echo number_format($nextBonusTier['min_amount']); ?></span>
                </div>
                <div class="overflow-hidden h-2.5 text-xs flex rounded-full bg-fuchsia-100 dark:bg-slate-700">
                    <div style="width: <?php echo $bonusProgress; ?>%" class="shadow-none flex flex-col text-center whitespace-nowrap text-white justify-center bg-fuchsia-500 transition-all duration-1000"></div>
                </div>
            </div>
            <a href="wallet/wallet.php" class="mt-4 text-[11px] font-bold text-center bg-gray-50 dark:bg-slate-700 text-gray-600 dark:text-gray-300 py-2 rounded-xl hover:bg-gray-100 dark:hover:bg-slate-600 transition">شارژ کیف پول ←</a>
        </div>
        <?php endif; ?>
    </div>
<?php endif; ?>

<div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4 mb-8">
    <?php if($isAdmin): ?>
        <a href="wallet/wallet.php" class="block bg-white dark:bg-slate-800 p-4 rounded-2xl shadow-sm border border-gray-100 dark:border-slate-700 border-t-4 border-t-amber-500 relative transition-all duration-300 hover:shadow-md hover:-translate-y-1 min-h-[120px] flex flex-col">
            <div class="flex justify-between items-center mb-1.5 shrink-0">
                <span class="text-[10px] font-bold text-gray-500 dark:text-gray-400">فیش‌های منتظر تایید</span>
                <span id="live_pending" data-val="<?php echo $pendingReceipts; ?>" class="text-xl font-black text-amber-500 transition-all duration-300"><?php echo $pendingReceipts; ?></span>
            </div>
            <div id="live_pending_list" class="flex-1 overflow-y-auto custom-scrollbar text-[9px] text-gray-600 dark:text-gray-400 space-y-1">
                <?php 
                if(empty($initPend)) echo '<span>موردی نیست</span>';
                foreach($initPend as $p): ?>
                    <div class="flex justify-between border-b border-gray-50 dark:border-slate-700/50 pb-0.5"><span class="truncate w-16"><?php echo htmlspecialchars($p['op_name']); ?></span><span class="font-mono text-amber-600 dark:text-amber-400" dir="ltr"><?php echo number_format($p['amount']); ?></span></div>
                <?php endforeach; ?>
            </div>
        </a>
        <a href="inventory/inventory.php" class="block bg-white dark:bg-slate-800 p-4 rounded-2xl shadow-sm border border-gray-100 dark:border-slate-700 border-t-4 border-t-rose-500 relative transition-all duration-300 hover:shadow-md hover:-translate-y-1 min-h-[120px] flex flex-col">
            <div class="flex justify-between items-center mb-1.5 shrink-0">
                <span class="text-[10px] font-bold text-gray-500 dark:text-gray-400">هشدار موجودی انبار</span>
                <span id="live_stock" data-val="<?php echo $lowStockCount; ?>" class="text-xl font-black text-rose-500 transition-all duration-300"><?php echo $lowStockCount; ?></span>
            </div>
            <div id="live_stock_list" class="flex-1 overflow-y-auto custom-scrollbar text-[9px] text-gray-600 dark:text-gray-400 space-y-1">
                <?php 
                if(empty($initStock)) echo '<span>موجودی تکمیل است</span>';
                foreach($initStock as $s): ?>
                    <div class="flex justify-between border-b border-gray-50 dark:border-slate-700/50 pb-0.5"><span class="truncate w-16"><?php echo htmlspecialchars($s['plan_name']); ?> (<?php echo $s['volume']; ?>G)</span><span class="font-mono font-bold text-rose-600 dark:text-rose-400"><?php echo $s['qty']; ?> عدد</span></div>
                <?php endforeach; ?>
            </div>
        </a>
    <?php else: ?>
        <div class="bg-white dark:bg-slate-800 p-5 rounded-2xl shadow-sm border border-gray-100 dark:border-slate-700 border-t-4 border-t-blue-500 relative overflow-hidden transition-all duration-300 min-h-[120px] flex flex-col justify-center">
            <span class="block text-[10px] font-bold text-gray-500 dark:text-gray-400 mb-1">موجودی کیف پول</span>
            <span class="text-xl font-black text-blue-600 dark:text-blue-400" dir="ltr"><?php echo number_format($walletBalance); ?> <span class="text-[10px]">T</span></span>
        </div>
        <div class="bg-white dark:bg-slate-800 p-5 rounded-2xl shadow-sm border border-gray-100 dark:border-slate-700 border-t-4 border-t-rose-500 relative overflow-hidden transition-all duration-300 min-h-[120px] flex flex-col justify-center">
            <span class="block text-[10px] font-bold text-gray-500 dark:text-gray-400 mb-1">بدهی اعتباری</span>
            <span class="text-xl font-black text-rose-600 dark:text-rose-400" dir="ltr"><?php echo number_format($creditDebt); ?> <span class="text-[10px]">T</span></span>
        </div>
    <?php endif; ?>

    <div class="bg-white dark:bg-slate-800 p-5 rounded-2xl shadow-sm border border-gray-100 dark:border-slate-700 border-t-4 border-t-emerald-500 relative overflow-hidden transition-all duration-300 min-h-[120px] flex flex-col justify-center">
        <span class="block text-[10px] font-bold text-gray-500 dark:text-gray-400 mb-1">سود خالص امروز</span>
        <span id="live_profit" data-val="<?php echo $todayProfit; ?>" class="text-xl font-black text-emerald-600 dark:text-emerald-400 transition-all duration-300" dir="ltr"><?php echo number_format($todayProfit); ?> <span class="text-[10px]">T</span></span>
    </div>
    <div class="bg-white dark:bg-slate-800 p-5 rounded-2xl shadow-sm border border-gray-100 dark:border-slate-700 border-t-4 border-t-cyan-500 relative overflow-hidden transition-all duration-300 min-h-[120px] flex flex-col justify-center">
        <span class="block text-[10px] font-bold text-gray-500 dark:text-gray-400 mb-1">تعداد فروش امروز</span>
        <span id="live_sales" data-val="<?php echo $todaySalesCount; ?>" class="text-2xl font-black text-cyan-600 dark:text-cyan-400 transition-all duration-300"><?php echo $todaySalesCount; ?></span>
    </div>
    <div class="bg-white dark:bg-slate-800 p-5 rounded-2xl shadow-sm border border-gray-100 dark:border-slate-700 border-t-4 border-t-fuchsia-500 relative overflow-hidden transition-all duration-300 min-h-[120px] flex flex-col justify-center">
        <span class="block text-[10px] font-bold text-gray-500 dark:text-gray-400 mb-1">حجم فروش امروز</span>
        <span id="live_volume" data-val="<?php echo $todayVolume; ?>" class="text-2xl font-black text-fuchsia-600 dark:text-fuchsia-400 transition-all duration-300"><?php echo $todayVolume; ?> <span class="text-[10px] font-normal text-gray-400">GB</span></span>
    </div>
</div>

<div class="grid grid-cols-1 lg:grid-cols-12 gap-8 mb-8">
    
    <div class="lg:col-span-5 bg-gray-900 dark:bg-black rounded-3xl shadow-xl border border-gray-800 p-6 flex flex-col h-full relative overflow-hidden">
        <div class="absolute -right-4 -top-4 opacity-5 text-7xl">📡</div>
        <h2 class="text-lg font-black text-white flex items-center gap-2 mb-2 relative z-10">
            <span class="flex h-2.5 w-2.5 relative">
              <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-red-400 opacity-75"></span>
              <span class="relative inline-flex rounded-full h-2.5 w-2.5 bg-red-500"></span>
            </span>
            تایم‌لاین زنده شبکه
        </h2>
        <p class="text-[11px] text-gray-400 mb-6 font-bold border-b border-gray-800 pb-3 relative z-10">موارد جدید با افکت نوری ظاهر می‌شوند.</p>
        
        <div class="flex-1 overflow-y-auto custom-scrollbar pr-2 relative z-10" style="max-height: 500px;">
            <div id="timeline_container" class="space-y-3">
                <?php if(empty($recentActivity)): ?>
                    <div id="empty_timeline" class="text-center text-gray-500 text-xs py-10 font-bold">در حال شنود شبکه...</div>
                <?php else: foreach($recentActivity as $act): 
                    $opName = ($act['fullname']) ? htmlspecialchars($act['fullname']) : (empty($act['username']) ? 'سیستم' : htmlspecialchars($act['username']));
                    $timeOnly = date('H:i', strtotime($act['created_at']));
                    
                    $isEmergency = (strpos($act['extra'] ?? '', 'اضطراری') !== false);
                    $bgClass = $isEmergency ? 'bg-rose-900/30 border-rose-800/50' : 'bg-gray-800/50 border-gray-700/50';
                    $uid = $act['act_type'] . '_' . $act['ref_id'];
                    
                    $icon = '🔔'; $color = 'text-blue-400';
                    if($act['act_type'] == 'sale') { $icon = '🛒'; $color = 'text-emerald-400'; }
                    if($act['act_type'] == 'receipt') { $icon = '📄'; $color = 'text-amber-400'; }
                    if($act['act_type'] == 'wallet') {
                        if($act['plan'] == 'bonus_add') { $icon = '🎁'; $color = 'text-purple-400'; }
                        elseif($act['plan'] == 'manual_sub') { $icon = '➖'; $color = 'text-rose-400'; }
                        else { $icon = '💳'; $color = 'text-indigo-400'; }
                    }
                    if($isEmergency) { $icon = '🚨'; $color = 'text-rose-500'; }
                ?>
                    <div data-uid="<?php echo $uid; ?>" class="flex items-start gap-3 p-3.5 rounded-xl border <?php echo $bgClass; ?>">
                        <div class="w-8 h-8 rounded-full bg-black/30 flex items-center justify-center shrink-0 shadow-inner <?php echo $color; ?> text-sm mt-1"><?php echo $icon; ?></div>
                        
                        <div class="flex-1 w-full">
                            <div class="flex justify-between items-center mb-1.5">
                                <span class="font-bold text-gray-200 text-sm"><?php echo $opName; ?></span>
                                <span class="text-[11px] text-gray-500 font-mono bg-gray-800 px-2 py-0.5 rounded-lg" dir="ltr"><?php echo $timeOnly; ?></span>
                            </div>
                            
                            <?php if($act['act_type'] == 'sale'): ?>
                                <div class="text-xs font-bold text-gray-300 leading-tight mb-2 bg-gray-800/50 p-2 rounded border border-gray-700/50 inline-block">
                                    طرح <?php echo htmlspecialchars($act['plan']); ?> <span class="text-blue-400 font-black">(<?php echo $act['volume']; ?>G)</span>
                                </div>
                                <div class="grid grid-cols-2 <?php echo $isAdmin ? 'sm:grid-cols-3' : ''; ?> gap-2 mt-1 bg-black/30 p-2.5 rounded-xl border border-gray-700/50">
                                    <div class="flex flex-col gap-1">
                                        <span class="text-gray-500 text-[10px] font-bold">پرداخت مشتری:</span>
                                        <span class="text-emerald-400 font-black text-sm" dir="ltr"><?php echo number_format($act['amount']); ?> <span class="text-[9px] font-normal">T</span></span>
                                    </div>
                                    <div class="flex flex-col gap-1">
                                        <span class="text-gray-500 text-[10px] font-bold">سود نماینده:</span>
                                        <span class="text-green-400 font-black text-sm" dir="ltr"><?php echo number_format($act['op_profit']); ?> <span class="text-[9px] font-normal">T</span></span>
                                    </div>
                                    <?php if($isAdmin): ?>
                                    <div class="flex flex-col gap-1 col-span-2 sm:col-span-1 border-t sm:border-t-0 sm:border-r border-gray-700/50 pt-2 sm:pt-0 sm:pr-2">
                                        <span class="text-gray-500 text-[10px] font-bold">سود ادمین:</span>
                                        <span class="text-purple-400 font-black text-sm" dir="ltr"><?php echo number_format($act['ad_profit']); ?> <span class="text-[9px] font-normal">T</span></span>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            <?php else: 
                                $title = $act['extra'] ?: 'فیش واریزی (منتظر تایید)';
                            ?>
                                <div class="text-xs font-bold text-gray-300 leading-tight mb-2"><?php echo $title; ?></div>
                                <div class="mt-2 bg-black/30 p-2.5 rounded-xl border border-gray-700/50 flex justify-between items-center">
                                    <span class="text-gray-500 text-[10px] font-bold">مبلغ تراکنش:</span>
                                    <span class="<?php echo $color; ?> font-black text-sm" dir="ltr"><?php echo number_format($act['amount']); ?> <span class="text-[9px] font-normal">T</span></span>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; endif; ?>
            </div>
        </div>
    </div>

    <div class="lg:col-span-7 bg-white dark:bg-slate-800 rounded-3xl shadow-sm border border-gray-100 dark:border-slate-700 p-6 md:p-8">
        <div class="flex flex-col xl:flex-row justify-between items-start xl:items-center mb-6 border-b border-gray-100 dark:border-slate-700 pb-4 gap-4">
            <h2 class="text-lg font-bold text-gray-800 dark:text-white flex items-center gap-2 shrink-0">
                <span class="w-2 h-6 bg-blue-600 rounded-full"></span> روند عملکرد و فروش کل
            </h2>
            <div class="flex flex-wrap gap-2">
                <button type="button" onclick="setChartDate('3days')" class="text-[10px] bg-gray-100 dark:bg-slate-700 text-gray-600 dark:text-gray-300 hover:bg-blue-100 hover:text-blue-600 px-2.5 py-1.5 rounded-lg font-bold transition">۳ روز اخیر</button>
                <button type="button" onclick="setChartDate('week')" class="text-[10px] bg-gray-100 dark:bg-slate-700 text-gray-600 dark:text-gray-300 hover:bg-blue-100 hover:text-blue-600 px-2.5 py-1.5 rounded-lg font-bold transition">۷ روز</button>
                <button type="button" onclick="setChartDate('15days')" class="text-[10px] bg-gray-100 dark:bg-slate-700 text-gray-600 dark:text-gray-300 hover:bg-blue-100 hover:text-blue-600 px-2.5 py-1.5 rounded-lg font-bold transition">۱۵ روز</button>
                <button type="button" onclick="setChartDate('month')" class="text-[10px] bg-gray-100 dark:bg-slate-700 text-gray-600 dark:text-gray-300 hover:bg-blue-100 hover:text-blue-600 px-2.5 py-1.5 rounded-lg font-bold transition">یک ماه</button>
                <button type="button" onclick="setChartDate('3months')" class="text-[10px] bg-gray-100 dark:bg-slate-700 text-gray-600 dark:text-gray-300 hover:bg-blue-100 hover:text-blue-600 px-2.5 py-1.5 rounded-lg font-bold transition">۳ ماه</button>
            </div>
        </div>

        <form id="chartFilterForm" class="flex flex-col sm:flex-row gap-3 items-end mb-6">
            <div class="relative w-full sm:w-40">
                <label class="block text-[10px] font-bold text-gray-500 dark:text-gray-400 mb-1">از تاریخ</label>
                <input type="text" id="start_date_picker" class="w-full border-2 border-gray-200 dark:border-slate-600 rounded-xl p-2 text-xs bg-gray-50 dark:bg-slate-700 focus:border-blue-500 outline-none dark:text-white cursor-pointer" dir="ltr" readonly>
                <input type="hidden" name="start_date" id="start_date_alt" value="<?php echo htmlspecialchars($filter_start); ?>">
            </div>
            <div class="relative w-full sm:w-40">
                <label class="block text-[10px] font-bold text-gray-500 dark:text-gray-400 mb-1">تا تاریخ</label>
                <input type="text" id="end_date_picker" class="w-full border-2 border-gray-200 dark:border-slate-600 rounded-xl p-2 text-xs bg-gray-50 dark:bg-slate-700 focus:border-blue-500 outline-none dark:text-white cursor-pointer" dir="ltr" readonly>
                <input type="hidden" name="end_date" id="end_date_alt" value="<?php echo htmlspecialchars($filter_end); ?>">
            </div>
            <button type="submit" class="w-full sm:w-auto bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-xl transition shadow-sm text-xs shrink-0">بروزرسانی نمودار</button>
        </form>

        <div id="chart_empty_msg" class="py-16 text-center text-gray-400 font-bold bg-gray-50 dark:bg-slate-700/30 rounded-2xl <?php echo empty($trendLabels) ? '' : 'hidden'; ?>">داده‌ای در این بازه یافت نشد.</div>
        <div id="chart_container" style="position: relative; height: 350px; width: 100%; transition: opacity 0.3s;" class="<?php echo empty($trendLabels) ? 'hidden' : ''; ?>">
            <canvas id="trendChart"></canvas>
        </div>
    </div>
</div>

<?php if($isAdmin): ?>
<div class="bg-white dark:bg-slate-800 rounded-3xl shadow-sm border border-gray-100 dark:border-slate-700 p-6 md:p-8 mb-8 border-t-8 border-t-indigo-500">
    <div class="flex flex-col xl:flex-row justify-between items-start xl:items-center mb-6 gap-4 border-b border-gray-100 dark:border-slate-700 pb-4">
        <h2 class="text-lg font-bold text-gray-800 dark:text-white flex items-center gap-2">
            <span class="w-2 h-6 bg-indigo-600 rounded-full"></span> مقایسه عملکرد و فروش نمایندگان
        </h2>
        
        <div class="flex flex-wrap items-center gap-2">
            <button type="button" onclick="loadOpChart('today', this)" class="op-time-btn active text-[10px] bg-indigo-100 text-indigo-700 dark:bg-indigo-900/50 dark:text-indigo-300 px-3 py-1.5 rounded-lg font-bold transition">امروز</button>
            <button type="button" onclick="loadOpChart('yesterday', this)" class="op-time-btn text-[10px] bg-gray-100 text-gray-600 dark:bg-slate-700 dark:text-gray-300 hover:bg-indigo-50 hover:text-indigo-600 px-3 py-1.5 rounded-lg font-bold transition">دیروز</button>
            <button type="button" onclick="loadOpChart('week', this)" class="op-time-btn text-[10px] bg-gray-100 text-gray-600 dark:bg-slate-700 dark:text-gray-300 hover:bg-indigo-50 hover:text-indigo-600 px-3 py-1.5 rounded-lg font-bold transition">این هفته</button>
            <button type="button" onclick="loadOpChart('month', this)" class="op-time-btn text-[10px] bg-gray-100 text-gray-600 dark:bg-slate-700 dark:text-gray-300 hover:bg-indigo-50 hover:text-indigo-600 px-3 py-1.5 rounded-lg font-bold transition">این ماه</button>
        </div>
    </div>

    <form id="opChartFilterForm" class="flex flex-col md:flex-row gap-3 items-end mb-6 bg-gray-50 dark:bg-slate-700/30 p-4 rounded-2xl border border-gray-100 dark:border-slate-600">
        <input type="hidden" id="op_time_filter" value="today">
        
        <div class="w-full md:w-1/3">
            <label class="block text-[10px] font-bold text-gray-500 dark:text-gray-400 mb-1">انتخاب نماینده (چندگانه):</label>
            <select id="op_select" multiple class="w-full border-2 border-gray-200 dark:border-slate-600 rounded-xl p-2 text-xs bg-white dark:bg-slate-700 focus:border-indigo-500 outline-none dark:text-white custom-scrollbar" style="height: 58px;">
                <option value="all" selected>همه نمایندگان (پیش‌فرض)</option>
                <?php 
                $opsList = $pdo->query("SELECT id, fullname, username FROM users WHERE role='operator'")->fetchAll();
                foreach($opsList as $op): 
                    $n = !empty($op['fullname']) ? $op['fullname'] : $op['username'];
                ?>
                    <option value="<?php echo $op['id']; ?>"><?php echo htmlspecialchars($n); ?></option>
                <?php endforeach; ?>
            </select>
            <p class="text-[9px] text-gray-400 mt-1">با نگه داشتن دکمه Ctrl در ویندوز می‌توانید چند نفر را انتخاب کنید</p>
        </div>
        
        <div class="w-full md:w-1/4">
            <label class="block text-[10px] font-bold text-gray-500 dark:text-gray-400 mb-1">از تاریخ (دلخواه)</label>
            <input type="text" id="op_start_picker" class="w-full border-2 border-gray-200 dark:border-slate-600 rounded-xl p-2.5 text-xs bg-white dark:bg-slate-700 outline-none dark:text-white cursor-pointer" dir="ltr" readonly placeholder="انتخاب کنید...">
            <input type="hidden" id="op_start_alt">
        </div>
        
        <div class="w-full md:w-1/4">
            <label class="block text-[10px] font-bold text-gray-500 dark:text-gray-400 mb-1">تا تاریخ (دلخواه)</label>
            <input type="text" id="op_end_picker" class="w-full border-2 border-gray-200 dark:border-slate-600 rounded-xl p-2.5 text-xs bg-white dark:bg-slate-700 outline-none dark:text-white cursor-pointer" dir="ltr" readonly placeholder="انتخاب کنید...">
            <input type="hidden" id="op_end_alt">
        </div>
        
        <button type="submit" class="w-full md:w-auto bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-2.5 px-6 rounded-xl transition shadow-sm text-xs shrink-0">اعمال فیلتر</button>
    </form>

    <div id="op_chart_empty" class="py-16 text-center text-gray-400 font-bold bg-gray-50 dark:bg-slate-700/30 rounded-2xl hidden">داده‌ای برای این نمایندگان یافت نشد.</div>
    <div id="op_chart_container" style="position: relative; height: 350px; width: 100%; transition: opacity 0.3s;">
        <canvas id="opChart"></canvas>
    </div>
</div>
<?php endif; ?>

<?php if($isAdmin): ?>
<div class="bg-white dark:bg-slate-800 rounded-3xl shadow-sm border border-gray-100 dark:border-slate-700 p-6 md:p-8 mb-8 border-t-8 border-t-rose-500">
    <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-8 gap-4">
        <div>
            <h2 class="text-xl font-black text-gray-800 dark:text-white flex items-center gap-2">
                <span class="text-2xl">📊</span> رادار هوشمند وضعیت شبکه
            </h2>
            <p class="text-xs text-gray-500 dark:text-gray-400 font-bold mt-1">مانیتورینگ لحظه‌ای نقدینگی، ریسک مالی و حجم سرور</p>
        </div>
        <a href="provider.php" class="bg-cyan-50 dark:bg-cyan-900/30 text-cyan-600 dark:text-cyan-400 px-4 py-2 rounded-xl text-xs font-bold border border-cyan-200 dark:border-cyan-800/50 hover:bg-cyan-100 transition shadow-sm">مدیریت حساب سرور اصلی ←</a>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-12 gap-8">
        <div class="lg:col-span-7 bg-gray-50 dark:bg-slate-700/50 rounded-2xl p-6 border border-gray-200 dark:border-slate-600 transition-all duration-300" id="radar_box_1">
            <h3 class="text-sm font-black text-gray-700 dark:text-gray-300 mb-4">وضعیت سرمایه در گردش پنل</h3>
            <div class="flex justify-between text-sm font-bold mb-2">
                <span class="text-emerald-600 dark:text-emerald-400 flex items-center gap-1"><span class="w-2 h-2 rounded-full bg-emerald-500"></span> نقدینگی امن (<span id="radar_wallet_perc"><?php echo $walletPercentage; ?></span>%)</span>
                <span class="text-rose-600 dark:text-rose-400 flex items-center gap-1">بدهی اعتباری نمایندگان (<span id="radar_debt_perc"><?php echo $debtPercentage; ?></span>%) <span class="w-2 h-2 rounded-full bg-rose-500"></span></span>
            </div>
            <div class="h-6 w-full bg-gray-200 dark:bg-slate-700 rounded-full overflow-hidden flex shadow-inner mb-4">
                <div id="radar_wallet_bar" class="h-full bg-emerald-500 transition-all duration-1000 relative" style="width: <?php echo $walletPercentage; ?>%">
                    <span id="radar_wallet_text" class="absolute inset-0 flex items-center justify-center text-[10px] text-white font-bold <?php echo $walletPercentage <= 10 ? 'hidden' : ''; ?>"><?php echo number_format($totalWalletBalance); ?></span>
                </div>
                <div id="radar_debt_bar" class="h-full bg-rose-500 transition-all duration-1000 relative" style="width: <?php echo $debtPercentage; ?>%">
                    <span id="radar_debt_text" class="absolute inset-0 flex items-center justify-center text-[10px] text-white font-bold <?php echo $debtPercentage <= 10 ? 'hidden' : ''; ?>"><?php echo number_format($totalCreditDebt); ?></span>
                </div>
            </div>
            <div class="text-xs text-gray-500 dark:text-gray-400 font-bold">
                مجموع سرمایه درگیر شبکه فروش: <span id="radar_total_system" data-val="<?php echo $totalSystemMoney; ?>" class="font-black text-blue-600 dark:text-blue-400"><?php echo number_format($totalSystemMoney); ?> تومان</span>
            </div>
        </div>

        <div class="lg:col-span-5 grid grid-cols-2 gap-4">
            <div class="bg-cyan-50 dark:bg-cyan-900/20 p-4 rounded-2xl border border-cyan-100 dark:border-cyan-800 flex flex-col justify-center transition-all duration-300" id="radar_box_2">
                <span class="text-[10px] font-bold text-cyan-600 dark:text-cyan-400 mb-1">کل حجم فروش رفته</span>
                <span id="radar_total_gb" data-val="<?php echo $totalGBSold; ?>" class="text-2xl font-black text-cyan-700 dark:text-cyan-300"><?php echo number_format($totalGBSold); ?> <span class="text-xs font-normal">GB</span></span>
            </div>
            <div class="bg-rose-50 dark:bg-rose-900/20 p-4 rounded-2xl border border-rose-100 dark:border-rose-800 flex flex-col justify-center transition-all duration-300" id="radar_box_3">
                <span class="text-[10px] font-bold text-rose-600 dark:text-rose-400 mb-1">بدهی شما به سرور اصلی</span>
                <span id="radar_provider_debt" data-val="<?php echo $providerDebt; ?>" class="text-xl font-black text-rose-700 dark:text-rose-300" dir="ltr"><?php echo number_format($providerDebt); ?> <span class="text-[10px] font-normal">T</span></span>
            </div>
            <div class="col-span-2 bg-amber-50 dark:bg-amber-900/20 p-4 rounded-2xl border border-amber-100 dark:border-amber-800 flex justify-between items-center transition-all duration-300" id="radar_box_4">
                <span class="text-xs font-bold text-amber-600 dark:text-amber-400 mb-1">ارزش فیش‌های منتظر بررسی:</span>
                <span id="radar_pending_amt" data-val="<?php echo $radarPendingAmount; ?>" class="text-xl font-black text-amber-700 dark:text-amber-300" dir="ltr"><?php echo number_format($radarPendingAmount); ?> <span class="text-[10px] font-normal">T</span></span>
            </div>
        </div>
    </div>
</div>
<?php else: ?>
<div class="bg-white dark:bg-slate-800 rounded-3xl shadow-sm border border-gray-100 dark:border-slate-700 p-6 md:p-8 mb-8 border-t-8 border-t-blue-500">
    <h2 class="text-xl font-black text-gray-800 dark:text-white mb-6 flex items-center gap-2">
        <span class="text-2xl">📊</span> رادار عملکرد و فروش شما
    </h2>
    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
        <div class="bg-blue-50 dark:bg-blue-900/20 p-5 rounded-2xl border border-blue-100 dark:border-blue-800 flex items-center gap-4 transition-all duration-300" id="radar_box_1">
            <div class="w-12 h-12 bg-blue-100 dark:bg-blue-800 text-blue-600 dark:text-blue-300 rounded-full flex items-center justify-center text-2xl shrink-0">🛒</div>
            <div>
                <span class="block text-xs font-bold text-blue-600 dark:text-blue-400 mb-1">مجموع خریدهای شما (کل)</span>
                <span id="radar_total_buys" data-val="<?php echo $radarTotalBuys; ?>" class="text-xl font-black text-blue-800 dark:text-blue-200"><?php echo number_format($radarTotalBuys); ?> <span class="text-xs font-normal">سرویس</span></span>
            </div>
        </div>
        <div class="bg-emerald-50 dark:bg-emerald-900/20 p-5 rounded-2xl border border-emerald-100 dark:border-emerald-800 flex items-center gap-4 transition-all duration-300" id="radar_box_2">
            <div class="w-12 h-12 bg-emerald-100 dark:bg-emerald-800 text-emerald-600 dark:text-emerald-300 rounded-full flex items-center justify-center text-2xl shrink-0">💎</div>
            <div>
                <span class="block text-xs font-bold text-emerald-600 dark:text-emerald-400 mb-1">مجموع پرداختی به سیستم</span>
                <span id="radar_total_spent" data-val="<?php echo $radarTotalSpent; ?>" class="text-lg font-black text-emerald-800 dark:text-emerald-200" dir="ltr"><?php echo number_format($radarTotalSpent); ?> <span class="text-[10px] font-normal">T</span></span>
            </div>
        </div>
        <div class="bg-purple-50 dark:bg-purple-900/20 p-5 rounded-2xl border border-purple-100 dark:border-purple-800 flex items-center gap-4 transition-all duration-300" id="radar_box_3">
            <div class="w-12 h-12 bg-purple-100 dark:bg-purple-800 text-purple-600 dark:text-purple-300 rounded-full flex items-center justify-center text-2xl shrink-0">📈</div>
            <div>
                <div class="text-xs font-bold text-gray-500">
    جدید: <span class="text-emerald-600"><?php echo $todayNewCount ?? 0; ?></span> 
    | تمدید: <span class="text-blue-600"><?php echo $todayRenewCount ?? 0; ?></span>
</div></div>
    </div>
</div>
<?php endif; ?>

<h2 class="text-lg font-black text-gray-800 dark:text-white mb-4 mt-8">میانبرهای عملیاتی و دسترسی سریع</h2>
<div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-8 gap-3 mb-8">
    <?php if ($isAdmin): ?>
        <a href="store/store.php" class="bg-white dark:bg-slate-800 rounded-2xl p-4 flex flex-col items-center justify-center gap-2 shadow-sm border border-gray-100 dark:border-slate-700 hover:-translate-y-1 transition-transform group">
            <div class="w-10 h-10 bg-blue-50 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400 rounded-xl flex items-center justify-center text-xl group-hover:scale-110 transition-transform">🛒</div>
            <span class="text-xs font-bold text-gray-700 dark:text-gray-300">فروشگاه</span>
        </a>
        <a href="inventory/inventory.php" class="bg-white dark:bg-slate-800 rounded-2xl p-4 flex flex-col items-center justify-center gap-2 shadow-sm border border-gray-100 dark:border-slate-700 hover:-translate-y-1 transition-transform group">
            <div class="w-10 h-10 bg-emerald-50 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400 rounded-xl flex items-center justify-center text-xl group-hover:scale-110 transition-transform">📦</div>
            <span class="text-xs font-bold text-gray-700 dark:text-gray-300">انبار</span>
        </a>
        <a href="reports.php" class="bg-white dark:bg-slate-800 rounded-2xl p-4 flex flex-col items-center justify-center gap-2 shadow-sm border border-gray-100 dark:border-slate-700 hover:-translate-y-1 transition-transform group">
            <div class="w-10 h-10 bg-purple-50 dark:bg-purple-900/30 text-purple-600 dark:text-purple-400 rounded-xl flex items-center justify-center text-xl group-hover:scale-110 transition-transform">📊</div>
            <span class="text-xs font-bold text-gray-700 dark:text-gray-300">گزارشات</span>
        </a>
        <a href="wallet/wallet.php" class="bg-white dark:bg-slate-800 rounded-2xl p-4 flex flex-col items-center justify-center gap-2 shadow-sm border <?php echo ($pendingReceipts ?? 0) > 0 ? 'border-amber-400 bg-amber-50 dark:bg-amber-900/10' : 'border-gray-100 dark:border-slate-700'; ?> hover:-translate-y-1 transition-transform group relative">
            <?php if(($pendingReceipts ?? 0) > 0): ?><span class="absolute top-2 right-2 flex h-2 w-2"><span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-amber-400 opacity-75"></span><span class="relative inline-flex rounded-full h-2 w-2 bg-amber-500"></span></span><?php endif; ?>
            <div class="w-10 h-10 bg-amber-50 dark:bg-amber-900/30 text-amber-600 dark:text-amber-400 rounded-xl flex items-center justify-center text-xl group-hover:scale-110 transition-transform">💳</div>
            <span class="text-xs font-bold text-gray-700 dark:text-gray-300">امور مالی</span>
        </a>
        <a href="subscriptions/subscriptions.php" class="bg-white dark:bg-slate-800 rounded-2xl p-4 flex flex-col items-center justify-center gap-2 shadow-sm border border-gray-100 dark:border-slate-700 hover:-translate-y-1 transition-transform group">
            <div class="w-10 h-10 bg-indigo-50 dark:bg-indigo-900/30 text-indigo-600 dark:text-indigo-400 rounded-xl flex items-center justify-center text-xl group-hover:scale-110 transition-transform">🌐</div>
            <span class="text-xs font-bold text-gray-700 dark:text-gray-300">اشتراک‌ها</span>
        </a>
        <a href="users.php" class="bg-white dark:bg-slate-800 rounded-2xl p-4 flex flex-col items-center justify-center gap-2 shadow-sm border border-gray-100 dark:border-slate-700 hover:-translate-y-1 transition-transform group">
            <div class="w-10 h-10 bg-pink-50 dark:bg-pink-900/30 text-pink-600 dark:text-pink-400 rounded-xl flex items-center justify-center text-xl group-hover:scale-110 transition-transform">👥</div>
            <span class="text-xs font-bold text-gray-700 dark:text-gray-300">کاربران</span>
        </a>
        <a href="provider.php" class="bg-white dark:bg-slate-800 rounded-2xl p-4 flex flex-col items-center justify-center gap-2 shadow-sm border border-gray-100 dark:border-slate-700 hover:-translate-y-1 transition-transform group">
            <div class="w-10 h-10 bg-cyan-50 dark:bg-cyan-900/30 text-cyan-600 dark:text-cyan-400 rounded-xl flex items-center justify-center text-xl group-hover:scale-110 transition-transform">🏦</div>
            <span class="text-xs font-bold text-gray-700 dark:text-gray-300">تسویه با سرور</span>
        </a>
        <a href="festivals.php" class="bg-white dark:bg-slate-800 rounded-2xl p-4 flex flex-col items-center justify-center gap-2 shadow-sm border border-gray-100 dark:border-slate-700 hover:-translate-y-1 transition-transform group">
            <div class="w-10 h-10 bg-rose-50 dark:bg-rose-900/30 text-rose-600 dark:text-rose-400 rounded-xl flex items-center justify-center text-xl group-hover:scale-110 transition-transform">🎉</div>
            <span class="text-xs font-bold text-gray-700 dark:text-gray-300">تخفیف‌ها</span>
        </a>
    <?php else: ?>
        <a href="store/store.php" class="bg-white dark:bg-slate-800 rounded-2xl p-4 flex flex-col items-center justify-center gap-2 shadow-sm border border-gray-100 dark:border-slate-700 hover:-translate-y-1 transition-transform group">
            <div class="w-10 h-10 bg-blue-50 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400 rounded-xl flex items-center justify-center text-xl group-hover:scale-110 transition-transform">🛒</div>
            <span class="text-xs font-bold text-gray-700 dark:text-gray-300">خرید سرویس</span>
        </a>
        <a href="wallet/wallet.php" class="bg-white dark:bg-slate-800 rounded-2xl p-4 flex flex-col items-center justify-center gap-2 shadow-sm border <?php echo $creditDebt > 0 ? 'border-rose-400 bg-rose-50 dark:bg-rose-900/10' : 'border-gray-100 dark:border-slate-700'; ?> hover:-translate-y-1 transition-transform group relative">
            <?php if($creditDebt > 0): ?><span class="absolute top-2 right-2 flex h-2 w-2"><span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-rose-400 opacity-75"></span><span class="relative inline-flex rounded-full h-2 w-2 bg-rose-500"></span></span><?php endif; ?>
            <div class="w-10 h-10 <?php echo $creditDebt > 0 ? 'bg-rose-100 text-rose-600 dark:bg-rose-900/50 dark:text-rose-400' : 'bg-emerald-50 text-emerald-600 dark:bg-emerald-900/30 dark:text-emerald-400'; ?> rounded-xl flex items-center justify-center text-xl group-hover:scale-110 transition-transform">💳</div>
            <span class="text-xs font-bold <?php echo $creditDebt > 0 ? 'text-rose-600 dark:text-rose-400' : 'text-gray-700 dark:text-gray-300'; ?>">کیف پول</span>
        </a>
        <a href="subscriptions/subscriptions.php" class="bg-white dark:bg-slate-800 rounded-2xl p-4 flex flex-col items-center justify-center gap-2 shadow-sm border border-gray-100 dark:border-slate-700 hover:-translate-y-1 transition-transform group">
            <div class="w-10 h-10 bg-purple-50 dark:bg-purple-900/30 text-purple-600 dark:text-purple-400 rounded-xl flex items-center justify-center text-xl group-hover:scale-110 transition-transform">🌐</div>
            <span class="text-xs font-bold text-gray-700 dark:text-gray-300">مشتریان من</span>
        </a>
        <a href="reports.php" class="bg-white dark:bg-slate-800 rounded-2xl p-4 flex flex-col items-center justify-center gap-2 shadow-sm border border-gray-100 dark:border-slate-700 hover:-translate-y-1 transition-transform group">
            <div class="w-10 h-10 bg-amber-50 dark:bg-amber-900/30 text-amber-600 dark:text-amber-400 rounded-xl flex items-center justify-center text-xl group-hover:scale-110 transition-transform">📊</div>
            <span class="text-xs font-bold text-gray-700 dark:text-gray-300">گزارشات</span>
        </a>
        <a href="settings.php" class="bg-white dark:bg-slate-800 rounded-2xl p-4 flex flex-col items-center justify-center gap-2 shadow-sm border border-gray-100 dark:border-slate-700 hover:-translate-y-1 transition-transform group">
            <div class="w-10 h-10 bg-cyan-50 dark:bg-cyan-900/30 text-cyan-600 dark:text-cyan-400 rounded-xl flex items-center justify-center text-xl group-hover:scale-110 transition-transform">🏦</div>
            <span class="text-xs font-bold text-gray-700 dark:text-gray-300">حساب‌های من</span>
        </a>
    <?php endif; ?>
</div>

<script src="/vpnet-panel/assets/js/jquery-3.7.0.min.js"></script>
<script src="/vpnet-panel/assets/js/chart.min.js"></script>
<script src="https://unpkg.com/persian-date@1.1.0/dist/persian-date.min.js"></script>
<script src="https://unpkg.com/persian-datepicker@1.2.0/dist/js/persian-datepicker.min.js"></script>

<script>
    // ==========================================
    // تنظیمات تقویم‌ها و نمودار آژاکسی اصلی
    // ==========================================
    $(document).ready(function() {
        const dpOptions = { format: 'YYYY/MM/DD', initialValue: false, autoClose: true, calendar: { persian: { locale: 'fa' } } };
        $('#start_date_picker').persianDatepicker({ ...dpOptions, onSelect: function (unix) { $('#start_date_alt').val(new persianDate(unix).format('YYYY/MM/DD')); } });
        $('#end_date_picker').persianDatepicker({ ...dpOptions, onSelect: function (unix) { $('#end_date_alt').val(new persianDate(unix).format('YYYY/MM/DD')); } });

        let startVal = $('#start_date_alt').val();
        let endVal = $('#end_date_alt').val();
        if(startVal) $('#start_date_picker').val(startVal);
        if(endVal) $('#end_date_picker').val(endVal);
    });

    let trendChart;
    Chart.defaults.font.family = 'Vazirmatn';
    Chart.defaults.color = document.documentElement.classList.contains('dark') ? '#94a3b8' : '#64748b';

    function initOrUpdateChart(labels, profit, volume, count) {
        if (labels.length === 0) {
            $('#chart_container').addClass('hidden');
            $('#chart_empty_msg').removeClass('hidden');
            return;
        }
        $('#chart_empty_msg').addClass('hidden');
        $('#chart_container').removeClass('hidden').css('opacity', '0.5');

        if (trendChart) {
            trendChart.data.labels = labels;
            trendChart.data.datasets[0].data = profit;
            trendChart.data.datasets[1].data = volume;
            trendChart.data.datasets[2].data = count;
            trendChart.update();
            setTimeout(() => $('#chart_container').css('opacity', '1'), 150);
        } else {
            const ctxTrend = document.getElementById('trendChart').getContext('2d');
            trendChart = new Chart(ctxTrend, {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [
                        { label: 'سود (T)', data: profit, backgroundColor: 'rgba(16, 185, 129, 0.8)', borderRadius: 6, yAxisID: 'y' },
                        { label: 'حجم (GB)', data: volume, type: 'line', borderColor: '#8b5cf6', borderWidth: 3, pointBackgroundColor: '#fff', tension: 0.4, yAxisID: 'y1' },
                        { label: 'فروش (عدد)', data: count, type: 'line', borderColor: '#f59e0b', borderWidth: 3, pointBackgroundColor: '#fff', tension: 0.4, yAxisID: 'y1' }
                    ]
                },
                options: {
                    responsive: true, maintainAspectRatio: false, interaction: { mode: 'index', intersect: false },
                    scales: {
                        y: { type: 'linear', position: 'left', grid: { color: 'rgba(156, 163, 175, 0.1)' } },
                        y1: { type: 'linear', position: 'right', grid: { display: false } },
                        x: { grid: { display: false } }
                    }
                }
            });
            setTimeout(() => $('#chart_container').css('opacity', '1'), 150);
        }
    }

    initOrUpdateChart(
        <?php echo json_encode($trendLabels); ?>, 
        <?php echo json_encode($trendDataProfit); ?>, 
        <?php echo json_encode($trendDataVolume); ?>, 
        <?php echo json_encode($trendDataCount); ?>
    );

    function fetchChartData(start, end) {
        $.ajax({
            url: window.location.href.split('?')[0],
            type: 'GET',
            data: { ajax_chart: 1, start_date: start, end_date: end },
            dataType: 'json',
            success: function(res) { initOrUpdateChart(res.labels, res.profit, res.volume, res.count); }
        });
    }

    function setChartDate(range) {
        const pd = new persianDate();
        let startStr = '', endStr = pd.format('YYYY/MM/DD');

        if (range === '3days') startStr = pd.subtract('days', 3).format('YYYY/MM/DD');
        else if (range === 'week') startStr = pd.subtract('days', 7).format('YYYY/MM/DD');
        else if (range === '15days') startStr = pd.subtract('days', 15).format('YYYY/MM/DD');
        else if (range === 'month') startStr = pd.subtract('days', 30).format('YYYY/MM/DD');
        else if (range === '3months') startStr = pd.subtract('days', 90).format('YYYY/MM/DD');

        $('#start_date_picker').val(startStr); $('#start_date_alt').val(startStr);
        $('#end_date_picker').val(endStr); $('#end_date_alt').val(endStr);
        fetchChartData(startStr, endStr);
    }

    $('#chartFilterForm').on('submit', function(e) {
        e.preventDefault();
        fetchChartData($('#start_date_alt').val(), $('#end_date_alt').val());
    });

    <?php if($isAdmin): ?>
    // ==========================================
    // کدهای مربوط به نمودار مقایسه نمایندگان (فقط ادمین)
    // ==========================================
    let opChart;
    function initOpChart(labels, sales, op_profit, ad_profit, vol) {
        if (labels.length === 0) {
            $('#op_chart_container').addClass('hidden');
            $('#op_chart_empty').removeClass('hidden');
            return;
        }
        $('#op_chart_empty').addClass('hidden');
        $('#op_chart_container').removeClass('hidden').css('opacity', '0.5');

        if (opChart) {
            opChart.data.labels = labels;
            opChart.data.datasets[0].data = sales;
            opChart.data.datasets[1].data = op_profit;
            opChart.data.datasets[2].data = ad_profit;
            opChart.data.datasets[3].data = vol;
            opChart.update();
            setTimeout(() => $('#op_chart_container').css('opacity', '1'), 150);
        } else {
            const ctx = document.getElementById('opChart').getContext('2d');
            opChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [
                        { label: 'فروش کل (T)', data: sales, backgroundColor: '#3b82f6', borderRadius: 4, yAxisID: 'y' },
                        { label: 'سود نماینده (T)', data: op_profit, backgroundColor: '#10b981', borderRadius: 4, yAxisID: 'y' },
                        { label: 'سود ادمین (T)', data: ad_profit, backgroundColor: '#8b5cf6', borderRadius: 4, yAxisID: 'y' },
                        { label: 'حجم فروخته شده (GB)', data: vol, type: 'line', borderColor: '#f59e0b', borderWidth: 3, pointBackgroundColor: '#fff', tension: 0.4, yAxisID: 'y1' }
                    ]
                },
                options: {
                    responsive: true, maintainAspectRatio: false, interaction: { mode: 'index', intersect: false },
                    scales: {
                        y: { type: 'linear', position: 'left', grid: { color: 'rgba(156, 163, 175, 0.1)' } },
                        y1: { type: 'linear', position: 'right', grid: { display: false } },
                        x: { grid: { display: false } }
                    }
                }
            });
            setTimeout(() => $('#op_chart_container').css('opacity', '1'), 150);
        }
    }

    function loadOpChart(timeFilter, btnElement) {
        $('.op-time-btn').removeClass('active bg-indigo-100 text-indigo-700 dark:bg-indigo-900/50 dark:text-indigo-300').addClass('bg-gray-100 text-gray-600 dark:bg-slate-700 dark:text-gray-300');
        $(btnElement).addClass('active bg-indigo-100 text-indigo-700 dark:bg-indigo-900/50 dark:text-indigo-300').removeClass('bg-gray-100 text-gray-600 dark:bg-slate-700 dark:text-gray-300');
        
        $('#op_time_filter').val(timeFilter);
        $('#op_start_picker').val(''); $('#op_start_alt').val('');
        $('#op_end_picker').val(''); $('#op_end_alt').val('');
        
        fetchOpChart();
    }

    function fetchOpChart() {
        let timeFilter = $('#op_time_filter').val();
        let sd = $('#op_start_alt').val();
        let ed = $('#op_end_alt').val();
        if(sd || ed) timeFilter = 'custom';
        
        let ops = $('#op_select').val();

        $.ajax({
            url: window.location.href.split('?')[0],
            type: 'GET',
            data: { ajax_op_chart: 1, time_filter: timeFilter, start: sd, end: ed, ops: ops },
            dataType: 'json',
            success: function(res) {
                initOpChart(res.labels, res.sales, res.op_profit, res.ad_profit, res.vol);
            }
        });
    }

    $('#opChartFilterForm').on('submit', function(e) {
        e.preventDefault();
        $('#op_time_filter').val('custom');
        $('.op-time-btn').removeClass('active bg-indigo-100 text-indigo-700 dark:bg-indigo-900/50 dark:text-indigo-300').addClass('bg-gray-100 text-gray-600 dark:bg-slate-700 dark:text-gray-300');
        fetchOpChart();
    });

    $(document).ready(function() {
        const dpOptions2 = { format: 'YYYY/MM/DD', initialValue: false, autoClose: true, calendar: { persian: { locale: 'fa' } } };
        $('#op_start_picker').persianDatepicker({ ...dpOptions2, onSelect: function (unix) { $('#op_start_alt').val(new persianDate(unix).format('YYYY/MM/DD')); } });
        $('#op_end_picker').persianDatepicker({ ...dpOptions2, onSelect: function (unix) { $('#op_end_alt').val(new persianDate(unix).format('YYYY/MM/DD')); } });
        
        fetchOpChart();
    });
    <?php endif; ?>

    // ==========================================
    // موتور مانیتورینگ زنده (AJAX Polling) 
    // ==========================================
    let lastTimeObj = "<?php echo $initLastTime; ?>";
    const isAdmin = <?php echo $isAdmin ? 'true' : 'false'; ?>;
    
    let processedIds = [
        <?php 
            if(!empty($newActivity)) {
                $ids = array_map(function($a) { return "'" . $a['act_type'] . "_" . $a['ref_id'] . "'"; }, $newActivity);
                echo implode(",", $ids);
            }
        ?>
    ];

    function formatNumber(num) {
        return Number(num).toLocaleString('en-US');
    }

    function updateStatBox(id, newValue, htmlContent) {
        let el = $('#' + id);
        if (el.attr('data-val') != newValue) {
            el.attr('data-val', newValue);
            el.html(htmlContent);
            let box = el.closest('div').length ? el.closest('div') : el.closest('a');
            box.addClass('ring-2 ring-emerald-500 scale-[1.02]').delay(1000).queue(function(next){
                $(this).removeClass('ring-2 ring-emerald-500 scale-[1.02]');
                next();
            });
        }
    }

    function updateLiveList(id, htmlContent) {
        let el = $('#' + id);
        el.html(htmlContent);
    }

    function fetchLiveFeed() {
        $.ajax({
            url: window.location.href.split('?')[0],
            type: 'GET',
            data: { ajax_live: 1, last_time: lastTimeObj },
            dataType: 'json',
            success: function(response) {
                // بروزرسانی ویجت‌های بالا
                if (isAdmin) {
                    updateStatBox('live_pending', response.stats.pending_count, formatNumber(response.stats.pending_count));
                    let pendHtml = '';
                    if(response.stats.pending_list.length > 0) {
                        response.stats.pending_list.forEach(p => {
                            pendHtml += `<div class="flex justify-between border-b border-gray-50 dark:border-slate-700/50 pb-0.5"><span class="truncate w-16">${p.op_name}</span><span class="font-mono text-amber-600 dark:text-amber-400" dir="ltr">${formatNumber(p.amount)}</span></div>`;
                        });
                    } else {
                        pendHtml = '<span>موردی نیست</span>';
                    }
                    updateLiveList('live_pending_list', pendHtml);

                    updateStatBox('live_stock', response.stats.stock_count, formatNumber(response.stats.stock_count));
                    let stockHtml = '';
                    if(response.stats.stock_list.length > 0) {
                        response.stats.stock_list.forEach(s => {
                            stockHtml += `<div class="flex justify-between border-b border-gray-50 dark:border-slate-700/50 pb-0.5"><span class="truncate w-16">${s.plan_name} (${s.volume}G)</span><span class="font-mono font-bold text-rose-600 dark:text-rose-400">${s.qty} عدد</span></div>`;
                        });
                    } else {
                        stockHtml = '<span>موجودی تکمیل است</span>';
                    }
                    updateLiveList('live_stock_list', stockHtml);
                }
                
                updateStatBox('live_profit', response.stats.profit, formatNumber(response.stats.profit) + ' <span class="text-[10px]">T</span>');
                updateStatBox('live_sales', response.stats.sales, formatNumber(response.stats.sales));
                updateStatBox('live_volume', response.stats.volume, formatNumber(response.stats.volume) + ' <span class="text-[10px] font-normal text-gray-400">GB</span>');

                // بروزرسانی رادار وضعیت شبکه (لایو)
                if (response.radar) {
                    if (isAdmin) {
                        updateStatBox('radar_total_system', response.radar.totalSystemMoney, formatNumber(response.radar.totalSystemMoney) + ' تومان');
                        updateStatBox('radar_total_gb', response.radar.totalGBSold, formatNumber(response.radar.totalGBSold) + ' <span class="text-xs font-normal">GB</span>');
                        updateStatBox('radar_provider_debt', response.radar.providerDebt, formatNumber(response.radar.providerDebt) + ' <span class="text-[10px] font-normal">T</span>');
                        updateStatBox('radar_pending_amt', response.radar.radarPendingAmount, formatNumber(response.radar.radarPendingAmount) + ' <span class="text-[10px] font-normal">T</span>');
                        
                        $('#radar_wallet_perc').text(response.radar.walletPercentage);
                        $('#radar_debt_perc').text(response.radar.debtPercentage);
                        $('#radar_wallet_bar').css('width', response.radar.walletPercentage + '%');
                        $('#radar_debt_bar').css('width', response.radar.debtPercentage + '%');
                        
                        if(response.radar.walletPercentage > 10) { $('#radar_wallet_text').removeClass('hidden').text(formatNumber(response.radar.totalWalletBalance)); } else { $('#radar_wallet_text').addClass('hidden'); }
                        if(response.radar.debtPercentage > 10) { $('#radar_debt_text').removeClass('hidden').text(formatNumber(response.radar.totalCreditDebt)); } else { $('#radar_debt_text').addClass('hidden'); }
                    } else {
                        updateStatBox('radar_total_buys', response.radar.radarTotalBuys, formatNumber(response.radar.radarTotalBuys) + ' <span class="text-xs font-normal">سرویس</span>');
                        updateStatBox('radar_total_spent', response.radar.radarTotalSpent, formatNumber(response.radar.radarTotalSpent) + ' <span class="text-[10px] font-normal">T</span>');
                        $('#radar_today_new').text(response.radar.todayNewCount);
                        $('#radar_today_renew').text(response.radar.todayRenewCount);
                    }
                }

                // بروزرسانی تایم‌لاین با انیمیشن
                if (response.activities && response.activities.length > 0) {
                    $('#empty_timeline').hide();
                    
                    response.activities.forEach(function(act) {
                        let uid = act.uid;
                        if(processedIds.includes(uid)) return;
                        processedIds.push(uid);

                        let opName = act.op_name;
                        let isEmergency = (act.extra && act.extra.includes('اضطراری'));
                        
                        let bgClass = isEmergency ? 'bg-rose-900/30 border-rose-800/50' : 'bg-gray-800/50 border-gray-700/50';
                        let glowClass = isEmergency ? 'super-emergency-item' : 'super-new-item';
                        
                        let icon = '🔔'; let color = 'text-blue-400';
                        if(act.act_type === 'sale') { icon = '🛒'; color = 'text-emerald-400'; }
                        if(act.act_type === 'receipt') { icon = '📄'; color = 'text-amber-400'; }
                        if(act.act_type === 'wallet') {
                            if(act.plan === 'bonus_add') { icon = '🎁'; color = 'text-purple-400'; }
                            else if(act.plan === 'manual_sub') { icon = '➖'; color = 'text-rose-400'; }
                            else { icon = '💳'; color = 'text-indigo-400'; }
                        }
                        if(isEmergency) { icon = '🚨'; color = 'text-rose-500'; }
                        
                        let contentHtml = '';
                        if (act.act_type === 'sale') {
                            let adminProfitHtml = isAdmin ? `
                                <div class="flex flex-col gap-1 col-span-2 sm:col-span-1 border-t sm:border-t-0 sm:border-r border-gray-700/50 pt-2 sm:pt-0 sm:pr-2">
                                    <span class="text-gray-500 text-[10px] font-bold">سود ادمین:</span>
                                    <span class="text-purple-400 font-black text-sm" dir="ltr">${formatNumber(act.ad_profit)} <span class="text-[9px] font-normal">T</span></span>
                                </div>` : '';
                            let gridCols = isAdmin ? 'sm:grid-cols-3' : '';
                            contentHtml = `
                                <div class="text-xs font-bold text-gray-300 leading-tight mb-2 bg-gray-800/50 p-2 rounded border border-gray-700/50 inline-block">
                                    طرح ${act.plan} <span class="text-blue-400 font-black">(${act.volume}G)</span>
                                </div>
                                <div class="grid grid-cols-2 ${gridCols} gap-2 mt-1 bg-black/30 p-2.5 rounded-xl border border-gray-700/50">
                                    <div class="flex flex-col gap-1">
                                        <span class="text-gray-500 text-[10px] font-bold">پرداخت مشتری:</span>
                                        <span class="text-emerald-400 font-black text-sm" dir="ltr">${formatNumber(act.amount)} <span class="text-[9px] font-normal">T</span></span>
                                    </div>
                                    <div class="flex flex-col gap-1">
                                        <span class="text-gray-500 text-[10px] font-bold">سود نماینده:</span>
                                        <span class="text-green-400 font-black text-sm" dir="ltr">${formatNumber(act.op_profit)} <span class="text-[9px] font-normal">T</span></span>
                                    </div>
                                    ${adminProfitHtml}
                                </div>
                            `;
                        } else {
                            let title = act.extra ? act.extra : 'فیش واریزی (منتظر تایید)';
                            contentHtml = `
                                <div class="text-xs font-bold text-gray-300 leading-tight mb-2">${title}</div>
                                <div class="mt-2 bg-black/30 p-2.5 rounded-xl border border-gray-700/50 flex justify-between items-center">
                                    <span class="text-gray-500 text-[10px] font-bold">مبلغ تراکنش:</span>
                                    <span class="${color} font-black text-sm" dir="ltr">${formatNumber(act.amount)} <span class="text-[9px] font-normal">T</span></span>
                                </div>
                            `;
                        }

                        let html = `
                        <div data-uid="${uid}" class="flex items-start gap-3 p-3.5 rounded-xl border ${bgClass} ${glowClass}" style="display:none;">
                            <div class="w-8 h-8 rounded-full bg-black/30 flex items-center justify-center shrink-0 shadow-inner ${color} text-sm mt-1">${icon}</div>
                            <div class="flex-1 w-full">
                                <div class="flex justify-between items-center mb-1.5">
                                    <span class="font-bold text-gray-200 text-[13px] sm:text-sm">${opName}</span>
                                    <span class="text-[11px] text-gray-500 font-mono bg-gray-800 px-2 py-0.5 rounded-lg" dir="ltr">${act.time_shamsi}</span>
                                </div>
                                ${contentHtml}
                            </div>
                        </div>`;
                        
                        let $el = $(html);
                        $('#timeline_container').prepend($el);
                        $el.slideDown(400);
                        
                        if ($('#timeline_container').children().length > 30) {
                            $('#timeline_container').children().last().remove();
                        }
                    });
                }
                lastTimeObj = response.current_time;
            },
            error: function(err) {
                console.log("Monitoring paused, retrying...");
            }
        });
    }

    setInterval(fetchLiveFeed, 5000);
</script>

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