<?php
// modules/subscriptions/widgets/stats_and_filters.php
if (basename($_SERVER['PHP_SELF']) == 'stats_and_filters.php') { die('Access Denied'); }

$current_date_filter = $_GET['date_filter'] ?? '';
$current_start_date  = $_GET['start_date'] ?? '';
$current_end_date    = $_GET['end_date'] ?? '';
$filter_operator     = $_GET['operator_id'] ?? '';

// محاسبات آماری دقیق
$statTotalSubs   = count($subscriptions ?? []);
$statTotalSales  = 0;
$statTotalProfit = 0;

if (!empty($subscriptions)) {
    foreach($subscriptions as $s) {
        $statTotalSales  += (int)($s['total_paid'] ?? 0);
        $statTotalProfit += $isAdmin ? (int)($s['total_admin_profit'] ?? 0) : (int)($s['total_profit'] ?? 0);
    }
}

if ($isAdmin) {
    $operatorsList = $pdo->query("SELECT id, username, fullname FROM users WHERE role != 'admin' ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
}
$serversList = $pdo->query("SELECT * FROM servers ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="bg-white dark:bg-slate-800 rounded-3xl p-6 md:p-8 mb-6 flex flex-col md:flex-row justify-between items-center shadow-sm border border-gray-100 dark:border-slate-700 relative overflow-hidden">
    <div class="absolute -right-5 -top-5 opacity-[0.03] dark:opacity-[0.05] text-9xl pointer-events-none">🌐</div>
    <div class="relative z-10 text-center md:text-right mb-4 md:mb-0">
        <h1 class="text-2xl font-black text-gray-900 dark:text-white tracking-tight flex items-center gap-2">مدیریت کاربران و اشتراک‌ها</h1>
        <p class="text-gray-500 dark:text-gray-400 text-xs font-bold mt-1">کنترل جامع لیست کاربران، وضعیت لایو و فیلترهای پیشرفته</p>
    </div>
</div>

<div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
    <div class="bg-white dark:bg-slate-800 rounded-3xl border border-gray-100 dark:border-slate-700 p-5 flex justify-between items-center shadow-sm hover:shadow-md transition">
        <span class="text-xs font-bold text-gray-500 flex items-center gap-2"><span class="w-2.5 h-2.5 rounded-full bg-blue-500"></span> تعداد اشتراک‌ها</span>
        <span class="text-3xl font-black text-gray-800 dark:text-slate-100"><?php echo number_format($statTotalSubs); ?></span>
    </div>
    <div class="bg-white dark:bg-slate-800 rounded-3xl border border-gray-100 dark:border-slate-700 p-5 flex justify-between items-center shadow-sm hover:shadow-md transition">
        <span class="text-xs font-bold text-gray-500 flex items-center gap-2"><span class="w-2.5 h-2.5 rounded-full bg-emerald-500"></span> <?php echo $isAdmin ? 'فروش کل (تومان)' : 'پرداختی شما'; ?></span>
        <span class="text-2xl font-black text-emerald-600 dark:text-emerald-400 font-mono" dir="ltr"><?php echo number_format($statTotalSales); ?></span>
    </div>
    <div class="bg-white dark:bg-slate-800 rounded-3xl border border-gray-100 dark:border-slate-700 p-5 flex justify-between items-center shadow-sm hover:shadow-md transition">
        <span class="text-xs font-bold text-gray-500 flex items-center gap-2"><span class="w-2.5 h-2.5 rounded-full bg-purple-500"></span> سود خالص (تومان)</span>
        <span class="text-2xl font-black text-purple-600 dark:text-purple-400 font-mono" dir="ltr"><?php echo number_format($statTotalProfit); ?></span>
    </div>
</div>

<div class="bg-white dark:bg-slate-800 rounded-3xl p-6 shadow-sm border border-gray-100 dark:border-slate-700 mb-6 space-y-5">
    <div class="flex flex-col xl:flex-row gap-3 items-center justify-between">
        <div class="flex flex-wrap items-center gap-3 w-full xl:w-auto">
            <div class="relative w-full md:w-[220px]">
                <svg class="absolute left-3 top-2.5 w-4 h-4 text-gray-400" 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>
                <input type="text" id="customSubSearch" placeholder="جستجوی یوزرنیم..." class="w-full bg-gray-50 dark:bg-slate-900 border border-gray-200 dark:border-slate-700 text-gray-700 dark:text-gray-200 rounded-xl pl-9 pr-4 py-2 text-xs font-bold outline-none focus:border-blue-500 transition shadow-sm">
            </div>
            
            <select id="target_server_id" onchange="loadSubsLive()" class="border-2 border-[#3b5998] rounded-xl px-4 py-2 text-xs font-bold text-[#3b5998] focus:ring-1 focus:ring-[#3b5998] outline-none bg-blue-50 dark:bg-[#3b5998]/20 dark:text-blue-300 shadow-sm cursor-pointer w-full md:w-auto">
                <?php if(empty($serversList)): ?>
                    <option value="" disabled selected>سروری یافت نشد</option>
                <?php else: ?>
                    <?php foreach($serversList as $index => $srv): ?>
                        <option value="<?php echo $srv['id']; ?>" <?php echo $index === 0 ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($srv['name']); ?>
                        </option>
                    <?php endforeach; ?>
                <?php endif; ?>
            </select>
            
            <select id="filter_live_usage" class="border border-gray-200 dark:border-slate-700 rounded-xl p-2 bg-gray-50 dark:bg-slate-900 text-xs font-bold focus:outline-none dark:text-white transition shadow-sm cursor-pointer w-full md:w-auto">
                <option value="all">📊 همه وضعیت‌های مصرف</option>
                <option value="unused">🆕 استفاده نشده (0 MB)</option>
                <option value="used">🔥 در حال استفاده</option>
            </select>

            <select id="filter_live_remain" class="border border-gray-200 dark:border-slate-700 rounded-xl p-2 bg-gray-50 dark:bg-slate-900 text-xs font-bold focus:outline-none dark:text-white transition shadow-sm cursor-pointer w-full md:w-auto">
                <option value="all">🔋 همه حجم‌های باقیمانده</option>
                <option value="ended">❌ تمام شده (لیمیت)</option>
                <option value="under_20">⚠️ زیر ۲۰٪ باقیمانده</option>
                <option value="under_50">⚡ زیر ۵0٪ باقیمانده</option>
            </select>
            
            <button onclick="loadSubsLive()" class="p-2 text-gray-500 hover:text-blue-600 bg-gray-50 hover:bg-blue-50 dark:bg-slate-900 dark:hover:bg-slate-700 border border-gray-200 dark:border-slate-700 rounded-xl transition shadow-sm" title="دریافت مجدد دیتای لایو">
                <svg id="refresh_live_icon" class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path></svg>
            </button>
        </div>
    </div>

    <hr class="border-gray-100 dark:border-slate-700/60">

    <form method="GET" action="subscriptions.php" class="flex flex-wrap gap-3 items-center">
        <?php if($isAdmin): ?>
        <select name="operator_id" class="border border-gray-200 dark:border-slate-700 rounded-xl p-2 bg-white dark:bg-slate-800 text-xs font-bold focus:outline-none dark:text-white transition shadow-sm 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>
        <?php endif; ?>

        <select name="date_filter" id="date_filter_select" onchange="toggleCustomDateInputs()" class="border border-gray-200 dark:border-slate-700 rounded-xl p-2 bg-white dark:bg-slate-800 text-xs font-bold focus:outline-none dark:text-white transition shadow-sm cursor-pointer">
            <option value="">📅 همه تاریخ‌های فروش</option>
            <option value="today" <?php if($current_date_filter == 'today') echo 'selected'; ?>>امروز</option>
            <option value="yesterday" <?php if($current_date_filter == 'yesterday') echo 'selected'; ?>>دیروز</option>
            <option value="last2days" <?php if($current_date_filter == 'last2days') echo 'selected'; ?>>۲ روز اخیر</option>
            <option value="last3days" <?php if($current_date_filter == 'last3days') echo 'selected'; ?>>۳ روز اخیر</option>
            <option value="lastweek" <?php if($current_date_filter == 'lastweek') echo 'selected'; ?>>هفته گذشته</option>
            <option value="lastmonth" <?php if($current_date_filter == 'lastmonth') echo 'selected'; ?>>ماه گذشته</option>
            <option value="custom" <?php if($current_date_filter == 'custom') echo 'selected'; ?>>انتخاب تاریخ دستی...</option>
        </select>

        <div id="custom_date_wrapper" class="flex items-center gap-2 <?php echo ($current_date_filter == 'custom') ? '' : 'hidden'; ?>">
            <input type="date" name="start_date" value="<?php echo htmlspecialchars($current_start_date); ?>" class="border border-gray-200 dark:border-slate-700 rounded-xl p-1.5 text-xs font-bold bg-white dark:bg-slate-800 dark:text-white shadow-sm outline-none">
            <span class="text-xs text-gray-500">تا</span>
            <input type="date" name="end_date" value="<?php echo htmlspecialchars($current_end_date); ?>" class="border border-gray-200 dark:border-slate-700 rounded-xl p-1.5 text-xs font-bold bg-white dark:bg-slate-800 dark:text-white shadow-sm outline-none">
        </div>

        <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white text-xs font-bold px-4 py-2 rounded-xl shadow-sm transition mr-auto">اعمال فیلتر</button>
        <?php if(!empty($_GET)): ?>
            <a href="subscriptions.php" class="bg-gray-100 dark:bg-slate-700 text-gray-600 dark:text-gray-300 hover:bg-gray-200 text-xs font-bold px-4 py-2 rounded-xl transition">پاک کردن</a>
        <?php endif; ?>
    </form>
</div>

<script>
function toggleCustomDateInputs() {
    var val = document.getElementById('date_filter_select').value;
    var wrapper = document.getElementById('custom_date_wrapper');
    if (val === 'custom') { wrapper.classList.remove('hidden'); } 
    else { wrapper.classList.add('hidden'); }
}
</script>