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

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

require_once '../includes/functions.php';

// ==========================================
// دریافت اطلاعات پایه برای ساخت فرم فیلتر
// ==========================================
$plansList = $pdo->query("SELECT plan_name FROM plans ORDER BY id ASC")->fetchAll(PDO::FETCH_COLUMN);
$operatorsList = [];
if ($isAdmin) {
    $operatorsList = $pdo->query("SELECT id, username, fullname FROM users WHERE role = 'operator' ORDER BY id ASC")->fetchAll();
}

$filter_start    = $_GET['start_date'] ?? '';
$filter_end      = $_GET['end_date'] ?? '';
$filter_plan     = $_GET['plan'] ?? '';
$filter_operator = $_GET['operator_id'] ?? '';

$conditions = [];
$params = [];

if (!$isAdmin) {
    $conditions[] = "t.user_id = :user_id";
    $params[':user_id'] = $userId;
} elseif ($isAdmin && !empty($filter_operator)) {
    $conditions[] = "t.user_id = :op_id";
    $params[':op_id'] = $filter_operator;
}
if (!empty($filter_plan)) {
    $conditions[] = "t.plan = :plan";
    $params[':plan'] = $filter_plan;
}
if (!empty($filter_start)) {
    $conditions[] = "t.date_shamsi >= :start";
    $params[':start'] = $filter_start;
}
if (!empty($filter_end)) {
    $conditions[] = "t.date_shamsi <= :end";
    $params[':end'] = $filter_end;
}

$whereSQL = (!empty($conditions)) ? "WHERE " . implode(" AND ", $conditions) : "";

// ==========================================
// اجرای کوئری‌های آماری کلان با فیلتر (بازه انتخابی)
// ==========================================
$sqlStats = "SELECT 
                SUM(t.profit) as total_op_profit, 
                SUM(t.admin_profit) as total_admin_profit,
                SUM(t.paid_amount) as total_revenue, 
                SUM(t.volume) as total_volume, 
                COUNT(t.id) as total_count,
                SUM(p.cost_price * t.volume) as total_cost_paid
             FROM transactions t 
             JOIN plans p ON t.plan = p.plan_name 
             $whereSQL";
$stmtStats = $pdo->prepare($sqlStats);
$stmtStats->execute($params);
$stats = $stmtStats->fetch();

$totalRevenue = $stats['total_revenue'] ?? 0;
$totalVolume  = $stats['total_volume'] ?? 0;
$totalCount   = $stats['total_count'] ?? 0;
$totalAdminProfit = $stats['total_admin_profit'] ?? 0;
$totalOpProfit    = $stats['total_op_profit'] ?? 0;

// ==========================================
// ترازنامه جامع مالی (کل زمان‌ها - بدون فیلتر)
// ==========================================
$financeStats = [
    'total_wallet' => 0,
    'active_credit' => 0,
    'total_credit' => 0,
    'active_emergency' => 0,
    'total_emergency' => 0,
    'total_deposits' => 0,
    'total_receipts' => 0,
    'total_manual' => 0,
    'total_bonus_given' => 0,
    'total_system_profit' => 0,
    'my_total_profit' => 0,
    'total_gb_sold' => 0,
    'total_provider_cost' => 0,
    'total_provider_paid' => 0,
    'provider_debt' => 0,
    'total_system_input' => 0,
    'real_cash_input' => 0
];

if ($isAdmin) {
    // ترازنامه شبکه
    $financeStats['total_wallet'] = $pdo->query("SELECT SUM(wallet_balance) FROM users WHERE role='operator'")->fetchColumn() ?: 0;
    $financeStats['active_credit'] = $pdo->query("SELECT SUM(credit_debt) FROM users WHERE role='operator'")->fetchColumn() ?: 0;
    $financeStats['active_emergency'] = $pdo->query("SELECT SUM(emergency_amount) FROM users WHERE role='operator'")->fetchColumn() ?: 0;
    
    $financeStats['total_credit'] = $pdo->query("SELECT SUM(amount) FROM wallet_logs WHERE type LIKE '%credit%'")->fetchColumn() ?: 0;
    $financeStats['total_emergency'] = $pdo->query("SELECT SUM(amount) FROM wallet_logs WHERE type LIKE '%emergency%'")->fetchColumn() ?: 0;
    $financeStats['total_bonus_given'] = $pdo->query("SELECT SUM(amount) FROM wallet_logs WHERE type LIKE '%bonus%'")->fetchColumn() ?: 0;
    
    $financeStats['total_receipts'] = $pdo->query("SELECT SUM(amount) FROM settlements WHERE status='approved'")->fetchColumn() ?: 0;
    $financeStats['total_manual'] = $pdo->query("SELECT SUM(amount) FROM wallet_logs WHERE type LIKE '%manual%'")->fetchColumn() ?: 0;
    $financeStats['total_deposits'] = $financeStats['total_receipts'] + $financeStats['total_manual'];

    $financeStats['total_system_profit'] = $pdo->query("SELECT SUM(admin_profit) FROM transactions")->fetchColumn() ?: 0;
    
    // ترازنامه تامین‌کننده سرور
    $financeStats['total_gb_sold'] = $pdo->query("SELECT SUM(volume) FROM transactions")->fetchColumn() ?: 0;
    $financeStats['total_provider_cost'] = $pdo->query("SELECT SUM(paid_amount - profit - admin_profit) FROM transactions")->fetchColumn() ?: 0;
    
    try {
        $financeStats['total_provider_paid'] = $pdo->query("SELECT SUM(paid_amount) FROM provider_settlements")->fetchColumn() ?: 0;
    } catch(Exception $e) {
        $financeStats['total_provider_paid'] = 0;
    }
    $financeStats['provider_debt'] = max(0, $financeStats['total_provider_cost'] - $financeStats['total_provider_paid']);

    // جریان نقدینگی کلان
    $totalSpentConfigs = $pdo->query("SELECT SUM(p.cost_price * t.volume) FROM transactions t JOIN plans p ON t.plan = p.plan_name")->fetchColumn() ?: 0;
    $financeStats['total_system_input'] = $financeStats['total_wallet'] + $totalSpentConfigs;
    $financeStats['total_manual_charges'] = $financeStats['total_system_input'] - $financeStats['total_receipts'] - $financeStats['active_credit'] - $financeStats['total_bonus_given'];
    $financeStats['real_cash_input'] = $financeStats['total_receipts'] + $financeStats['total_manual_charges'];

} else {
    // ترازنامه شخصی نماینده
    $stmtUserFin = $pdo->prepare("SELECT wallet_balance, credit_debt, emergency_amount FROM users WHERE id = ?");
    $stmtUserFin->execute([$userId]);
    $uFin = $stmtUserFin->fetch();
    
    $financeStats['total_wallet'] = $uFin['wallet_balance'] ?? 0;
    $financeStats['active_credit'] = $uFin['credit_debt'] ?? 0;
    $financeStats['active_emergency'] = $uFin['emergency_amount'] ?? 0;
    
    $stmtLogsFin = $pdo->prepare("SELECT type, SUM(amount) as sum_amt FROM wallet_logs WHERE user_id = ? GROUP BY type");
    $stmtLogsFin->execute([$userId]);
    $uLogs = $stmtLogsFin->fetchAll(PDO::FETCH_ASSOC);
    
    foreach($uLogs as $log) {
        $t = strtolower($log['type']);
        if(strpos($t, 'emergency') !== false) {
            $financeStats['total_emergency'] += $log['sum_amt'];
        } elseif(strpos($t, 'credit') !== false) {
            $financeStats['total_credit'] += $log['sum_amt'];
        } elseif(strpos($t, 'bonus') !== false) {
            $financeStats['total_bonus_given'] += $log['sum_amt'];
        } elseif(strpos($t, 'manual') !== false) {
            $financeStats['total_manual'] += $log['sum_amt'];
        }
    }

    $stmtReceipts = $pdo->prepare("SELECT SUM(amount) FROM settlements WHERE user_id = ? AND status='approved'");
    $stmtReceipts->execute([$userId]);
    $financeStats['total_receipts'] = $stmtReceipts->fetchColumn() ?: 0;
    $financeStats['total_deposits'] = $financeStats['total_receipts'] + $financeStats['total_manual'];
    
    $stmtMyProf = $pdo->prepare("SELECT SUM(profit) FROM transactions WHERE user_id = ?");
    $stmtMyProf->execute([$userId]);
    $financeStats['my_total_profit'] = $stmtMyProf->fetchColumn() ?: 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,
                    SUM(paid_amount) as daily_revenue
             FROM transactions t $whereSQL 
             GROUP BY date_shamsi ORDER BY date_shamsi ASC";
$stmtTrend = $pdo->prepare($sqlTrend);
$stmtTrend->execute($params);
$trendRows = $stmtTrend->fetchAll();

$trendLabels = [];
$trendDataProfit = [];
$trendDataCount = [];
$trendDataVolume = [];
$trendDataRevenue = [];

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'];
    $trendDataRevenue[] = $row['daily_revenue'];
}

