<?php
// شروع session قبل از هر چیز
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once '../config.php';

// بررسی لاگین
if (!isLoggedIn()) {
    redirect('../login.php');
}

// بررسی دسترسی ادمین
if (!isAdmin()) {
    setMessage('دسترسی غیرمجاز', 'error');
    redirect('../login.php');
}

$page_title = 'مانیتورینگ کلی';

// آمار کلی
$total_stats = $pdo->query("
    SELECT 
        COUNT(DISTINCT r.id) as total_reps,
        COUNT(DISTINCT CASE WHEN r.status = 'active' THEN r.id END) as active_reps,
        COUNT(DISTINCT ru.id) as total_users,
        COUNT(DISTINCT CASE WHEN ru.status = 'active' THEN ru.id END) as active_users,
        SUM(ru.total_traffic) as total_traffic,
        SUM(ru.traffic_limit) as total_limit
    FROM representatives r
    LEFT JOIN reseller_users ru ON r.id = ru.representative_id
")->fetch();

// آمار هر نماینده
$rep_stats = $pdo->query("
    SELECT 
        r.id,
        r.username,
        r.full_name,
        p.name as panel_name,
        r.traffic_limit as rep_traffic_limit,
        r.used_traffic as rep_used_traffic,
        r.expiry_date as rep_expiry_date,
        r.status as rep_status,
        COUNT(ru.id) as user_count,
        SUM(ru.total_traffic) as user_traffic,
        SUM(CASE WHEN ru.status = 'active' THEN 1 ELSE 0 END) as active_user_count
    FROM representatives r
    LEFT JOIN panels p ON r.panel_id = p.id
    LEFT JOIN reseller_users ru ON r.id = ru.representative_id
    GROUP BY r.id
    ORDER BY user_traffic DESC
")->fetchAll();

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

<div class="row g-3 mb-4">
    <div class="col-md-3">
        <div class="card stat-card-pro h-100">
            <div class="card-body">
                <h6 class="text-muted fw-normal">کل نمایندگان</h6>
                <h3 class="mb-0"><?= $total_stats['total_reps'] ?? 0 ?></h3>
                <small class="text-muted">فعال: <?= $total_stats['active_reps'] ?? 0 ?></small>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card stat-card-pro h-100">
            <div class="card-body">
                <h6 class="text-muted fw-normal">کل کاربران</h6>
                <h3 class="mb-0"><?= $total_stats['total_users'] ?? 0 ?></h3>
                <small class="text-muted">فعال: <?= $total_stats['active_users'] ?? 0 ?></small>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card stat-card-pro h-100">
            <div class="card-body">
                <h6 class="text-muted fw-normal">ترافیک کل</h6>
                <h3 class="mb-0"><?= number_format(($total_stats['total_traffic'] ?? 0) / (1024 * 1024 * 1024), 2) ?> <small>GB</small></h3>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card stat-card-pro h-100">
            <div class="card-body">
                <h6 class="text-muted fw-normal">حد ترافیک کل</h6>
                <h3 class="mb-0"><?= number_format(($total_stats['total_limit'] ?? 0) / (1024 * 1024 * 1024), 2) ?> <small>GB</small></h3>
            </div>
        </div>
    </div>
</div>

<div class="card admin-main-card">
    <div class="card-header">
        <h3 class="card-title mb-0"><?= htmlspecialchars($page_title) ?></h3>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>نام کاربری</th>
                        <th>نام کامل</th>
                        <th>پنل</th>
                        <th>کاربران</th>
                        <th>کاربران فعال</th>
                        <th>ترافیک کاربران</th>
                        <th>حد ترافیک نماینده</th>
                        <th>ترافیک مصرفی نماینده</th>
                        <th>تاریخ انقضا</th>
                        <th>وضعیت</th>
                        <th>عملیات</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($rep_stats as $stat): 
                        $is_expired = $stat['rep_expiry_date'] && strtotime($stat['rep_expiry_date']) < time();
                        $is_traffic_limited = $stat['rep_traffic_limit'] > 0 && ($stat['rep_used_traffic'] ?? 0) >= $stat['rep_traffic_limit'];
                    ?>
                        <tr>
                            <td><?= $stat['id'] ?></td>
                            <td><?= htmlspecialchars($stat['username']) ?></td>
                            <td><?= htmlspecialchars($stat['full_name'] ?? '-') ?></td>
                            <td><?= htmlspecialchars($stat['panel_name']) ?></td>
                            <td><?= $stat['user_count'] ?? 0 ?></td>
                            <td><?= $stat['active_user_count'] ?? 0 ?></td>
                            <td><?= number_format(($stat['user_traffic'] ?? 0) / (1024 * 1024 * 1024), 2) ?> GB</td>
                            <td><?= $stat['rep_traffic_limit'] > 0 ? number_format($stat['rep_traffic_limit'] / (1024 * 1024 * 1024), 2) . ' GB' : 'نامحدود' ?></td>
                            <td><?= number_format(($stat['rep_used_traffic'] ?? 0) / (1024 * 1024 * 1024), 2) ?> GB</td>
                            <td><?= $stat['rep_expiry_date'] ? date('Y/m/d H:i', strtotime($stat['rep_expiry_date'])) : 'نامحدود' ?></td>
                            <td>
                                <?php if ($stat['rep_status'] !== 'active'): ?>
                                    <span class="badge bg-danger">غیرفعال</span>
                                <?php elseif ($is_expired): ?>
                                    <span class="badge bg-danger">منقضی شده</span>
                                <?php elseif ($is_traffic_limited): ?>
                                    <span class="badge bg-warning">محدود شده</span>
                                <?php else: ?>
                                    <span class="badge bg-success">فعال</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <a href="representative_monitor.php?id=<?= $stat['id'] ?>" class="btn btn-sm btn-primary">
                                    <i class="bi bi-eye"></i>
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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