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

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

// دریافت لیست اپراتورها برای فیلتر ادمین
$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_op    = $_GET['operator_id'] ?? '';

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

// ==========================================
// حالت ۱: نمایش تاریخچه یک مشتری خاص (پروفایل مشتری)
// ==========================================
if (isset($_GET['view_customer'])) {
    $customerName = $_GET['view_customer'];
    $opId = $_GET['op_id'] ?? null; 
    
    $conditions = ["t.customer_name = :customer"];
    $params = [':customer' => $customerName];

    if (!$isAdmin) {
        $conditions[] = "t.user_id = :user_id";
        $params[':user_id'] = $userId;
    } elseif ($isAdmin && $opId) {
        $conditions[] = "t.user_id = :op_id";
        $params[':op_id'] = $opId;
    }

    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 = implode(" AND ", $conditions);

    $sqlHistory = "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 
                   WHERE $whereSQL 
                   ORDER BY t.id DESC";

    $stmtHistory = $pdo->prepare($sqlHistory);
    $stmtHistory->execute($params);
    $history = $stmtHistory->fetchAll();
    
    // محاسبات سربرگ مشتری
    $totalPaid = 0; $totalVol = 0; $totalProfit = 0; $totalAdminProfit = 0; $totalOpProfit = 0;
    foreach($history as $tx) {
        $totalPaid += $tx['paid_amount'];
        $totalVol += $tx['volume'];
        $totalProfit += $tx['profit']; // سود نماینده برای حالت کاربری
        $totalAdminProfit += $tx['admin_profit'];
        $totalOpProfit += $tx['profit'];
    }
    
    // نشان ویژه
    $vipBadge = '';
    if ($totalVol >= 100) $vipBadge = '<span class="text-xl" title="مشتری طلایی (بالای ۱۰۰ گیگ)">👑</span>';
    elseif ($totalVol >= 50) $vipBadge = '<span class="text-xl" title="مشتری وفادار (بالای ۵۰ گیگ)">🌟</span>';
    ?>

    <div class="bg-gradient-to-r from-blue-700 to-indigo-800 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 flex items-center justify-center md:justify-start gap-2">
                پروفایل مشتری: <span class="text-yellow-300"><?php echo htmlspecialchars($customerName); ?></span> <?php echo $vipBadge; ?>
            </h1>
            <p class="text-indigo-200 text-sm font-bold">تاریخچه کامل خریدها و وضعیت سودآوری</p>
        </div>
        <a href="customers.php?start_date=<?php echo urlencode($filter_start); ?>&end_date=<?php echo urlencode($filter_end); ?>&operator_id=<?php echo urlencode($filter_op); ?>" class="mt-4 md:mt-0 relative z-10 bg-white/20 hover:bg-white/30 text-white border border-white/30 font-bold px-6 py-2.5 rounded-xl transition backdrop-blur-sm">بازگشت به لیست ⮌</a>
    </div>

    <!-- تغییر تعداد باکس‌ها برای ادمین -->
    <div class="grid grid-cols-2 <?php echo $isAdmin ? 'md:grid-cols-5' : 'md:grid-cols-4'; ?> gap-4 mb-8">
        <div class="bg-white dark:bg-slate-800 p-5 rounded-2xl shadow-sm border border-gray-100 dark:border-slate-700">
            <span class="block text-xs font-bold text-gray-500 dark:text-gray-400 mb-1">تعداد خرید</span>
            <span class="text-2xl font-black text-gray-800 dark:text-white"><?php echo count($history); ?> <span class="text-sm font-normal">سرویس</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-b-4 border-b-blue-500">
            <span class="block text-xs font-bold text-gray-500 dark:text-gray-400 mb-1">مجموع حجم</span>
            <span class="text-2xl font-black text-blue-600 dark:text-blue-400"><?php echo $totalVol; ?> <span class="text-sm font-normal">GB</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-b-4 border-b-emerald-500">
            <span class="block text-xs font-bold text-gray-500 dark:text-gray-400 mb-1">مجموع پرداختی</span>
            <span class="text-xl font-black text-emerald-600 dark:text-emerald-400" dir="ltr"><?php echo number_format($totalPaid); ?> <span class="text-sm font-normal">T</span></span>
        </div>
        
        <?php if($isAdmin): ?>
            <div class="bg-white dark:bg-slate-800 p-5 rounded-2xl shadow-sm border border-gray-100 dark:border-slate-700 border-b-4 border-b-green-500">
                <span class="block text-xs font-bold text-gray-500 dark:text-gray-400 mb-1">کل سود نماینده</span>
                <span class="text-xl font-black text-green-600 dark:text-green-400" dir="ltr"><?php echo number_format($totalOpProfit); ?> <span class="text-sm font-normal">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-b-4 border-b-purple-500">
                <span class="block text-xs font-bold text-gray-500 dark:text-gray-400 mb-1">کل سود ادمین</span>
                <span class="text-xl font-black text-purple-600 dark:text-purple-400" dir="ltr"><?php echo number_format($totalAdminProfit); ?> <span class="text-sm font-normal">T</span></span>
            </div>
        <?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-b-4 border-b-purple-500">
                <span class="block text-xs font-bold text-gray-500 dark:text-gray-400 mb-1">سودآوری شما</span>
                <span class="text-xl font-black text-purple-600 dark:text-purple-400" dir="ltr"><?php echo number_format($totalProfit); ?> <span class="text-sm font-normal">T</span></span>
            </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-6 overflow-hidden">
        <h3 class="text-lg font-bold text-gray-800 dark:text-white mb-6 flex items-center gap-2">
            <span class="w-2 h-5 bg-blue-500 rounded-full"></span> تاریخچه تراکنش‌ها
        </h3>
        <div class="overflow-x-auto">
            <table class="w-full text-sm text-right text-gray-600 dark:text-gray-400 stripe hover display" id="customerHistoryTable">
                <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-lg">تاریخ</th>
                        <th class="px-4 py-3">اکانت</th>
                        <th class="px-4 py-3">سرویس (حجم)</th>
                        <th class="px-4 py-3 text-emerald-700 dark:text-emerald-400">مبلغ پرداختی</th>
                        
                        <?php if($isAdmin): ?>
                            <th class="px-4 py-3 text-green-700 dark:text-green-400">سود نماینده</th>
                            <th class="px-4 py-3 text-purple-700 dark:text-purple-400">سود ادمین</th>
                        <?php else: ?>
                            <th class="px-4 py-3 text-purple-700 dark:text-purple-400">سودآوری</th>
                        <?php endif; ?>
                        
                        <th class="px-4 py-3">واریز به</th>
                        <?php if($isAdmin): ?><th class="px-4 py-3 rounded-tl-lg">نماینده</th><?php endif; ?>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100 dark:divide-slate-700">
                    <?php foreach($history as $tx): 
                        $creatorDisplayName = !empty($tx['creator_fullname']) ? htmlspecialchars($tx['creator_fullname']) : htmlspecialchars($tx['creator_username']);
                    ?>
                    <tr class="hover:bg-gray-50 dark:hover:bg-slate-700/30 transition">
                        <td class="px-4 py-4 text-xs font-mono" dir="ltr"><?php echo $tx['date_shamsi']; ?></td>
                        <td class="px-4 py-4 font-mono text-blue-600 dark:text-blue-400 text-xs" dir="ltr"><?php echo htmlspecialchars($tx['account_username']); ?></td>
                        <td class="px-4 py-4 font-bold text-gray-800 dark:text-gray-200"><?php echo $tx['plan']; ?> <span class="bg-gray-200 dark:bg-slate-600 text-gray-600 dark:text-gray-300 px-1.5 rounded text-xs ml-1"><?php echo $tx['volume']; ?>G</span></td>
                        <td class="px-4 py-4 font-mono font-bold text-emerald-600 dark:text-emerald-400 bg-emerald-50/30 dark:bg-emerald-900/10" dir="ltr"><?php echo number_format($tx['paid_amount']); ?></td>
                        
                        <?php if($isAdmin): ?>
                            <td class="px-4 py-4 font-mono font-bold text-green-600 dark:text-green-400 bg-green-50/30 dark:bg-green-900/10" dir="ltr"><?php echo number_format($tx['profit']); ?></td>
                            <td class="px-4 py-4 font-mono font-bold text-purple-600 dark:text-purple-400 bg-purple-50/30 dark:bg-purple-900/10" dir="ltr"><?php echo number_format($tx['admin_profit']); ?></td>
                        <?php else: ?>
                            <td class="px-4 py-4 font-mono font-bold text-purple-600 dark:text-purple-400 bg-purple-50/30 dark:bg-purple-900/10" dir="ltr"><?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="text-gray-400 bg-gray-100 dark:bg-slate-700 px-2 py-0.5 rounded border border-gray-200 dark:border-slate-600">-</span>'; ?>
                        </td>
                        <?php if($isAdmin): ?>
                            <td class="px-4 py-4 text-xs font-bold text-gray-500 dark:text-gray-400"><?php echo $creatorDisplayName; ?></td>
                        <?php endif; ?>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <link rel="stylesheet" href="https://unpkg.com/persian-datepicker@1.2.0/dist/css/persian-datepicker.min.css"/>
    <link rel="stylesheet" type="text/css" href="/vpnet-panel/assets/css/datatables.min.css">
    
    <style>
        .dataTables_wrapper .dataTables_filter input { border: 2px solid #e5e7eb; border-radius: 12px; padding: 6px 12px; outline: none; }
        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: 8px; padding: 4px; outline: none; }
        html.dark .dataTables_wrapper .dataTables_length select { background-color: #0f172a; color: #f8fafc; border-color: #334155; }
    </style>

    <script src="/vpnet-panel/assets/js/jquery-3.7.0.min.js"></script>
    <script src="/vpnet-panel/assets/js/jquery.dataTables.min.js"></script>
    <script>
    $(document).ready(function() {
        $('#customerHistoryTable').DataTable({
            "language": { 
                "url": "//cdn.datatables.net/plug-ins/1.13.4/i18n/fa.json",
                "search": "جستجو:"
            },
            "order": [],
            "pageLength": 25
        });
    });
    </script>

    <?php
} 
// ==========================================
// حالت ۲: نمایش لیست کل مشتریان (CRM اصلی)
// ==========================================
else {
    $conditions = ["t.customer_name != '-'", "t.customer_name != ''"];
    $params = [];

    if (!$isAdmin) {
        $conditions[] = "t.user_id = :user_id";
        $params[':user_id'] = $userId;
    } elseif ($isAdmin && !empty($filter_op)) {
        $conditions[] = "t.user_id = :op_id";
        $params[':op_id'] = $filter_op;
    }

    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 = implode(" AND ", $conditions);

    $sqlCustomers = "SELECT 
                        t.customer_name, 
                        t.user_id,
                        COUNT(t.id) as tx_count, 
                        SUM(t.volume) as total_volume,
                        SUM(t.paid_amount) as total_paid,
                        SUM(t.profit) as total_op_profit,
                        SUM(t.admin_profit) as total_admin_profit,
                        u.username,
                        u.fullname
                     FROM transactions t
                     LEFT JOIN users u ON t.user_id = u.id
                     WHERE $whereSQL 
                     GROUP BY t.customer_name, t.user_id 
                     ORDER BY tx_count DESC, total_paid DESC";
                     
    $stmtList = $pdo->prepare($sqlCustomers);
    $stmtList->execute($params);
    $customers = $stmtList->fetchAll();
    ?>

    <div class="bg-gradient-to-r from-blue-700 to-indigo-800 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-indigo-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 mb-8 relative z-10">
        <h2 class="text-sm font-bold text-gray-800 dark:text-white mb-4 flex items-center gap-2">
            <span class="w-2 h-4 bg-indigo-500 rounded-full"></span> فیلترهای گزارش‌گیری
        </h2>
        <form method="GET" class="flex flex-col sm:flex-row flex-wrap items-end gap-4 w-full">
            <div class="relative w-full sm:w-48">
                <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-2.5 text-xs bg-gray-50 dark:bg-slate-700 focus:border-indigo-500 outline-none dark:text-white cursor-pointer transition" 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-48">
                <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-2.5 text-xs bg-gray-50 dark:bg-slate-700 focus:border-indigo-500 outline-none dark:text-white cursor-pointer transition" dir="ltr" readonly>
                <input type="hidden" name="end_date" id="end_date_alt" value="<?php echo htmlspecialchars($filter_end); ?>">
            </div>

            <?php if($isAdmin): ?>
            <div class="w-full sm:w-48">
                <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-2.5 bg-gray-50 dark:bg-slate-700 text-xs font-bold focus:outline-none focus:border-indigo-500 dark:text-white transition">
                    <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_op == $op['id']) echo 'selected'; ?>><?php echo $displayName; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <?php endif; ?>

            <div class="flex gap-2 w-full sm:w-auto mt-2 sm:mt-0">
                <button type="submit" class="w-full sm:w-auto bg-indigo-600 text-white font-bold py-2.5 px-6 rounded-xl hover:bg-indigo-700 shadow-md transition text-xs">اعمال فیلتر</button>
                <?php if(!empty($filter_start) || !empty($filter_end) || !empty($filter_op)): ?>
                    <a href="customers.php" class="w-full sm:w-auto bg-gray-100 dark:bg-slate-700 text-gray-600 dark:text-gray-300 text-center font-bold py-2.5 px-6 rounded-xl hover:bg-gray-200 dark:hover:bg-slate-600 transition border border-gray-200 dark:border-slate-600 text-xs">پاک کردن</a>
                <?php endif; ?>
            </div>
        </form>
    </div>

    <!-- جدول لیست مشتریان -->
    <div class="bg-white dark:bg-slate-800 rounded-3xl shadow-sm border border-gray-100 dark:border-slate-700 p-6 overflow-hidden">
        <h2 class="text-lg font-bold mb-6 text-gray-800 dark:text-white flex items-center gap-2">
            <span class="text-xl">🏆</span> رتبه‌بندی مشتریان (VIP)
        </h2>
        
        <div class="overflow-x-auto">
            <table id="customersTable" class="w-full text-sm text-right text-gray-600 dark:text-gray-400 stripe hover display">
                <thead class="bg-indigo-50 dark:bg-indigo-900/20 text-indigo-800 dark:text-indigo-300 border-b border-indigo-100 dark:border-indigo-900/50">
                    <tr>
                        <th class="px-4 py-4 rounded-tr-lg">نام مشتری</th>
                        <?php if($isAdmin): ?><th class="px-4 py-4">نماینده (ثبت‌کننده)</th><?php endif; ?>
                        <th class="px-4 py-4">تعداد خرید</th>
                        <th class="px-4 py-4">حجم دریافتی</th>
                        <th class="px-4 py-4 text-emerald-700 dark:text-emerald-400">مجموع پرداختی</th>
                        
                        <?php if($isAdmin): ?>
                            <th class="px-4 py-4 text-green-700 dark:text-green-400">سود نماینده</th>
                            <th class="px-4 py-4 text-purple-700 dark:text-purple-400">سود ادمین</th>
                        <?php else: ?>
                            <th class="px-4 py-4 text-purple-700 dark:text-purple-400">سودآوری شما</th>
                        <?php endif; ?>
                        
                        <th class="px-4 py-4 text-center rounded-tl-lg">عملیات</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100 dark:divide-slate-700">
                    <?php foreach($customers as $c): 
                        $creatorName = !empty($c['fullname']) ? htmlspecialchars($c['fullname']) : htmlspecialchars($c['username']);
                        
                        // نشان ویژه
                        $vipBadge = '';
                        if ($c['total_volume'] >= 100) $vipBadge = '<span class="text-base mr-1" title="مشتری طلایی">👑</span>';
                        elseif ($c['total_volume'] >= 50) $vipBadge = '<span class="text-base mr-1" title="مشتری وفادار">🌟</span>';
                    ?>
                    <tr class="hover:bg-gray-50 dark:hover:bg-slate-700/30 transition">
                        <td class="px-4 py-4 font-black text-gray-800 dark:text-gray-200 text-base flex items-center">
                            <?php echo htmlspecialchars($c['customer_name']); ?> <?php echo $vipBadge; ?>
                        </td>
                        
                        <?php if($isAdmin): ?>
                            <td class="px-4 py-4 text-xs font-bold text-indigo-700 dark:text-indigo-400 bg-indigo-50/30 dark:bg-indigo-900/10"><?php echo $creatorName; ?></td>
                        <?php endif; ?>

                        <td class="px-4 py-4">
                            <span class="bg-gray-100 dark:bg-slate-700 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-slate-600 px-2.5 py-1 rounded-lg font-bold text-xs">
                                <?php echo $c['tx_count']; ?> تراکنش
                            </span>
                        </td>
                        <td class="px-4 py-4 font-black text-blue-600 dark:text-blue-400 text-lg">
                            <?php echo $c['total_volume']; ?> <span class="text-xs text-gray-400 font-normal">GB</span>
                        </td>
                        <td class="px-4 py-4 font-mono font-black text-emerald-600 dark:text-emerald-400 bg-emerald-50/30 dark:bg-emerald-900/10" dir="ltr"><?php echo number_format($c['total_paid']); ?></td>
                        
                        <?php if($isAdmin): ?>
                            <td class="px-4 py-4 font-mono font-black text-green-600 dark:text-green-400 bg-green-50/30 dark:bg-green-900/10" dir="ltr"><?php echo number_format($c['total_op_profit']); ?></td>
                            <td class="px-4 py-4 font-mono font-black text-purple-600 dark:text-purple-400 bg-purple-50/30 dark:bg-purple-900/10" dir="ltr"><?php echo number_format($c['total_admin_profit']); ?></td>
                        <?php else: ?>
                            <td class="px-4 py-4 font-mono font-black text-purple-600 dark:text-purple-400 bg-purple-50/30 dark:bg-purple-900/10" dir="ltr"><?php echo number_format($c['total_op_profit']); ?></td>
                        <?php endif; ?>

                        <td class="px-4 py-4 text-center">
                            <a href="customers.php?view_customer=<?php echo urlencode($c['customer_name']); ?>&op_id=<?php echo $c['user_id']; ?>&start_date=<?php echo urlencode($filter_start); ?>&end_date=<?php echo urlencode($filter_end); ?>" class="bg-indigo-50 dark:bg-indigo-900/30 text-indigo-600 dark:text-indigo-400 border border-indigo-200 dark:border-indigo-800 hover:bg-indigo-100 dark:hover:bg-indigo-900/50 px-4 py-2 rounded-xl text-xs font-bold transition shadow-sm inline-block">ریز جزئیات ➔</a>
                        </td>
                    </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>
                        <th colspan="<?php echo $isAdmin ? '3' : '2'; ?>" class="px-4 py-4 text-left font-black text-gray-800 dark:text-white">جمع کل در این صفحه:</th>
                        <th class="px-4 py-4 font-black text-blue-700 dark:text-blue-400 text-lg" id="footer-total-volume">0</th>
                        <th class="px-4 py-4 font-mono font-black text-emerald-700 dark:text-emerald-400 text-lg" id="footer-total-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-total-op-profit" 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-total-admin-profit" dir="ltr">0</th>
                        <?php else: ?>
                            <th class="px-4 py-4 font-mono font-black text-purple-700 dark:text-purple-400 text-lg" id="footer-total-profit" dir="ltr">0</th>
                        <?php endif; ?>
                        <th></th>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>

    <!-- فایل‌های تقویم و DataTables -->
    <link rel="stylesheet" href="https://unpkg.com/persian-datepicker@1.2.0/dist/css/persian-datepicker.min.css"/>
    <link rel="stylesheet" type="text/css" href="/vpnet-panel/assets/css/datatables.min.css">
    
    <style>
        .dataTables_wrapper .dataTables_filter input { border: 2px solid #e5e7eb; border-radius: 12px; padding: 6px 12px; 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: 8px; padding: 4px; outline: none; }
        html.dark .dataTables_wrapper .dataTables_length select { background-color: #0f172a; color: #f8fafc; border-color: #334155; }
        
        .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>

    <script src="/vpnet-panel/assets/js/jquery-3.7.0.min.js"></script>
    <script src="/vpnet-panel/assets/js/jquery.dataTables.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);

        // راه‌اندازی DataTables به همراه محاسبه فوتر
        let isAdmin = <?php echo $isAdmin ? 'true' : 'false'; ?>;
        
        // محاسبه ایندکس ستون‌ها بر اساس سطح دسترسی (ادمین یا نماینده)
        let volColIdx = isAdmin ? 3 : 2;
        let paidColIdx = isAdmin ? 4 : 3;
        let opProfitColIdx = isAdmin ? 5 : 4;
        let adminProfitColIdx = isAdmin ? 6 : -1;

        $('#customersTable').DataTable({
            "language": { 
                "url": "//cdn.datatables.net/plug-ins/1.13.4/i18n/fa.json",
                "search": "جستجوی سریع:"
            },
            "order": [[ volColIdx, "desc"]], 
            "pageLength": 25,
            "footerCallback": function ( row, data, start, end, display ) {
                var api = this.api(), data;
                
                // تابع اصلاح شده برای حذف تمام تگ‌های HTML (مثل اسپان‌ها) قبل از تبدیل به عدد
                var intVal = function ( i ) {
                    if (typeof i === 'string') {
                        return i.replace(/<[^>]*>?/gm, '').replace(/[\$,A-Za-z]/g, '').trim() * 1;
                    }
                    return typeof i === 'number' ? i : 0;
                };

                let pageTotalVol = api.column( volColIdx, { page: 'current'} ).data().reduce( function (a, b) { return intVal(a) + intVal(b); }, 0 );
                let pageTotalPaid = api.column( paidColIdx, { page: 'current'} ).data().reduce( function (a, b) { return intVal(a) + intVal(b); }, 0 );
                let pageTotalOpProfit = api.column( opProfitColIdx, { page: 'current'} ).data().reduce( function (a, b) { return intVal(a) + intVal(b); }, 0 );

                $( api.column( volColIdx ).footer() ).html(pageTotalVol + ' GB');
                $( api.column( paidColIdx ).footer() ).html(pageTotalPaid.toLocaleString('en-US'));
                
                if (isAdmin) {
                    let pageTotalAdminProfit = api.column( adminProfitColIdx, { page: 'current'} ).data().reduce( function (a, b) { return intVal(a) + intVal(b); }, 0 );
                    $( api.column( opProfitColIdx ).footer() ).html(pageTotalOpProfit.toLocaleString('en-US'));
                    $( api.column( adminProfitColIdx ).footer() ).html(pageTotalAdminProfit.toLocaleString('en-US'));
                } else {
                    $( api.column( opProfitColIdx ).footer() ).html(pageTotalOpProfit.toLocaleString('en-US'));
                }
            }
        });
    });
    </script>

    <?php
}

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