$sqlPlanChart = "SELECT plan, COUNT(id) as count_sales FROM transactions t $whereSQL GROUP BY plan";
$stmtPlanChart = $pdo->prepare($sqlPlanChart);
$stmtPlanChart->execute($params);
$planRows = $stmtPlanChart->fetchAll();

$planLabels = [];
$planDataCount = [];
$planColors = ['#3b82f6', '#10b981', '#f59e0b', '#8b5cf6', '#ef4444', '#ec4899', '#14b8a6', '#64748b']; 
foreach($planRows as $row) {
    $planLabels[] = $row['plan'];
    $planDataCount[] = $row['count_sales'];
}

// ==========================================
// مانیتورینگ ۳۶۰ درجه عملکرد فروشندگان (وابسته به فیلتر زمانی)
// ==========================================
$operatorStats = [];
$opPlans = [];
$topCustomers = [];

if ($isAdmin) {
    // آماده‌سازی شروط اختصاصی برای Join تا نماینده‌ها با فیلتر زمانی هماهنگ شوند
    $opJoinConditions = [];
    $opParams = [];
    
    if (!empty($filter_start)) { $opJoinConditions[] = "t.date_shamsi >= :start"; $opParams[':start'] = $filter_start; }
    if (!empty($filter_end)) { $opJoinConditions[] = "t.date_shamsi <= :end"; $opParams[':end'] = $filter_end; }
    if (!empty($filter_plan)) { $opJoinConditions[] = "t.plan = :plan"; $opParams[':plan'] = $filter_plan; }
    
    $opJoinSQL = !empty($opJoinConditions) ? " AND " . implode(" AND ", $opJoinConditions) : "";
    
    $opWhereSQL = "WHERE u.role = 'operator'";
    if (!empty($filter_operator)) {
        $opWhereSQL .= " AND u.id = :op_id";
        $opParams[':op_id'] = $filter_operator;
    }

    $stmtOps = $pdo->prepare("
        SELECT u.id, u.username, u.fullname, u.wallet_balance, u.credit_debt,
               COUNT(t.id) as total_sales,
               COALESCE(SUM(t.volume), 0) as total_gb,
               COALESCE(SUM(t.profit), 0) as total_income
        FROM users u
        LEFT JOIN transactions t ON u.id = t.user_id $opJoinSQL
        $opWhereSQL
        GROUP BY u.id
        ORDER BY total_sales DESC
    ");
    $stmtOps->execute($opParams);
    $operatorStats = $stmtOps->fetchAll(PDO::FETCH_ASSOC);

    // استخراج ریز فروش پلن‌ها برای هر نماینده (مبتنی بر فیلتر)
    $planWhereConditions = [];
    if (!empty($filter_start)) $planWhereConditions[] = "date_shamsi >= :start";
    if (!empty($filter_end)) $planWhereConditions[] = "date_shamsi <= :end";
    if (!empty($filter_plan)) $planWhereConditions[] = "plan = :plan";
    if (!empty($filter_operator)) $planWhereConditions[] = "user_id = :op_id";
    $planWhereSQL = !empty($planWhereConditions) ? "WHERE " . implode(" AND ", $planWhereConditions) : "";

    $stmtPlans = $pdo->prepare("
        SELECT user_id, plan, COUNT(id) as count, SUM(volume) as gb
        FROM transactions
        $planWhereSQL
        GROUP BY user_id, plan
    ");
    $stmtPlans->execute($opParams);
    foreach ($stmtPlans->fetchAll() as $row) {
        $opPlans[$row['user_id']][] = $row;
    }
} else {
    // اصلاح خطای کریتیکال (جلوگیری از ترکیب پارامترهای ? و : در PDO)
    $cusWhere = $whereSQL . " AND t.customer_name != '' AND t.customer_name != '-'";
    $stmtTopCustomers = $pdo->prepare("
        SELECT customer_name, SUM(paid_amount) as total_paid, SUM(profit) as total_profit, COUNT(id) as buy_count 
        FROM transactions t 
        $cusWhere 
        GROUP BY customer_name 
        ORDER BY total_paid DESC 
        LIMIT 5
    ");
    $stmtTopCustomers->execute($params);
    $topCustomers = $stmtTopCustomers->fetchAll();
}

// ==========================================
// دیتا تیبل تراکنش‌ها
// ==========================================
$sqlDetails = "SELECT t.*, u.username as creator_username, u.fullname as creator_fullname, b.bank_name 
               FROM transactions t 
               LEFT JOIN users u ON t.user_id = u.id 
               LEFT JOIN banks b ON t.bank_id = b.id
               $whereSQL ORDER BY t.id DESC";
$stmtDetails = $pdo->prepare($sqlDetails);
$stmtDetails->execute($params);
$reportDetails = $stmtDetails->fetchAll();

require_once '../includes/header.php';
?>

<link rel="stylesheet" type="text/css" href="/vpnet-panel/assets/css/datatables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.dataTables.min.css">
<link rel="stylesheet" href="https://unpkg.com/persian-datepicker@1.2.0/dist/css/persian-datepicker.min.css"/>

<style>
    .dt-buttons .dt-button { background-color: #f3f4f6 !important; border: 1px solid #d1d5db !important; border-radius: 8px !important; color: #374151 !important; font-family: 'Vazirmatn', sans-serif !important; font-weight: bold !important; padding: 6px 12px !important; margin-left: 8px !important; transition: all 0.2s !important; }
    .dt-buttons .dt-button.buttons-excel { background-color: #ecfdf5 !important; border-color: #10b981 !important; color: #047857 !important; }
    .dt-buttons .dt-button.buttons-excel:hover { background-color: #10b981 !important; color: white !important; }
    .dt-buttons .dt-button.buttons-print { background-color: #eff6ff !important; border-color: #3b82f6 !important; color: #1d4ed8 !important; }
    .dt-buttons .dt-button.buttons-print:hover { background-color: #3b82f6 !important; color: white !important; }
    html.dark .dt-buttons .dt-button { background-color: #1e293b !important; border-color: #334155 !important; color: #cbd5e1 !important; }
    html.dark .dt-buttons .dt-button.buttons-excel { background-color: #064e3b !important; border-color: #065f46 !important; color: #34d399 !important; }
    html.dark .dt-buttons .dt-button.buttons-print { background-color: #1e3a8a !important; border-color: #1e40af !important; color: #60a5fa !important; }
    .dataTables_wrapper .dataTables_filter input { border: 2px solid #e5e7eb; border-radius: 12px; padding: 8px 16px; outline: none; margin-bottom: 10px; }
    html.dark .dataTables_wrapper .dataTables_filter input { background-color: #0f172a; color: #f8fafc; border-color: #334155; }
    .dataTables_wrapper .dataTables_length select { border: 2px solid #e5e7eb; border-radius: 10px; padding: 5px; outline: none; }
    html.dark .dataTables_wrapper .dataTables_length select { background-color: #0f172a; color: #f8fafc; border-color: #334155; }
    html.dark .dataTables_wrapper .dataTables_info { color: #94a3b8 !important; }
    html.dark .dataTables_wrapper .dataTables_paginate .paginate_button { color: #94a3b8 !important; border-color: #334155 !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; }
</style>

<div class="bg-gradient-to-r from-amber-600 to-orange-700 rounded-3xl p-6 md:p-8 mb-8 text-white flex flex-col md:flex-row justify-between items-center shadow-lg relative overflow-hidden">
    <div class="absolute -right-10 -top-10 opacity-10 text-9xl">📊</div>
    <div class="relative z-10 text-center md:text-right">
        <h1 class="text-2xl font-black text-gray-100 mb-2">هوش تجاری و گزارشات پیشرفته</h1>
        <p class="text-orange-200 text-sm font-bold">فیلتر، استخراج و بررسی دقیق جریان نقدینگی و عملکرد سیستم</p>
    </div>
</div>

<!-- ========================================== -->
<!-- جریان نقدینگی و ترازنامه جامع مالی -->
<!-- ========================================== -->
<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-emerald-500 relative overflow-hidden">
    <div class="absolute -left-10 -bottom-10 opacity-5 text-9xl">💎</div>
    
    <?php if($isAdmin): ?>
        <h2 class="text-xl font-black text-gray-800 dark:text-white mb-6 flex items-center gap-2 relative z-10">
            <span class="text-2xl">💰</span> گزارش جامع جریان نقدینگی (Cash Flow - کل زمان‌ها)
        </h2>
        <!-- باکس جریان نقدینگی اضافه شده از والت -->
        <div class="grid grid-cols-2 md:grid-cols-3 gap-4 mb-8 relative z-10">
            <div class="bg-gray-50 dark:bg-slate-700/50 p-4 rounded-2xl border border-gray-200 dark:border-slate-600 relative">
                <span class="text-[11px] font-bold text-gray-500 dark:text-gray-400 block mb-1">فیش‌های بانکی تایید شده</span>
                <span class="text-xl font-black text-gray-800 dark:text-gray-200" dir="ltr"><?php echo number_format($financeStats['total_receipts']); ?> <span class="text-[10px] font-normal">T</span></span>
                <div class="text-[10px] text-gray-400 mt-2">خرید از طریق ثبت فیش</div>
            </div>
            <div class="bg-gray-50 dark:bg-slate-700/50 p-4 rounded-2xl border border-gray-200 dark:border-slate-600 relative">
                <span class="text-[11px] font-bold text-gray-500 dark:text-gray-400 block mb-1">شارژهای دستی ادمین</span>
                <span class="text-xl font-black text-gray-800 dark:text-gray-200" dir="ltr"><?php echo number_format($financeStats['total_manual_charges']); ?> <span class="text-[10px] font-normal">T</span></span>
                <div class="text-[10px] text-gray-400 mt-2">افزایش موجودی بدون فیش</div>
            </div>
            <div class="bg-indigo-50 dark:bg-indigo-900/20 p-4 rounded-2xl border border-indigo-200 dark:border-indigo-800 relative">
                <span class="text-[11px] font-bold text-indigo-700 dark:text-indigo-400 block mb-1">هدایای تشویقی پرداختی</span>
                <span class="text-xl font-black text-indigo-700 dark:text-indigo-400" dir="ltr"><?php echo number_format($financeStats['total_bonus_given']); ?> <span class="text-[10px] font-normal">T</span></span>
                <div class="text-[10px] text-indigo-600 dark:text-indigo-500 mt-2 font-bold">بونوس رایگان واریز یکجا</div>
            </div>
            <div class="bg-emerald-50 dark:bg-emerald-900/20 p-4 rounded-2xl border border-emerald-200 dark:border-emerald-800 relative">
                <span class="text-[11px] font-bold text-emerald-700 dark:text-emerald-400 block mb-1">مجموع فیش و شارژ دستی</span>
                <span class="text-xl font-black text-emerald-700 dark:text-emerald-400" dir="ltr"><?php echo number_format($financeStats['real_cash_input']); ?> <span class="text-[10px] font-normal">T</span></span>
                <div class="text-[10px] text-emerald-600 dark:text-emerald-500 mt-2 font-bold">کل پول واقعی دریافت شده</div>
            </div>
            <div class="bg-rose-50 dark:bg-rose-900/20 p-4 rounded-2xl border border-rose-200 dark:border-rose-800 relative">
                <span class="text-[11px] font-bold text-rose-700 dark:text-rose-400 block mb-1">شارژ اعتباری (بدهی کاربران)</span>
                <span class="text-xl font-black text-rose-700 dark:text-rose-400" dir="ltr"><?php echo number_format($financeStats['active_credit']); ?> <span class="text-[10px] font-normal">T</span></span>
                <div class="text-[10px] text-rose-600 dark:text-rose-500 mt-2">اعتبار پرداخت نشده</div>
            </div>
            <div class="bg-gray-800 dark:bg-black p-4 rounded-2xl border border-gray-900 relative text-white shadow-lg">
                <span class="text-[11px] font-bold text-gray-400 block mb-1">مجموع کل جریان ورودی سیستم</span>
                <span class="text-2xl font-black text-amber-400" dir="ltr"><?php echo number_format($financeStats['total_system_input']); ?> <span class="text-[10px] font-normal">T</span></span>
                <div class="text-[10px] text-gray-400 mt-2">پول واقعی + اعتبار + هدیه</div>
            </div>
        </div>

        <div class="bg-gray-900 dark:bg-black p-6 rounded-2xl border border-gray-800 shadow-inner mb-6 flex flex-col md:flex-row justify-between gap-6 relative overflow-hidden text-white z-10">
            <div class="absolute -right-4 -top-4 opacity-10 text-7xl">📡</div>
            <div class="flex-1 relative z-10">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-cyan-400 font-bold text-sm">وضعیت حساب تامین‌کننده اصلی (سرور)</h3>
                    <a href="provider.php" class="bg-cyan-600 hover:bg-cyan-700 text-white text-[10px] px-3 py-1 rounded-lg font-bold transition">مدیریت حساب ←</a>
                </div>
                <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                    <div>
                        <span class="block text-[10px] text-gray-400 mb-1">کل حجم فروش رفته شبکه</span>
                        <span class="text-xl font-black text-gray-100"><?php echo number_format($financeStats['total_gb_sold']); ?> <span class="text-[10px] font-normal">GB</span></span>
                    </div>
                    <div>
                        <span class="block text-[10px] text-gray-400 mb-1">ارزش کل حجم (بدهی ثبت شده)</span>
                        <span class="text-xl font-black text-rose-400" dir="ltr"><?php echo number_format($financeStats['total_provider_cost']); ?> <span class="text-[10px] font-normal">T</span></span>
                    </div>
                    <div>
                        <span class="block text-[10px] text-gray-400 mb-1">مجموع پرداختی به سرور (تسویه)</span>
                        <span class="text-xl font-black text-emerald-400" dir="ltr"><?php echo number_format($financeStats['total_provider_paid']); ?> <span class="text-[10px] font-normal">T</span></span>
                    </div>
                    <div class="bg-gray-800 p-2 rounded-lg text-center border border-gray-700">
                        <span class="block text-[10px] text-gray-400 mb-1">بدهی باقیمانده به سرور</span>
                        <span class="text-xl font-black text-amber-400" dir="ltr"><?php echo number_format($financeStats['provider_debt']); ?> <span class="text-[10px] font-normal">T</span></span>
                    </div>
                </div>
            </div>
        </div>
    <?php else: ?>
        <h2 class="text-xl font-black text-gray-800 dark:text-white mb-6 flex items-center gap-2 relative z-10">
            <span class="text-2xl">💰</span> ترازنامه جامع مالی (کل زمان‌ها)
        </h2>
    <?php endif; ?>

    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 relative z-10">
        <?php if($isAdmin): ?>
            <div class="bg-blue-50 dark:bg-blue-900/20 p-5 rounded-2xl border border-blue-100 dark:border-blue-800 flex flex-col justify-center">
                <span class="block text-[10px] font-bold text-blue-600 dark:text-blue-400 mb-1">کل نقدینگی نمایندگان</span>
                <span class="text-xl font-black text-blue-700 dark:text-blue-300" dir="ltr"><?php echo number_format($financeStats['total_wallet']); ?> <span class="text-[10px] font-normal">T</span></span>
            </div>
            <div class="bg-amber-50 dark:bg-amber-900/20 p-5 rounded-2xl border border-amber-100 dark:border-amber-800 flex flex-col justify-between">
                <span class="block text-[10px] font-bold text-amber-600 dark:text-amber-400 mb-2">شارژ اضطراری شبکه</span>
                <div class="flex justify-between items-end">
                    <div>
                        <span class="block text-[9px] font-bold text-amber-500/80 mb-0.5">فعلی (تسویه نشده):</span>
                        <span class="text-xl font-black text-amber-700 dark:text-amber-300" dir="ltr"><?php echo number_format($financeStats['active_emergency']); ?> <span class="text-[10px] font-normal">T</span></span>
                    </div>
                    <div class="text-left border-r border-amber-200 dark:border-amber-700/50 pr-3">
                        <span class="block text-[9px] font-bold text-amber-500/80 mb-0.5">کل تاریخچه:</span>
                        <span class="text-sm font-bold text-amber-600 dark:text-amber-400" dir="ltr"><?php echo number_format($financeStats['total_emergency']); ?></span>
                    </div>
                </div>
            </div>
            <div class="bg-emerald-50 dark:bg-emerald-900/20 p-5 rounded-2xl border border-emerald-100 dark:border-emerald-800 shadow-inner flex flex-col justify-center lg:col-span-2">
                <span class="block text-[10px] font-bold text-emerald-600 dark:text-emerald-400 mb-1">سود خالص ادمین (خلق شده)</span>
                <span class="text-2xl font-black text-emerald-700 dark:text-emerald-300" dir="ltr"><?php echo number_format($financeStats['total_system_profit']); ?> <span class="text-[10px] font-normal">T</span></span>
            </div>
        <?php else: ?>
            <div class="bg-blue-50 dark:bg-blue-900/20 p-5 rounded-2xl border border-blue-100 dark:border-blue-800 flex flex-col justify-center">
                <span class="block text-[10px] font-bold text-blue-600 dark:text-blue-400 mb-1">موجودی فعلی (نقدینگی)</span>
                <span class="text-xl font-black text-blue-700 dark:text-blue-300" dir="ltr"><?php echo number_format($financeStats['total_wallet']); ?> <span class="text-[10px] font-normal">T</span></span>
            </div>
            <div class="bg-rose-50 dark:bg-rose-900/20 p-5 rounded-2xl border border-rose-100 dark:border-rose-800 flex flex-col justify-between">
                <span class="block text-[10px] font-bold text-rose-600 dark:text-rose-400 mb-2">بدهی اعتباری به سیستم</span>
                <div class="flex justify-between items-end">
                    <div>
                        <span class="block text-[9px] font-bold text-rose-500/80 mb-0.5">فعلی (تسویه نشده):</span>
                        <span class="text-xl font-black text-rose-700 dark:text-rose-300" dir="ltr"><?php echo number_format($financeStats['active_credit']); ?> <span class="text-[10px] font-normal">T</span></span>
                    </div>
                    <div class="text-left border-r border-rose-200 dark:border-rose-700/50 pr-3">
                        <span class="block text-[9px] font-bold text-rose-500/80 mb-0.5">کل تاریخچه:</span>
                        <span class="text-sm font-bold text-rose-600 dark:text-rose-400" dir="ltr"><?php echo number_format($financeStats['total_credit']); ?></span>
                    </div>
                </div>
            </div>
            <div class="bg-amber-50 dark:bg-amber-900/20 p-5 rounded-2xl border border-amber-100 dark:border-amber-800 flex flex-col justify-between">
                <span class="block text-[10px] font-bold text-amber-600 dark:text-amber-400 mb-2">شارژ اضطراری دریافت شده</span>
                <div class="flex justify-between items-end">
                    <div>
                        <span class="block text-[9px] font-bold text-amber-500/80 mb-0.5">فعلی (تسویه نشده):</span>
                        <span class="text-xl font-black text-amber-700 dark:text-amber-300" dir="ltr"><?php echo number_format($financeStats['active_emergency']); ?> <span class="text-[10px] font-normal">T</span></span>
                    </div>
                    <div class="text-left border-r border-amber-200 dark:border-amber-700/50 pr-3">
                        <span class="block text-[9px] font-bold text-amber-500/80 mb-0.5">کل تاریخچه:</span>
                        <span class="text-sm font-bold text-amber-600 dark:text-amber-400" dir="ltr"><?php echo number_format($financeStats['total_emergency']); ?></span>
                    </div>
                </div>
            </div>
            <div class="bg-emerald-50 dark:bg-emerald-900/20 p-5 rounded-2xl border border-emerald-100 dark:border-emerald-800 shadow-inner flex flex-col justify-center">
                <span class="block text-[10px] font-bold text-emerald-600 dark:text-emerald-400 mb-1">سود خالص شما (تاریخچه)</span>
                <span class="text-2xl font-black text-emerald-700 dark:text-emerald-300" dir="ltr"><?php echo number_format($financeStats['my_total_profit']); ?> <span class="text-[10px] font-normal">T</span></span>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- ========================================== -->
<!-- پنل فیلتر پیشرفته -->
<!-- ========================================== -->
<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 relative overflow-hidden">
    <div class="absolute right-0 top-0 w-2 h-full bg-blue-500"></div>
    <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6 border-b border-gray-100 dark:border-slate-700 pb-4 pl-2 gap-4">
        <h2 class="text-lg font-bold text-gray-800 dark:text-white flex items-center gap-2">
            <svg class="w-5 h-5 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z"></path></svg>
            فیلتر پیشرفته آمار و گزارشات پایین
        </h2>
        <div class="flex flex-wrap gap-2">
            <button type="button" onclick="setQuickDate('today')" class="text-xs bg-gray-100 dark:bg-slate-700 text-gray-600 dark:text-gray-300 hover:bg-blue-100 hover:text-blue-600 dark:hover:bg-blue-900/50 dark:hover:text-blue-400 px-3 py-1.5 rounded-lg font-bold transition">امروز</button>
            <button type="button" onclick="setQuickDate('yesterday')" class="text-xs bg-gray-100 dark:bg-slate-700 text-gray-600 dark:text-gray-300 hover:bg-blue-100 hover:text-blue-600 dark:hover:bg-blue-900/50 dark:hover:text-blue-400 px-3 py-1.5 rounded-lg font-bold transition">دیروز</button>
            <button type="button" onclick="setQuickDate('week')" class="text-xs bg-gray-100 dark:bg-slate-700 text-gray-600 dark:text-gray-300 hover:bg-blue-100 hover:text-blue-600 dark:hover:bg-blue-900/50 dark:hover:text-blue-400 px-3 py-1.5 rounded-lg font-bold transition">۷ روز اخیر</button>
            <button type="button" onclick="setQuickDate('month')" class="text-xs bg-gray-100 dark:bg-slate-700 text-gray-600 dark:text-gray-300 hover:bg-blue-100 hover:text-blue-600 dark:hover:bg-blue-900/50 dark:hover:text-blue-400 px-3 py-1.5 rounded-lg font-bold transition">۳۰ روز اخیر</button>
            <?php if(!empty($_GET)): ?>
                <a href="reports.php" class="text-xs bg-red-50 dark:bg-red-900/30 text-red-600 dark:text-red-400 px-3 py-1.5 rounded-lg font-bold hover:bg-red-100 dark:hover:bg-red-900/50 transition border border-red-200 dark:border-red-800">✕ لغو فیلترها</a>
            <?php endif; ?>
        </div>
    </div>

    <form method="GET" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4 items-end mb-8 pl-2">
        <div class="relative">
            <label class="block text-xs font-bold text-gray-500 dark:text-gray-400 mb-2">از تاریخ (شمسی)</label>
            <input type="text" id="start_date_picker" class="w-full border-2 border-gray-200 dark:border-slate-600 rounded-xl p-3 pr-10 bg-white dark:bg-slate-700 text-sm 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 class="absolute right-3 top-10 opacity-50 pointer-events-none">📅</div>
        </div>
        <div class="relative">
            <label class="block text-xs font-bold text-gray-500 dark:text-gray-400 mb-2">تا تاریخ (شمسی)</label>
            <input type="text" id="end_date_picker" class="w-full border-2 border-gray-200 dark:border-slate-600 rounded-xl p-3 pr-10 bg-white dark:bg-slate-700 text-sm 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 class="absolute right-3 top-10 opacity-50 pointer-events-none">📅</div>
        </div>
        <div>
            <label class="block text-xs font-bold text-gray-500 dark:text-gray-400 mb-2">طرح فروش</label>
            <select name="plan" class="w-full border-2 border-gray-200 dark:border-slate-600 rounded-xl p-3 bg-white dark:bg-slate-700 text-sm focus:border-blue-500 outline-none dark:text-white cursor-pointer">
                <option value="">همه طرح‌ها</option>
                <?php foreach($plansList as $pName): ?>
                    <option value="<?php echo $pName; ?>" <?php if($filter_plan == $pName) echo 'selected'; ?>><?php echo $pName; ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <?php if($isAdmin): ?>
        <div>
            <label class="block text-xs font-bold text-gray-500 dark:text-gray-400 mb-2">اپراتور</label>
            <select name="operator_id" class="w-full border-2 border-gray-200 dark:border-slate-600 rounded-xl p-3 bg-white dark:bg-slate-700 text-sm focus:border-blue-500 outline-none dark:text-white cursor-pointer">
                <option value="">همه اپراتورها</option>
                <?php foreach($operatorsList as $op): 
                    $displayName = !empty($op['fullname']) ? htmlspecialchars($op['fullname']) : htmlspecialchars($op['username']);
                ?>
                    <option value="<?php echo $op['id']; ?>" <?php if($filter_operator == $op['id']) echo 'selected'; ?>><?php echo $displayName; ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <?php endif; ?>
        <div>
            <button type="submit" class="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-3.5 rounded-xl transition shadow-lg text-sm flex items-center justify-center gap-2">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg>
                اجرای تحلیل
            </button>
        </div>
    </form>

    <div class="grid grid-cols-2 md:grid-cols-4 gap-4 bg-gray-50 dark:bg-slate-700/50 p-4 rounded-2xl border border-gray-100 dark:border-slate-600 ml-2 relative">
        <div class="p-3">
            <span class="block text-[10px] text-gray-400 font-bold uppercase mb-1">تعداد فروش (بازه انتخابی)</span>
            <span class="text-xl font-black text-gray-800 dark:text-white"><?php echo number_format($totalCount); ?></span>
        </div>
        <div class="p-3 border-r border-gray-200 dark:border-slate-600">
            <span class="block text-[10px] text-gray-400 font-bold uppercase mb-1">ارزش کل فروش (بازه انتخابی)</span>
            <span class="text-xl font-black text-blue-600 dark:text-blue-400"><?php echo number_format($totalRevenue); ?></span>
        </div>
        <div class="p-3 border-r border-gray-200 dark:border-slate-600">
            <span class="block text-[10px] text-gray-400 font-bold uppercase mb-1">سود اپراتور (بازه انتخابی)</span>
            <span class="text-xl font-black text-green-600 dark:text-emerald-400"><?php echo number_format($totalOpProfit); ?></span>
        </div>
        <?php if($isAdmin): ?>
        <div class="p-3 border-r border-gray-200 dark:border-slate-600 bg-purple-50 dark:bg-purple-900/10 rounded-xl border border-purple-100 dark:border-purple-800/50">
            <span class="block text-[10px] text-purple-600 dark:text-purple-400 font-bold uppercase mb-1">سود خالص ادمین (بازه انتخابی)</span>
            <span class="text-xl font-black text-purple-600 dark:text-purple-500"><?php echo number_format($totalAdminProfit); ?></span>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- ========================================== -->
<!-- تحلیل‌های هوش تجاری (BI) - نمودار ۴ محوره -->
<!-- ========================================== -->
<div class="grid grid-cols-1 lg:grid-cols-3 gap-8 mb-8">
    <div class="lg:col-span-2 bg-white dark:bg-slate-800 rounded-3xl shadow-sm border border-gray-100 dark:border-slate-700 p-8">
        <div class="flex justify-between items-center mb-6">
            <h2 class="text-lg font-bold text-gray-800 dark:text-white flex items-center gap-2">
                <span class="w-2 h-6 bg-blue-600 rounded-full"></span> نمودار جامع جریان نقدینگی و عملکرد فروش
            </h2>
            <span class="text-[10px] bg-blue-50 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400 px-2 py-1 rounded font-bold">بازه انتخابی</span>
        </div>
        <?php if(empty($trendLabels)): ?>
            <div class="py-20 text-center text-gray-400 font-bold">داده‌ای برای ترسیم نمودار در این بازه وجود ندارد.</div>
        <?php else: ?>
            <div style="position: relative; height: 300px; width: 100%;">
                <canvas id="trendChart"></canvas>
            </div>
        <?php endif; ?>
    </div>

    <div class="bg-white dark:bg-slate-800 rounded-3xl shadow-sm border border-gray-100 dark:border-slate-700 p-8">
        <div class="flex justify-between items-center mb-6">
            <h2 class="text-lg font-bold text-gray-800 dark:text-white flex items-center gap-2">
                <span class="w-2 h-6 bg-amber-500 rounded-full"></span> سهم فروش طرح‌ها
            </h2>
            <span class="text-[10px] bg-amber-50 text-amber-600 dark:bg-amber-900/30 dark:text-amber-400 px-2 py-1 rounded font-bold">بازه انتخابی</span>
        </div>
        <div style="position: relative; height: 250px; width: 100%;">
            <canvas id="planChart"></canvas>
        </div>
    </div>
</div>

<!-- ========================================== -->
<!-- مانیتورینگ ۳۶۰ درجه عملکرد فروشندگان -->
<!-- ========================================== -->
<?php if($isAdmin): ?>
<div class="mb-8">
    <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
        <h2 class="text-xl font-black text-gray-800 dark:text-white flex items-center gap-2">
            <span class="text-2xl">👥</span> مانیتورینگ جامع عملکرد فروشندگان
        </h2>
        <span class="text-xs bg-gray-100 text-gray-600 dark:bg-slate-700 dark:text-gray-300 px-3 py-1.5 rounded-lg font-bold">بر اساس بازه و فیلترهای انتخابی بالا</span>
    </div>
    
    <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
        <?php foreach($operatorStats as $op): 
            $opName = !empty($op['fullname']) ? htmlspecialchars($op['fullname']) : htmlspecialchars($op['username']);
            $walletColor = $op['wallet_balance'] >= 0 ? 'text-emerald-600 dark:text-emerald-400' : 'text-rose-600 dark:text-rose-400';
            $debtColor = $op['credit_debt'] > 0 ? 'text-rose-600 dark:text-rose-400' : 'text-gray-400 dark:text-gray-500';
        ?>
        <div class="bg-white dark:bg-slate-800 rounded-3xl p-6 shadow-sm border border-gray-100 dark:border-slate-700 transition hover:shadow-md hover:border-blue-300 dark:hover:border-blue-700">
            <!-- هدر کارت نماینده -->
            <div class="flex justify-between items-center mb-5 pb-4 border-b border-gray-100 dark:border-slate-700">
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 rounded-full bg-blue-100 dark:bg-blue-900/50 flex items-center justify-center text-blue-600 dark:text-blue-400 text-lg">👤</div>
                    <div>
                        <h3 class="font-black text-gray-800 dark:text-white"><?php echo $opName; ?></h3>
                        <span class="text-[10px] text-gray-400 font-bold tracking-wider">کد سیستمی: <?php echo $op['id']; ?></span>
                    </div>
                </div>
            </div>

            <!-- شاخص‌های مالی (موجودی / بدهی - کل زمان‌ها) -->
            <div class="grid grid-cols-2 gap-3 mb-5">
                <div class="bg-gray-50 dark:bg-slate-700/50 p-3 rounded-2xl border border-gray-100 dark:border-slate-600">
                    <span class="block text-[10px] font-bold text-gray-500 dark:text-gray-400 mb-1">موجودی پنل (لحظه‌ای)</span>
                    <span class="font-black text-sm <?php echo $walletColor; ?>" dir="ltr"><?php echo number_format($op['wallet_balance']); ?> <span class="text-[9px] font-normal">T</span></span>
                </div>
                <div class="bg-gray-50 dark:bg-slate-700/50 p-3 rounded-2xl border border-gray-100 dark:border-slate-600">
                    <span class="block text-[10px] font-bold text-gray-500 dark:text-gray-400 mb-1">بدهی ثبت شده (لحظه‌ای)</span>
                    <span class="font-black text-sm <?php echo $debtColor; ?>" dir="ltr"><?php echo number_format($op['credit_debt']); ?> <span class="text-[9px] font-normal">T</span></span>
                </div>
            </div>

            <!-- شاخص‌های فروش (بازه انتخابی) -->
            <div class="flex justify-between items-center mb-5 bg-blue-50/50 dark:bg-blue-900/10 p-3 rounded-xl border border-blue-100/50 dark:border-blue-800/30">
                <div>
                    <span class="block text-[10px] font-bold text-gray-500 dark:text-gray-400">درآمد نماینده (بازه)</span>
                    <span class="font-black text-blue-600 dark:text-blue-400 text-lg" dir="ltr"><?php echo number_format($op['total_income']); ?> <span class="text-[10px] font-normal">T</span></span>
                </div>
                <div class="text-left">
                    <div class="text-xs font-bold text-gray-700 dark:text-gray-300"><span class="text-gray-400">فروش بازه:</span> <?php echo number_format($op['total_sales']); ?> اکانت</div>
                    <div class="text-xs font-bold text-gray-700 dark:text-gray-300 mt-1"><span class="text-gray-400">حجم بازه:</span> <?php echo number_format($op['total_gb']); ?> گیگ</div>
                </div>
            </div>

            <!-- تفکیک پلن‌های فروخته شده (بازه انتخابی) -->
            <div>
                <span class="block text-[10px] font-bold text-gray-500 dark:text-gray-400 mb-2">ریز فروش طرح‌ها (بازه):</span>
                <div class="flex flex-wrap gap-2 max-h-24 overflow-y-auto custom-scrollbar">
                    <?php if(!empty($opPlans[$op['id']])): foreach($opPlans[$op['id']] as $p): ?>
                        <div class="bg-gray-100 dark:bg-slate-700 text-gray-700 dark:text-gray-300 text-[10px] font-bold px-2.5 py-1.5 rounded-lg border border-gray-200 dark:border-slate-600 flex items-center gap-1.5">
                            <span class="text-blue-500"><?php echo htmlspecialchars($p['plan']); ?></span>
                            <span class="bg-white dark:bg-slate-800 px-1.5 rounded text-gray-500"><?php echo $p['count']; ?> عدد / <?php echo $p['gb']; ?>G</span>
                        </div>
                    <?php endforeach; else: ?>
                        <span class="text-xs text-gray-400">خریدی در این بازه ثبت نشده است.</span>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </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-8 mb-8">
    <div class="flex justify-between items-center mb-6">
        <h2 class="text-lg font-bold text-gray-800 dark:text-white flex items-center gap-2">
            <span class="w-2 h-6 bg-amber-500 rounded-full"></span> باشگاه مشتریان وفادار
        </h2>
        <span class="text-[10px] bg-amber-50 text-amber-600 dark:bg-amber-900/30 dark:text-amber-400 px-2 py-1 rounded font-bold">بازه انتخابی</span>
    </div>
    <div class="overflow-x-auto">
        <table class="w-full text-sm text-right">
            <thead class="text-gray-400 dark:text-gray-500 text-xs uppercase bg-gray-50 dark:bg-slate-700/50">
                <tr>
                    <th class="px-4 py-3 rounded-tr-lg">نام مشتری</th>
                    <th class="px-4 py-3">دفعات خرید</th>
                    <th class="px-4 py-3 rounded-tl-lg">مجموع خرید (تومان)</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-gray-100 dark:divide-slate-700 text-gray-700 dark:text-gray-300">
                <?php if(empty($topCustomers)): ?>
                    <tr><td colspan="3" class="px-4 py-6 text-center text-gray-400">مشتری نام‌داری در این بازه یافت نشد.</td></tr>
                <?php else: foreach($topCustomers as $idx => $cus): ?>
                <tr class="hover:bg-gray-50 dark:hover:bg-slate-700/30">
                    <td class="px-4 py-3 font-bold"><?php echo ($idx===0)?'⭐ ':''; ?><?php echo htmlspecialchars($cus['customer_name']); ?></td>
                    <td class="px-4 py-3 font-mono" dir="ltr"><?php echo $cus['buy_count']; ?></td>
                    <td class="px-4 py-3 font-mono font-black text-amber-600 dark:text-amber-400" dir="ltr"><?php echo number_format($cus['total_paid']); ?></td>
                </tr>
                <?php endforeach; endif;?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<!-- ========================================== -->
<!-- جدول ریز تراکنش‌ها -->
<!-- ========================================== -->
<div class="bg-white dark:bg-slate-800 rounded-3xl shadow-sm border border-gray-100 dark:border-slate-700 p-8 mb-12">
    <div class="flex justify-between items-center mb-6">
        <h2 class="text-lg font-bold text-gray-800 dark:text-white flex items-center gap-2">
            <span class="w-2 h-6 bg-gray-800 dark:bg-white rounded-full"></span> دیتابیس تراکنش‌ها (قابل خروجی‌گیری)
        </h2>
        <span class="text-[10px] bg-gray-100 text-gray-600 dark:bg-slate-700 dark:text-gray-300 px-2 py-1 rounded font-bold">بازه انتخابی</span>
    </div>
    <div class="overflow-x-auto">
        <table id="reportTable" class="w-full text-sm text-gray-500 dark:text-gray-400">
            <thead class="bg-gray-50 dark:bg-slate-700/50 text-gray-700 dark:text-gray-300">
                <tr>
                    <th class="px-4 py-3 rounded-tr-xl text-right">تاریخ و ساعت</th>
                    <th class="px-4 py-3 text-right">مشتری</th>
                    <th class="px-4 py-3 text-right">اکانت</th>
                    <th class="px-4 py-3 text-right">طرح / حجم</th>
                    <th class="px-4 py-3 text-right">واریزی (تومان)</th>
                    <?php if($isAdmin): ?>
                        <th class="px-4 py-3 text-green-700 dark:text-green-400 text-right">سود نماینده</th>
                        <th class="px-4 py-3 text-purple-700 dark:text-purple-400 text-right">سود ادمین</th>
                    <?php else: ?>
                        <th class="px-4 py-3 text-green-700 dark:text-green-400 text-right">سود شما</th>
                    <?php endif; ?>
                    <th class="px-4 py-3 text-right">حساب واریزی</th>
                    <?php if($isAdmin): ?><th class="px-4 py-3 rounded-tl-xl text-right">اپراتور</th><?php endif; ?>
                </tr>
            </thead>
            <tbody class="divide-y divide-gray-100 dark:divide-slate-700">
                <?php foreach($reportDetails as $tx): 
                    $creatorDisplayName = !empty($tx['creator_fullname']) ? htmlspecialchars($tx['creator_fullname']) : htmlspecialchars($tx['creator_username']);
                    $time = date('H:i', strtotime($tx['created_at']));
                ?>
                <tr class="hover:bg-gray-50 dark:hover:bg-slate-700/30 transition text-right">
                    <td class="px-4 py-4" dir="ltr">
                        <span class="font-bold text-gray-800 dark:text-gray-200"><?php echo $tx['date_shamsi']; ?></span>
                        <span class="text-xs text-gray-400 ml-1"><?php echo $time; ?></span>
                    </td>
                    <td class="px-4 py-4 font-bold text-gray-800 dark:text-gray-200"><?php echo htmlspecialchars($tx['customer_name']); ?></td>
                    <td class="px-4 py-4 font-mono text-blue-600 dark:text-blue-400" dir="ltr"><?php echo htmlspecialchars($tx['account_username']); ?></td>
                    <td class="px-4 py-4 font-bold"><?php echo $tx['plan']; ?> <span class="text-xs opacity-70 font-normal">(<?php echo $tx['volume']; ?>G)</span></td>
                    <td class="px-4 py-4 font-bold text-gray-800 dark:text-white"><?php echo number_format($tx['paid_amount']); ?></td>
                    
                    <?php if($isAdmin): ?>
                        <td class="px-4 py-4 font-black <?php echo ($tx['profit'] < 0) ? 'text-red-500' : 'text-green-500'; ?>"><?php echo number_format($tx['profit']); ?></td>
                        <td class="px-4 py-4 font-black <?php echo ($tx['admin_profit'] < 0) ? 'text-red-500' : 'text-purple-500'; ?>"><?php echo number_format($tx['admin_profit']); ?></td>
                    <?php else: ?>
                        <td class="px-4 py-4 font-black <?php echo ($tx['profit'] < 0) ? 'text-red-500' : 'text-green-500'; ?>"><?php echo number_format($tx['profit']); ?></td>
                    <?php endif; ?>

                    <td class="px-4 py-4 text-xs"><?php echo !empty($tx['bank_name']) ? htmlspecialchars($tx['bank_name']) : '<span class="opacity-50">-</span>'; ?></td>
                    <?php if($isAdmin): ?><td class="px-4 py-4 text-xs font-bold text-gray-600 dark:text-gray-300"><?php echo $creatorDisplayName; ?></td><?php endif; ?>
                </tr>
                <?php endforeach; ?>
            </tbody>
            <tfoot class="bg-gray-50 dark:bg-slate-700/50 border-t-2 border-gray-200 dark:border-slate-600">
                <tr class="text-right">
                    <th colspan="4" class="px-4 py-4 text-left font-black text-gray-800 dark:text-white">مجموع کل در این صفحه:</th>
                    <th class="px-4 py-4 font-mono font-black text-emerald-700 dark:text-emerald-400 text-lg" id="footer-report-paid" dir="ltr">0</th>
                    
                    <?php if($isAdmin): ?>
                        <th class="px-4 py-4 font-mono font-black text-green-700 dark:text-green-400 text-lg" id="footer-report-profit-op" dir="ltr">0</th>
                        <th class="px-4 py-4 font-mono font-black text-purple-700 dark:text-purple-400 text-lg" id="footer-report-profit-admin" dir="ltr">0</th>
                    <?php else: ?>
                        <th class="px-4 py-4 font-mono font-black text-green-700 dark:text-green-400 text-lg" id="footer-report-profit" dir="ltr">0</th>
                    <?php endif; ?>

                    <th></th>
                    <?php if($isAdmin): ?><th></th><?php endif; ?>
                </tr>
            </tfoot>
        </table>
    </div>
</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="/vpnet-panel/assets/js/jquery.dataTables.min.js"></script>
<script src="/vpnet-panel/assets/js/dataTables.buttons.min.js"></script>
<script src="/vpnet-panel/assets/js/jszip.min.js"></script>
<script src="/vpnet-panel/assets/js/buttons.html5.min.js"></script>
<script src="/vpnet-panel/assets/js/buttons.print.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,
            observer: 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); }
    });

    function setQuickDate(range) {
        const pd = new persianDate();
        let startStr = '', endStr = '';

        if (range === 'today') {
            startStr = pd.format('YYYY/MM/DD');
            endStr = pd.format('YYYY/MM/DD');
        } else if (range === 'yesterday') {
            let yd = pd.subtract('days', 1);
            startStr = yd.format('YYYY/MM/DD');
            endStr = yd.format('YYYY/MM/DD');
        } else if (range === 'week') {
            let wS = pd.subtract('days', 7);
            startStr = wS.format('YYYY/MM/DD');
            endStr = new persianDate().format('YYYY/MM/DD');
        } else if (range === 'month') {
            let mS = pd.subtract('days', 30);
            startStr = mS.format('YYYY/MM/DD');
            endStr = new persianDate().format('YYYY/MM/DD');
        }

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

    $(document).ready(function() {
        $('#reportTable').DataTable({
            destroy: true, 
            dom: '<"flex flex-col md:flex-row justify-between items-center mb-4 gap-4"<"flex items-center gap-4"lB>f>rt<"flex flex-col md:flex-row justify-between items-center mt-4 gap-4"ip>',
            buttons: [
                { extend: 'excelHtml5', text: '📥 دانلود Excel', className: 'btn-export' },
                { 
                    extend: 'print', 
                    text: '🖨️ چاپ / PDF', 
                    className: 'btn-export',
                    title: 'گزارش مالی هوشمند VPNet - تاریخ: <?php echo getTodayShamsi(); ?>',
                    customize: function ( win ) {
                        $(win.document.body).css( 'direction', 'rtl' ).css('font-family', 'Vazirmatn');
                        $(win.document.body).find( 'table' ).addClass( 'compact' ).css( 'font-size', '12px' );
                    }
                }
            ],
            language: {
                "sEmptyTable": "تراکنشی برای این فیلتر یافت نشد",
                "sSearch": "جستجو سریع در دیتا:",
                "sInfo": "نمایش _START_ تا _END_ از _TOTAL_ رکورد",
                "oPaginate": { "sNext": "بعدی", "sPrevious": "قبلی" },
                "sLengthMenu": "نمایش _MENU_ سطر"
            },
            order: [],
            pageLength: 25,
            footerCallback: function ( row, data, start, end, display ) {
                var api = this.api(), data;
                var intVal = function ( i ) { return typeof i === 'string' ? i.replace(/[\$,]/g, '')*1 : typeof i === 'number' ? i : 0; };
                
                var pageTotalPaid = api.column( 4, { page: 'current'} ).data().reduce( function (a, b) { return intVal(a) + intVal(b); }, 0 );
                $( '#footer-report-paid' ).html(pageTotalPaid.toLocaleString('en-US'));

                <?php if($isAdmin): ?>
                    var pageTotalProfitOp = api.column( 5, { page: 'current'} ).data().reduce( function (a, b) { return intVal(a) + intVal(b); }, 0 );
                    var pageTotalProfitAdmin = api.column( 6, { page: 'current'} ).data().reduce( function (a, b) { return intVal(a) + intVal(b); }, 0 );
                    $( '#footer-report-profit-op' ).html(pageTotalProfitOp.toLocaleString('en-US'));
                    $( '#footer-report-profit-admin' ).html(pageTotalProfitAdmin.toLocaleString('en-US'));
                <?php else: ?>
                    var pageTotalProfit = api.column( 5, { page: 'current'} ).data().reduce( function (a, b) { return intVal(a) + intVal(b); }, 0 );
                    $( '#footer-report-profit' ).html(pageTotalProfit.toLocaleString('en-US'));
                <?php endif; ?>
            }
        });
    });

    Chart.defaults.font.family = 'Vazirmatn';
    Chart.defaults.color = document.documentElement.classList.contains('dark') ? '#94a3b8' : '#64748b';
    
    <?php if(!empty($trendLabels)): ?>
    const ctxTrend = document.getElementById('trendChart').getContext('2d');
    new Chart(ctxTrend, {
        type: 'bar',
        data: {
            labels: <?php echo json_encode($trendLabels); ?>,
            datasets: [
                {
                    label: 'ارزش کل فروش (T)',
                    data: <?php echo json_encode($trendDataRevenue); ?>,
                    backgroundColor: 'rgba(59, 130, 246, 0.8)', // blue-500
                    borderRadius: 6,
                    yAxisID: 'y'
                },
                {
                    label: 'سود خالص (T)',
                    data: <?php echo json_encode($trendDataProfit); ?>,
                    backgroundColor: 'rgba(16, 185, 129, 0.8)', // emerald-500
                    borderRadius: 6,
                    yAxisID: 'y'
                },
                {
                    label: 'حجم مصرفی (GB)',
                    data: <?php echo json_encode($trendDataVolume); ?>,
                    type: 'line',
                    borderColor: '#8b5cf6', // violet-500
                    borderWidth: 3,
                    pointBackgroundColor: '#fff',
                    pointBorderWidth: 2,
                    tension: 0.4,
                    yAxisID: 'y1'
                },
                {
                    label: 'تعداد اکانت',
                    data: <?php echo json_encode($trendDataCount); ?>,
                    type: 'line',
                    borderColor: '#f59e0b', // amber-500
                    borderWidth: 3,
                    pointBackgroundColor: '#fff',
                    pointBorderWidth: 2,
                    tension: 0.4,
                    yAxisID: 'y1'
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: { mode: 'index', intersect: false },
            plugins: { legend: { position: 'top', align: 'end' } },
            scales: {
                y: { 
                    type: 'linear', 
                    display: true, 
                    position: 'left', 
                    grid: { color: 'rgba(156, 163, 175, 0.1)' } 
                },
                y1: { 
                    type: 'linear', 
                    display: true, 
                    position: 'right', 
                    grid: { display: false } 
                },
                x: { grid: { display: false } }
            }
        }
    });
    <?php endif; ?>

    const ctxPlan = document.getElementById('planChart').getContext('2d');
    new Chart(ctxPlan, {
        type: 'doughnut',
        data: {
            labels: <?php echo json_encode($planLabels); ?>,
            datasets: [{
                data: <?php echo json_encode($planDataCount); ?>,
                backgroundColor: <?php echo json_encode($planColors); ?>,
                borderWidth: 0,
                cutout: '75%'
            }]
        },
        options: { plugins: { legend: { position: 'bottom' } }, maintainAspectRatio: false }
    });
</script>

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