<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../config.php';

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

$page_title = 'چک پنل‌ها و مانیتورینگ';

set_time_limit(120);

try {
    $panels = $pdo->query("SELECT * FROM panels ORDER BY status DESC, name")->fetchAll();
} catch (Exception $e) {
    $panels = [];
}

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

$panel_stats = [];
$total_users = 0;
$total_traffic = 0;
$total_limit = 0;
$total_online = 0;

foreach ($panels as $panel) {
    $pid = (int)$panel['id'];
    $row = $pdo->prepare("
        SELECT 
            COUNT(*) as user_count,
            COALESCE(SUM(total_traffic), 0) as traffic_used,
            COALESCE(SUM(traffic_limit), 0) as traffic_limit_sum
        FROM reseller_users 
        WHERE panel_id = ?
    ");
    $row->execute([$pid]);
    $row = $row->fetch();

    $user_count = (int)($row['user_count'] ?? 0);
    $traffic_used = (int)($row['traffic_used'] ?? 0);
    $traffic_limit_sum = (int)($row['traffic_limit_sum'] ?? 0);

    $status = 'error';
    $status_msg = '';
    $online_count = 0;
    $inbounds_info = [];

    if ($panel['status'] !== 'active') {
        $status = 'inactive';
        $status_msg = 'پنل غیرفعال';
    } else {
        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);
            $online_list = $xrayAPI->getOnlines();
            $online_count = is_array($online_list) ? count($online_list) : 0;
            $status = 'online';
            $status_msg = $online_count . ' آنلاین';

            try {
                $inbounds_result = $xrayAPI->getInbounds();
                $inbounds = isset($inbounds_result['obj']) && is_array($inbounds_result['obj']) ? $inbounds_result['obj'] : (is_array($inbounds_result) ? $inbounds_result : []);
            } catch (Exception $e2) {
                $inbounds = [];
            }
            if (is_array($inbounds)) {
                foreach ($inbounds as $inb) {
                    if (!is_array($inb)) continue;
                    $iid = (int)($inb['id'] ?? 0);
                    $remark = $inb['remark'] ?? ('Inbound #' . $iid);
                    $up = (int)($inb['up'] ?? 0);
                    $down = (int)($inb['down'] ?? 0);
                    $clients = $inb['clients'] ?? [];
                    if (empty($clients) && !empty($inb['settings'])) {
                        $s = is_string($inb['settings']) ? json_decode($inb['settings'], true) : $inb['settings'];
                        $clients = $s['clients'] ?? [];
                    }
                    $client_count = count($clients);
                    $inbounds_info[] = [
                        'id' => $iid,
                        'remark' => $remark,
                        'port' => $inb['port'] ?? '-',
                        'protocol' => $inb['protocol'] ?? '-',
                        'clients' => $client_count,
                        'up' => $up,
                        'down' => $down,
                        'total' => $up + $down,
                    ];
                }
            }
        } catch (Exception $e) {
            $status = 'error';
            $status_msg = $e->getMessage();
        }
    }

    $panel_stats[] = [
        'panel' => $panel,
        'user_count' => $user_count,
        'traffic_used' => $traffic_used,
        'traffic_limit_sum' => $traffic_limit_sum,
        'status' => $status,
        'status_msg' => $status_msg,
        'online_count' => $online_count,
        'inbounds_info' => $inbounds_info,
    ];

    $total_users += $user_count;
    $total_traffic += $traffic_used;
    $total_limit += $traffic_limit_sum;
    if ($status === 'online') $total_online += $online_count;
}

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

<div class="row g-3 mb-4">
    <div class="col-md-3 col-sm-6">
        <div class="card stat-card-pro h-100">
            <div class="card-body">
                <h6 class="text-muted fw-normal">کل پنل‌ها</h6>
                <h3 class="mb-0"><?= count($panels) ?></h3>
                <small class="text-muted">فعال: <?= count(array_filter($panels, function($p) { return isset($p['status']) && $p['status'] === 'active'; })) ?></small>
            </div>
        </div>
    </div>
    <div class="col-md-3 col-sm-6">
        <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_users) ?></h3>
                <small class="text-muted">آنلاین: <?= $total_online ?></small>
            </div>
        </div>
    </div>
    <div class="col-md-3 col-sm-6">
        <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_traffic / (1024*1024*1024), 2) ?> <small>GB</small></h3>
            </div>
        </div>
    </div>
    <div class="col-md-3 col-sm-6">
        <div class="card stat-card-pro h-100">
            <div class="card-body">
                <h6 class="text-muted fw-normal">حد ترافیک کل</h6>
                <h3 class="mb-0"><?= $total_limit > 0 ? number_format($total_limit / (1024*1024*1024), 2) . ' GB' : '∞' ?></h3>
            </div>
        </div>
    </div>
