<?php
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 = 'کاربران پنل (همه کاربران مثل x-ui)';

$panels = $pdo->query("SELECT * FROM panels WHERE status = 'active' ORDER BY name")->fetchAll();
$panel_onlines = [];

require_once __DIR__ . '/../api/XrayAPI.php';

// برای هر پنل: کاربران (با email و xray_user_id) و لیست آنلاین‌ها و در صورت امکان مصرف لحظه‌ای از پنل
$stmt_users = $pdo->prepare("
    SELECT id, email, xray_user_id, inbound_id, total_traffic, traffic_limit, expiry_date 
    FROM reseller_users 
    WHERE panel_id = ? AND status IN ('active', 'expired', 'limited')
");
foreach ($panels as $panel) {
    $stmt_users->execute([$panel['id']]);
    $users_by_key = []; // کلید: email یا xray_user_id (برای تطبیق با خروجی getOnlines)
    while ($row = $stmt_users->fetch(PDO::FETCH_ASSOC)) {
        $rec = [
            'email' => $row['email'],
            'xray_user_id' => $row['xray_user_id'],
            'inbound_id' => (int)$row['inbound_id'],
            'total_traffic' => (int)$row['total_traffic'],
            'traffic_limit' => (int)$row['traffic_limit'],
            'expiry_date' => $row['expiry_date'],
        ];
        $emailKey = trim($row['email']);
        $users_by_key[$emailKey] = $rec;
        if ($emailKey !== '') {
            $users_by_key[mb_strtolower($emailKey)] = $rec;
        }
        if (!empty($row['xray_user_id'])) {
            $users_by_key[trim($row['xray_user_id'])] = $rec;
        }
    }
    $panel_users_unique = [];
    foreach ($users_by_key as $r) {
        $panel_users_unique[$r['email']] = $r;
    }
    $panel_users_unique = array_values($panel_users_unique);

    $item = [
        'name' => $panel['name'],
        'panel_id' => $panel['id'],
        'emails' => [],
        'users_by_key' => $users_by_key,
        'panel_users_unique' => $panel_users_unique,
        'error' => null,
        'xrayAPI' => null,
    ];
    try {
        $proxy_config = null;
        if (!empty($panel['proxy_host'])) {
            $proxy_config = [
                'type' => $panel['proxy_type'] ?? 'socks5',
                'host' => $panel['proxy_host'],
                'port' => $panel['proxy_port'] ?? 1080,
                'username' => $panel['proxy_username'] ?? null,
                'password' => $panel['proxy_password'] ?? null,
                'use_on_error' => !empty($panel['use_proxy']),
            ];
        }
        $xrayAPI = new XrayAPI($panel['url'], $panel['username'], $panel['password'], $proxy_config);
        $item['xrayAPI'] = $xrayAPI;
        $item['emails'] = $xrayAPI->getOnlines();
    } catch (Exception $e) {
        $item['error'] = $e->getMessage();
        $item['emails'] = [];
    }
    $panel_onlines[] = $item;
}

require_once '../includes/header.php';
?>
<div class="card admin-main-card mb-4">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h3 class="card-title mb-0"><i class="bi bi-broadcast"></i> <?= htmlspecialchars($page_title) ?></h3>
        <a href="online_users.php" class="btn btn-light btn-sm" title="بروزرسانی">
            <i class="bi bi-arrow-clockwise"></i> بروزرسانی
        </a>
    </div>
    <div class="card-body">
        <p class="text-muted small mb-0">
            لیست همه کاربران ثبت‌شده در هر پنل با مصرف ترافیک، خط روند و وضعیت آنلاین/آفلاین.
        </p>
    </div>
</div>

<?php if (empty($panel_onlines)): ?>
    <div class="alert alert-warning">
        هیچ پنل فعالی وجود ندارد. از بخش <a href="panels.php">پنل‌ها</a> پنل اضافه کنید.
    </div>
<?php else: ?>
    <div class="row">
        <?php foreach ($panel_onlines as $po): ?>
            <div class="col-12 col-lg-6 mb-4">
                <div class="card h-100">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <strong><?= htmlspecialchars($po['name']) ?></strong>
                        <span class="badge bg-<?= $po['error'] ? 'danger' : 'success' ?>">
                            <?= $po['error'] ? 'خطا' : count($po['emails']) . ' آنلاین' ?>
                        </span>
                    </div>
                    <div class="card-body">
                        <?php if ($po['error']): ?>
                            <p class="text-danger small mb-2"><?= htmlspecialchars($po['error']) ?></p>
                        <?php endif; ?>
                        <?php if (empty($po['panel_users_unique'])): ?>
                            <p class="text-muted small mb-0">هیچ کاربری در این پنل ثبت نشده است.</p>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-hover table-users table-borderless align-middle mb-0">
                                    <thead>
                                        <tr>
                                            <th style="width:1px">وضعیت</th>
                                            <th>کاربر</th>
                                            <th>مصرف / سقف</th>
                                            <th class="text-nowrap">اعتبار</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                <?php
                                $online_set = [];
                                foreach ($po['emails'] as $e) {
                                    $e = trim($e);
                                    if ($e !== '') { $online_set[$e] = true; $online_set[mb_strtolower($e)] = true; }
                                }
                                foreach ($po['panel_users_unique'] as $u):
                                    $used = (int)$u['total_traffic'];
                                    if ($po['xrayAPI'] && $u['inbound_id'] && !empty($u['xray_user_id'])) {
                                        try {
                                            $stats = $po['xrayAPI']->getClientStats($u['inbound_id'], $u['xray_user_id']);
                                            $tr = isset($stats['obj']) ? $stats['obj'] : $stats;
                                            if (is_array($tr)) {
                                                $used = (int)(($tr['up'] ?? 0) + ($tr['down'] ?? 0));
                                            }
                                        } catch (Exception $e) { /* از مقدار DB */ }
                                    }
                                    $limit = (int)$u['traffic_limit'];
                                    $expiry_date = $u['expiry_date'] ?? null;
                                    $is_finished = $limit > 0 && $used >= $limit;
                                    $used_gb = $used / (1024 * 1024 * 1024);
                                    $limit_gb = $limit / (1024 * 1024 * 1024);
                                    $traffic_percent = $limit > 0 ? min(100, ($used / $limit) * 100) : 0;
                                    $bar_class = $limit > 0 ? ($traffic_percent >= 100 ? 'bg-danger' : ($traffic_percent >= 80 ? 'bg-warning' : 'bg-success')) : 'bg-info';
                                    $is_online = isset($online_set[trim($u['email'])]) || isset($online_set[mb_strtolower(trim($u['email']))]) || (!empty($u['xray_user_id']) && isset($online_set[trim($u['xray_user_id'])]));
                                    $dot_class = $is_finished ? 'limit-exceeded' : ($is_online ? 'online' : 'offline');
                                    if ($expiry_date) {
                                        $rem = strtotime($expiry_date) - time();
                                        if ($rem < 0) {
                                            $duration_dh = abs((int)floor($rem / 86400)) . 'd گذشته';
                                            $validity_class = 'bg-danger';
                                        } else {
                                            $d = (int)floor($rem / 86400);
                                            $h = (int)floor(($rem % 86400) / 3600);
                                            $duration_dh = $d . 'd ' . $h . 'h';
                                            $validity_class = 'bg-success';
                                        }
                                    } else {
                                        $duration_dh = '∞';
                                        $validity_class = 'badge-validity infinite';
                                    }
                                ?>
                                        <tr>
                                            <td>
                                                <span class="xui-dot <?= $dot_class ?>" title="<?= $is_online ? 'آنلاین' : 'آفلاین' ?>"></span>
                                                <span class="small text-muted"><?= $is_online ? 'آنلاین' : 'آفلاین' ?></span>
                                            </td>
                                            <td><code class="small text-break"><?= htmlspecialchars($u['email']) ?></code></td>
                                            <td>
                                                <div class="d-flex align-items-center gap-2 flex-wrap">
                                                    <span class="fw-bold text-nowrap"><?= $used_gb >= 1 ? number_format($used_gb, 2) . ' GB' : number_format($used / (1024*1024), 2) . ' MB' ?></span>
                                                    <span class="text-muted">/</span>
                                                    <?php if ($limit > 0): ?>
                                                        <span class="text-nowrap"><?= number_format($limit_gb, 2) ?> GB</span>
                                                        <?php if ($is_finished): ?><span class="badge bg-danger rounded-pill">تمام</span><?php endif; ?>
                                                    <?php else: ?>
                                                        <span class="text-muted">∞</span>
                                                    <?php endif; ?>
                                                </div>
                                                <div class="progress xui-progress mt-1" style="max-width: 200px;" role="progressbar" title="<?= (int)$traffic_percent ?>%">
                                                    <?php if ($limit > 0): ?>
                                                        <div class="progress-bar <?= $bar_class ?>" style="width: <?= max(2, min(100, $traffic_percent)) ?>%;"></div>
                                                    <?php else: ?>
                                                        <div class="progress-bar bg-info" style="width: <?= $used > 0 ? min(50, 10 + ($used_gb * 2)) : 2 ?>%;"></div>
                                                    <?php endif; ?>
                                                </div>
                                            </td>
                                            <td>
                                                <span class="badge rounded-pill <?= $validity_class ?> badge-validity"><?= $duration_dh ?></span>
                                            </td>
                                        </tr>
                                <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
<?php endif; ?>

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