</div>

<div class="card admin-main-card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h3 class="card-title mb-0"><i class="bi bi-hdd-network"></i> <?= htmlspecialchars($page_title) ?></h3>
        <a href="panel_monitor.php" class="btn btn-light btn-sm"><i class="bi bi-arrow-clockwise"></i> بروزرسانی</a>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead>
                    <tr>
                        <th style="width:1px">وضعیت</th>
                        <th>پنل</th>
                        <th>کاربران</th>
                        <th>آنلاین</th>
                        <th>ترافیک مصرف‌شده</th>
                        <th>حد ترافیک</th>
                        <th>استفاده</th>
                        <th>عملیات</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($panel_stats as $ps): 
                        $p = $ps['panel'];
                        $used_gb = $ps['traffic_used'] / (1024*1024*1024);
                        $limit_gb = $ps['traffic_limit_sum'] / (1024*1024*1024);
                        $pct = $ps['traffic_limit_sum'] > 0 ? min(100, ($ps['traffic_used'] / $ps['traffic_limit_sum']) * 100) : 0;
                        $bar_class = $pct >= 100 ? 'bg-danger' : ($pct >= 80 ? 'bg-warning' : 'bg-success');
                    ?>
                        <tr>
                            <td>
                                <span class="status-dot <?= $ps['status'] ?>" title="<?= htmlspecialchars($ps['status_msg']) ?>"></span>
                                <span class="small text-muted"><?= $ps['status'] === 'online' ? 'آنلاین' : ($ps['status'] === 'inactive' ? 'غیرفعال' : 'خطا') ?></span>
                            </td>
                            <td>
                                <strong><?= htmlspecialchars($p['name']) ?></strong>
                                <?php if ($ps['status'] === 'error' && $ps['status_msg']): ?>
                                    <br><small class="text-danger"><?= htmlspecialchars(mb_substr($ps['status_msg'], 0, 50)) ?>…</small>
                                <?php endif; ?>
                            </td>
                            <td><?= number_format($ps['user_count']) ?></td>
                            <td>
                                <?php if ($ps['status'] === 'online'): ?>
                                    <span class="badge bg-success"><?= $ps['online_count'] ?></span>
                                <?php else: ?>
                                    <span class="text-muted">—</span>
                                <?php endif; ?>
                            </td>
                            <td class="traffic-mini"><?= number_format($used_gb, 2) ?> GB</td>
                            <td class="traffic-mini"><?= $limit_gb > 0 ? number_format($limit_gb, 2) . ' GB' : '∞' ?></td>
                            <td style="min-width: 100px;">
                                <?php if ($limit_gb > 0): ?>
                                    <div class="progress" style="height: 8px; background: rgba(255,255,255,0.1);">
                                        <div class="progress-bar <?= $bar_class ?>" style="width: <?= min(100, $pct) ?>%"></div>
                                    </div>
                                    <small class="text-muted"><?= (int)$pct ?>%</small>
                                <?php else: ?>
                                    <span class="text-muted">—</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <a href="panel_manage.php?id=<?= $p['id'] ?>" class="btn btn-sm btn-outline-primary" title="مدیریت">
                                    <i class="bi bi-gear"></i>
                                </a>
                                <a href="online_users.php" class="btn btn-sm btn-outline-secondary" title="کاربران">
                                    <i class="bi bi-people"></i>
                                </a>
                            </td>
                        </tr>
                        <?php if (!empty($ps['inbounds_info']) && count($ps['inbounds_info']) <= 8): ?>
                        <tr>
                            <td colspan="8" class="py-2 small">
                                <div class="d-flex flex-wrap gap-2">
                                    <?php foreach ($ps['inbounds_info'] as $ib): ?>
                                        <span class="badge bg-secondary"><?= htmlspecialchars($ib['remark']) ?>: <?= $ib['clients'] ?> کاربر، <?= number_format(($ib['total'] ?? 0) / (1024*1024*1024), 2) ?> GB</span>
                                    <?php endforeach; ?>
                                </div>
                            </td>
                        </tr>
                        <?php elseif (!empty($ps['inbounds_info'])): ?>
                        <tr>
                            <td colspan="8" class="py-2 small">
                                <span class="text-muted"><?= count($ps['inbounds_info']) ?> اینباند — <?= array_sum(array_column($ps['inbounds_info'], 'clients')) ?> کلاینت</span>
                            </td>
                        </tr>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php if (empty($panel_stats)): ?>
    <div class="alert alert-info">
        هیچ پنلی ثبت نشده است. از بخش <a href="panels.php">پنل‌ها</a> پنل اضافه کنید.
    </div>
<?php endif; ?>

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