<?php
/**
 * channels.php — manage channels + bot verifications on a single AJAX-tabbed page.
 *
 * Permission: owner OR 'channels'. The owner additionally sees the "bots" tab
 * (bot verifications are owner-only, matching the standalone bot_verifications.php).
 * Non-owner admins with the 'channels' permission see only the channels tab.
 *
 * Both channels and bot_verifications are MANDATORY only on this page (no task
 * mode). Reward-on-join / reward-on-start tasks are managed entirely from the
 * Tasks page (admin/pages/tasks.php) — which can also CREATE a new channel/bot
 * inline when building a task.
 *
 * Tabs:
 *   - channels  (default): list + add form for channels (existing behaviour)
 *   - bots:              list + add form + edit modal for bot verifications
 *                        (mirrors bot_verifications.php)
 *
 * POST actions (CSRF-guarded by admin/index.php before this file loads):
 *   Channel: add | toggle | delete
 *   Bot:     bot_add | bot_update | bot_toggle | bot_delete
 *            (prefixed to avoid colliding with the channel actions)
 */

$pageTitle = 'مدیریت کانال‌ها و ربات‌ها';

// Permission: owner OR 'channels'. Owner sees both tabs; non-owner with
// 'channels' permission sees only the channels tab.
$canChannels = $adminAuth->isOwner() || $adminAuth->hasPermission('channels');
$canBots     = $adminAuth->isOwner();

if (!$canChannels && !$canBots) {
    http_response_code(403);
    echo 'Access Denied';
    exit;
}

// ── Active tab resolution (SSR default) ─────────────────────────────
// The tab is only used to decide which div is visible on first paint. Tab
// switching itself is fully client-side (with URL-hash deep-linking).
$tab = $_GET['tab'] ?? 'channels';
if (!in_array($tab, ['channels', 'bots'], true)) {
    $tab = 'channels';
}
// Hide a tab from a user who lacks its specific permission. (Owner sees both.)
if ($tab === 'channels' && !$canChannels) {
    $tab = $canBots ? 'bots' : 'channels';
}
if ($tab === 'bots' && !$canBots) {
    $tab = $canChannels ? 'channels' : 'bots';
}

// ── POST handlers (CSRF already verified in admin/index.php) ───────
// Each branch sets a flash + redirects back to the appropriate tab.
if (isset($_POST['action'])) {
    $redirectTab = 'channels'; // default for channel actions

    // ═══ Channel actions ═══
    if ($canChannels && $_POST['action'] === 'add') {
        // Form payload: display name + numeric id + type + (handle | join_link)
        $displayName = trim($_POST['display_name'] ?? '');
        $numericId   = trim($_POST['numeric_id'] ?? '');
        $type        = $_POST['channel_type'] ?? 'public';

        // SECURITY: validate input lengths to prevent abuse / DB bloat.
        if (mb_strlen($displayName) > 100) {
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'نام نمایشی خیلی طولانی است (حداکثر ۱۰۰ کاراکتر).'];
        } elseif (mb_strlen($numericId) > 64) {
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'شناسه عددی خیلی طولانی است (حداکثر ۶۴ کاراکتر).'];
        } elseif ($displayName === '' || $numericId === '') {
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'نام نمایشی و شناسه عددی الزامی هستند.'];
        } else {
            // Mandatory mode — classic VPN-bot behaviour.
            $resolved = resolveChannelHandleAndLink($type, $_POST);
            if (is_array($resolved)) {
                [$handle, $joinLink] = $resolved;
                Database::addChannel($handle, $displayName, $type, $numericId, $joinLink, 'mandatory', null, null);
                AdminDB::logAction($currentUser['user_id'], 'add_channel', 'channel', $displayName, "type={$type},mode=mandatory,id={$numericId}");
                $_SESSION['flash'] = ['type' => 'success', 'msg' => "«{$displayName}» اضافه شد."];
            } else {
                $_SESSION['flash'] = ['type' => 'error', 'msg' => $resolved];
            }
        }
    }

    if ($canChannels && $_POST['action'] === 'toggle') {
        $handle = $_POST['handle'] ?? '';
        $active = (int)($_POST['active'] ?? 0);
        Database::setChannelActive($handle, (bool)$active);
        AdminDB::logAction($currentUser['user_id'], 'toggle_channel', 'channel', $handle, "active=$active");
    }

    if ($canChannels && $_POST['action'] === 'delete') {
        $handle = $_POST['handle'] ?? '';
        Database::removeChannel($handle);
        AdminDB::logAction($currentUser['user_id'], 'delete_channel', 'channel', $handle);
        $_SESSION['flash'] = ['type' => 'success', 'msg' => 'حذف شد.'];
    }

    // ═══ Bot actions (owner-only — matches bot_verifications.php) ═══
    if ($canBots && $_POST['action'] === 'bot_add') {
        $redirectTab = 'bots';
        $botUsername = trim($_POST['bot_username'] ?? '');
        $apiUrl      = trim($_POST['api_url'] ?? '');
        $apiKey      = trim($_POST['api_key'] ?? '');

        $ok = true;
        if ($botUsername === '' || !preg_match('/^@?[a-zA-Z][a-zA-Z0-9_]{3,31}$/', ltrim($botUsername, '@'))) {
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'یوزرنیم ربات نامعتبر است (۵-۳۲ کاراکتر، شروع با حرف).'];
            $ok = false;
        } elseif (!preg_match('#^https?://#i', $apiUrl)) {
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'آدرس API باید با http:// یا https:// شروع شود.'];
            $ok = false;
        } elseif (mb_strlen($apiUrl) > 500) {
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'آدرس API خیلی طولانی است.'];
            $ok = false;
        } elseif ($apiKey === '') {
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'API Key الزامی است.'];
            $ok = false;
        }

        if ($ok) {
            if ($botUsername[0] !== '@') {
                $botUsername = '@' . $botUsername;
            }
            $newId = Database::addBotVerification(
                $botUsername, $apiUrl, $apiKey, 'mandatory', null, null
            );
            AdminDB::logAction(
                (int)$currentUser['user_id'], 'add_bot_verification',
                'bot_verification', (string)$newId,
                "mode=mandatory,bot={$botUsername}"
            );
            $_SESSION['flash'] = ['type' => 'success', 'msg' => "«{$botUsername}» به‌عنوان بررسی اجباری اضافه شد."];
        }
    }

    if ($canBots && $_POST['action'] === 'bot_update') {
        $redirectTab = 'bots';
        $id          = (int)($_POST['id'] ?? 0);
        $botUsername = trim($_POST['bot_username'] ?? '');
        $apiUrl      = trim($_POST['api_url'] ?? '');
        $apiKey      = trim($_POST['api_key'] ?? '');

        $existing = $id > 0 ? Database::getBotVerification($id) : null;

        $ok = true;
        if ($existing === null) {
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'مورد یافت نشد.'];
            $ok = false;
        } elseif ($botUsername === '' || !preg_match('/^@?[a-zA-Z][a-zA-Z0-9_]{3,31}$/', ltrim($botUsername, '@'))) {
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'یوزرنیم ربات نامعتبر است (۵-۳۲ کاراکتر، شروع با حرف).'];
            $ok = false;
        } elseif (!preg_match('#^https?://#i', $apiUrl)) {
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'آدرس API باید با http:// یا https:// شروع شود.'];
            $ok = false;
        } elseif (mb_strlen($apiUrl) > 500) {
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'آدرس API خیلی طولانی است.'];
            $ok = false;
        } elseif ($apiKey === '') {
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'API Key الزامی است.'];
            $ok = false;
        }

        if ($ok) {
            if ($botUsername[0] !== '@') {
                $botUsername = '@' . $botUsername;
            }
            Database::updateBotVerification(
                $id, $botUsername, $apiUrl, $apiKey, 'mandatory', null, null
            );
            AdminDB::logAction(
                (int)$currentUser['user_id'], 'update_bot_verification',
                'bot_verification', (string)$id,
                "mode=mandatory,bot={$botUsername}"
            );
            $_SESSION['flash'] = ['type' => 'success', 'msg' => "بررسی ربات #{$id} به‌روزرسانی شد."];
        }
    }

    if ($canBots && $_POST['action'] === 'bot_toggle') {
        $redirectTab = 'bots';
        $id       = (int)($_POST['id'] ?? 0);
        $existing = $id > 0 ? Database::getBotVerification($id) : null;
        if ($existing === null) {
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'مورد یافت نشد.'];
        } else {
            $newActive = !$existing['is_active'];
            Database::setBotVerificationActive($id, $newActive);
            AdminDB::logAction(
                (int)$currentUser['user_id'], 'toggle_bot_verification',
                'bot_verification', (string)$id,
                'active=' . ($newActive ? '1' : '0')
            );
            $_SESSION['flash'] = ['type' => 'success', 'msg' => $newActive ? 'فعال شد.' : 'غیرفعال شد.'];
        }
    }

    if ($canBots && $_POST['action'] === 'bot_delete') {
        $redirectTab = 'bots';
        $id       = (int)($_POST['id'] ?? 0);
        $existing = $id > 0 ? Database::getBotVerification($id) : null;
        if ($existing === null) {
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'مورد یافت نشد.'];
        } else {
            Database::deleteBotVerification($id);
            AdminDB::logAction(
                (int)$currentUser['user_id'], 'delete_bot_verification',
                'bot_verification', (string)$id,
                "bot=" . ($existing['bot_username'] ?? '')
            );
            $_SESSION['flash'] = ['type' => 'success', 'msg' => 'حذف شد.'];
        }
    }

    header("Location: ?page=channels&tab=" . $redirectTab);
    exit;
}

/**
 * Resolve a channel's handle + join_link from the POST payload based on the
 * chosen channel_type. Returns [handle, joinLink] on success, or a Persian
 * error string on failure.
 *
 * @return array{0:string,1:?string}|string
 */
function resolveChannelHandleAndLink(string $type, array $post): array|string
{
    if ($type === 'private') {
        $joinLink = trim($post['join_link'] ?? '');
        if ($joinLink === '') {
            return 'برای کانال/گروه خصوصی لینک عضویت الزامی است.';
        }
        if (!preg_match('#^https://t\.me/(\+[A-Za-z0-9_-]{5,}|joinchat/[A-Za-z0-9_-]{5,})$#', $joinLink)) {
            return 'لینک عضویت نامعتبر است. باید با https://t.me/+... شروع شود.';
        }
        // For private channels/groups use the numeric id as the unique handle
        // key (so getChatMember can be called with it later). The join_link is
        // what the user actually clicks.
        return [(string)$post['numeric_id'], $joinLink];
    }

    // Public channel/group: handle is the @username.
    $handle = trim($post['handle'] ?? '');
    if ($handle === '') {
        return 'برای کانال/گروه عمومی یوزرنیم (@username) الزامی است.';
    }
    if (!preg_match('/^@?[a-zA-Z][a-zA-Z0-9_]{3,31}$/', ltrim($handle, '@'))) {
        return 'یوزرنیم کانال نامعتبر است (۵-۳۲ کاراکتر، شروع با حرف).';
    }
    if ($handle[0] !== '@') {
        $handle = '@' . $handle;
    }
    return [$handle, null];
}

/**
 * Mask an API key for display: first 6 + last 4 chars.
 * Short keys (<=10 chars) are fully masked.
 */
function maskApiKey(string $key): string
{
    $len = mb_strlen($key);
    if ($len <= 10) return str_repeat('•', $len);
    return mb_substr($key, 0, 6) . '…' . mb_substr($key, -4);
}

// ── Load data ───────────────────────────────────────────────────────────
$channels = AdminDB::getAllChannels();
$bvs      = $canBots ? Database::getAllBotVerifications() : [];

require __DIR__ . '/layout_top.php';
?>

<div class="page-header">
    <h1><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-3px;margin-left:6px;"><path d="m3 11 18-5v12L3 14v-3z"/><path d="M11.6 16.8a3 3 0 1 1-5.8-1.6"/></svg> مدیریت کانال‌ها و ربات‌ها</h1>
    <span class="breadcrumb">خانه / کانال‌ها و ربات‌ها</span>
</div>

<?php if ($flash): ?>
    <div class="alert alert-<?= e($flash['type']) ?>" style="margin-bottom:16px;"><?= e($flash['msg']) ?></div>
<?php endif; ?>

<!-- ═══ Tabs (client-side toggle, no page reload) ═══ -->
<div class="glass-card" style="padding:6px;margin-bottom:20px;display:flex;gap:6px;flex-wrap:wrap;">
    <?php if ($canChannels): ?>
    <button type="button" id="tabBtnChannels" class="btn btn-sm" style="flex:1;min-width:140px;justify-content:center;display:inline-flex;align-items:center;gap:8px;cursor:pointer;" onclick="showTab('channels')">
        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m3 11 18-5v12L3 14v-3z"/><path d="M11.6 16.8a3 3 0 1 1-5.8-1.6"/></svg>
        کانال‌ها
        <span id="tabBadgeChannels" style="background:rgba(34,211,238,0.15);color:#22d3ee;padding:1px 8px;border-radius:50px;font-size:11px;font-weight:700;"><?= count($channels) ?></span>
    </button>
    <?php endif; ?>
    <?php if ($canBots): ?>
    <button type="button" id="tabBtnBots" class="btn btn-sm" style="flex:1;min-width:140px;justify-content:center;display:inline-flex;align-items:center;gap:8px;cursor:pointer;" onclick="showTab('bots')">
        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M21.94 13.5a9 9 0 0 0-.4-2.3l1.96-1.5-2-3.46-2.31.94a9 9 0 0 0-2-1.15L16.5 3.5h-4l-.69 2.53a9 9 0 0 0-2 1.15l-2.31-.94-2 3.46 1.96 1.5a9 9 0 0 0 0 4.6l-1.96 1.5 2 3.46 2.31-.94a9 9 0 0 0 2 1.15l.69 2.53h4l.69-2.53a9 9 0 0 0 2-1.15l2.31.94 2-3.46-1.96-1.5a9 9 0 0 0 .4-2.3Z"/></svg>
        ربات‌ها
        <span id="tabBadgeBots" style="background:rgba(52,211,153,0.15);color:#34d399;padding:1px 8px;border-radius:50px;font-size:11px;font-weight:700;"><?= count($bvs) ?></span>
    </button>
    <?php endif; ?>
</div>

<!-- ═══════════════════════════════════════════════════════════════════ -->
<!-- CHANNELS TAB                                                       -->
<!-- ═══════════════════════════════════════════════════════════════════ -->
<div id="tab-channels"<?= $canChannels ? '' : ' style="display:none;"' ?>>
<?php if ($adminAuth->hasPermission('channels')): ?>
<div class="glass-card" style="margin-bottom:24px;">
    <div class="card-title" style="margin-bottom:16px;display:flex;align-items:center;gap:8px;"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="M12 5v14"/></svg> افزودن گروه/کانال جدید</div>

    <!-- Step 1: choose channel type -->
    <div class="form-group" style="margin-bottom:16px;">
        <label>نوع (عمومی / خصوصی)</label>
        <div style="display:flex;gap:12px;flex-wrap:wrap;">
            <label style="display:flex;align-items:center;gap:6px;cursor:pointer;padding:10px 16px;border:1px solid var(--border);border-radius:10px;">
                <input type="radio" name="channel_type_picker" value="public" checked onchange="switchChannelType('public')">
                <span style="display:inline-flex;align-items:center;gap:6px;"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/></svg> عمومی (Public) — دارای @username</span>
            </label>
            <label style="display:flex;align-items:center;gap:6px;cursor:pointer;padding:10px 16px;border:1px solid var(--border);border-radius:10px;">
                <input type="radio" name="channel_type_picker" value="private" onchange="switchChannelType('private')">
                <span style="display:inline-flex;align-items:center;gap:6px;"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="18" height="11" x="3" y="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg> خصوصی (Private) — با لینک دعوت</span>
            </label>
        </div>
        <small style="color:var(--text-muted);display:block;margin-top:6px;">این نوع برای هر دو «گروه» و «کانال» (عمومی یا خصوصی) کار می‌کند. همهٔ کانال‌ها به‌صورت اجباری ذخیره می‌شوند — برای ساخت تسک عضویت پاداش‌دار به صفحهٔ <a href="?page=tasks" style="color:var(--accent-cyan);">تسک‌ها</a> مراجعه کنید.</small>
    </div>

    <form method="POST" id="addChannelForm">
            <?= csrf_field() ?>
        <input type="hidden" name="action" value="add">
        <input type="hidden" name="channel_type" id="channel_type_input" value="public">

        <div class="grid-2">
            <div class="form-group">
                <label>۱) نام نمایشی</label>
                <input type="text" name="display_name" class="form-control" placeholder="مثال: کانال رسمی نترکس" required>
                <small style="color:var(--text-muted);">این نام روی دکمه عضویت به کاربر نمایش داده می‌شود.</small>
            </div>
            <div class="form-group">
                <label>۲) شناسه عددی چت (Numeric ID)</label>
                <input type="text" name="numeric_id" class="form-control" placeholder="مثال: -1001676284133" required>
                <small style="color:var(--text-muted);">شناسه عددی چت گروه/کانال. برای دریافت آن می‌توانید از ربات <code>@userinfobot</code> یا <code>@getidsbot</code> استفاده کنید (ابتدا پیام گروه/کانال را فوروارد کنید).</small>
            </div>
        </div>

        <!-- Public: @username -->
        <div class="form-group" id="public_fields">
            <label>۳) یوزرنیم عمومی</label>
            <input type="text" name="handle" class="form-control" placeholder="@channel_or_group_username">
            <small style="color:var(--text-muted);">یوزرنیم عمومی (با @ شروع شود). دکمه عضویت به <code>https://t.me/username</code> هدایت می‌کند.</small>
        </div>

        <!-- Private: invite link -->
        <div class="form-group" id="private_fields" style="display:none;">
            <label>۳) لینک عضویت (دعوت)</label>
            <input type="text" name="join_link" class="form-control" placeholder="https://t.me/+AbCdEfGhIjKl">
            <small style="color:var(--text-muted);">لینک دعوت (با <code>https://t.me/+...</code> شروع می‌شود). دکمه عضویت از همین لینک استفاده می‌کند.</small>
        </div>

        <button type="submit" class="btn btn-primary" style="padding:12px 28px;margin-top:14px;">افزودن</button>
    </form>
</div>

<script>
function switchChannelType(type) {
    var pub = document.getElementById('public_fields');
    var prv = document.getElementById('private_fields');
    var input = document.getElementById('channel_type_input');
    if (type === 'private') {
        pub.style.display = 'none';
        prv.style.display = '';
        input.value = 'private';
        var h = document.querySelector('#addChannelForm input[name="handle"]');
        var l = document.querySelector('#addChannelForm input[name="join_link"]');
        if (h) h.required = false;
        if (l) l.required = true;
    } else {
        pub.style.display = '';
        prv.style.display = 'none';
        input.value = 'public';
        var h = document.querySelector('#addChannelForm input[name="handle"]');
        var l = document.querySelector('#addChannelForm input[name="join_link"]');
        if (h) h.required = true;
        if (l) l.required = false;
    }
}
</script>
<?php endif; ?>

<div class="glass-card">
    <div class="card-header">
        <span class="card-title">لیست (<?= count($channels) ?>)</span>
    </div>
    <?php if (empty($channels)): ?>
        <div class="empty-state"><div class="empty-icon"><svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 12h-6l-2 3h-4l-2-3H2"/><path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/></svg></div><div class="empty-text">موردی ثبت نشده</div></div>
    <?php else: ?>
    <div class="table-container">
        <table>
            <thead><tr><th>نام نمایشی</th><th>نوع</th><th>شناسه / یوزرنیم</th><th>وضعیت</th><th>تاریخ افزودن</th><th>عملیات</th></tr></thead>
            <tbody>
                <?php foreach ($channels as $ch):
                    $displayName = $ch['display_name'] ?? null;
                    if ($displayName === null || $displayName === '') {
                        $displayName = $ch['channel_handle'];
                    }
                    $type      = $ch['channel_type'] ?? 'public';
                    $typeLabel = $type === 'private' ? '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-left:4px;"><rect width="18" height="11" x="3" y="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg> خصوصی' : '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-left:4px;"><circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/></svg> عمومی';

                    $numericId = $ch['numeric_id'] ?? null;
                    if ($type === 'private' && !empty($numericId)) {
                        $idOrHandle = '<code>' . e($numericId) . '</code>';
                    } else {
                        $idOrHandle = e($ch['channel_handle']);
                    }
                ?>
                <tr>
                    <td style="font-weight:600;"><?= e($displayName) ?></td>
                    <td><?= $typeLabel ?></td>
                    <td style="font-size:12px;"><?= $idOrHandle ?></td>
                    <td>
                        <span class="badge <?= $ch['is_active'] ? 'badge-active' : 'badge-inactive' ?>">
                            <?= $ch['is_active'] ? 'فعال' : 'غیرفعال' ?>
                        </span>
                    </td>
                    <td style="font-size:12px;color:var(--text-muted);"><?= e($ch['created_at'] ?? '') ?></td>
                    <td>
                        <div style="display:flex;gap:6px;flex-wrap:wrap;">
                            <?php if ($adminAuth->hasPermission('channels')): ?>
                            <form method="POST" style="display:inline;">
            <?= csrf_field() ?>
                                <input type="hidden" name="action" value="toggle">
                                <input type="hidden" name="handle" value="<?= e($ch['channel_handle']) ?>">
                                <input type="hidden" name="active" value="<?= $ch['is_active'] ? 0 : 1 ?>">
                                <button class="btn btn-glass btn-xs" style="display:inline-flex;align-items:center;gap:4px;"><?php if ($ch['is_active']): ?><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/></svg><?php else: ?><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="6 3 20 12 6 21 6 3"/></svg><?php endif; ?> <?= $ch['is_active'] ? 'غیرفعال' : 'فعال' ?></button>
                            </form>

                            <form method="POST" style="display:inline;" onsubmit="return confirm('حذف؟')">
            <?= csrf_field() ?>
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="handle" value="<?= e($ch['channel_handle']) ?>">
                                <button class="btn btn-danger btn-xs" style="display:inline-flex;align-items:center;"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/><line x1="10" x2="10" y1="11" y2="17"/><line x1="14" x2="14" y1="11" y2="17"/></svg></button>
                            </form>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>
</div><!-- /#tab-channels -->

<!-- ═══════════════════════════════════════════════════════════════════ -->
<!-- BOTS TAB                                                           -->
<!-- ═══════════════════════════════════════════════════════════════════ -->
<div id="tab-bots"<?= $canBots ? '' : ' style="display:none;"' ?>>
<!-- Info banner (always visible inside the bots tab) -->
<div class="glass-card" style="margin-bottom:24px;border-right:3px solid var(--accent-cyan);">
    <div style="display:flex;gap:12px;align-items:flex-start;">
        <div style="flex-shrink:0;color:#22d3ee;">
            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg>
        </div>
        <div style="font-size:13px;line-height:1.9;color:var(--text-muted);">
            در این بخش ربات‌های تلگرام قبلی را اضافه کنید تا ربات بررسی کند آیا کاربر آن‌ها را استارت کرده یا نه.
            <br>
            <strong style="color:#7da9ff;">جوین اجباری (mandatory):</strong> کاربر تا زمانی که ربات‌های اجباری را استارت نکرده باشد، نمی‌تواند از ربات استفاده کند.
            <br>
            برای ساخت تسک استارتِ پاداش‌دار به صفحهٔ <a href="?page=tasks" style="color:var(--accent-cyan);">تسک‌ها</a> مراجعه کنید.
            <br>
            برای هر ربات، آدرس فایل API (<code>check_started.php</code>) و یک API Key (با مجوز <code>users:read</code> از پنل ادمین ربات قبلی) نیاز است.
        </div>
    </div>
</div>

<!-- Add form -->
<div class="glass-card" style="margin-bottom:24px;">
    <div class="card-title" style="margin-bottom:16px;display:flex;align-items:center;gap:8px;">
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="M12 5v14"/></svg>
        افزودن ربات برای بررسی
    </div>

    <form method="POST" id="addBotVerificationForm">
        <?= csrf_field() ?>
        <input type="hidden" name="action" value="bot_add">

        <div class="form-group">
            <label>۱) یوزرنیم ربات</label>
            <input type="text" name="bot_username" class="form-control" placeholder="@OldNetrexBot" required maxlength="33">
            <small style="color:var(--text-muted);">یوزرنیم تلگرام ربات قبلی (با @ شروع شود). دکمه استارت به <code>https://t.me/&lt;username&gt;?start=netrex</code> هدایت می‌شود.</small>
        </div>

        <div class="form-group">
            <label>۲) آدرس API (check_started.php)</label>
            <input type="text" name="api_url" class="form-control" placeholder="https://your-old-site.com/admin/api/check_started.php" required maxlength="500">
            <small style="color:var(--text-muted);">آدرس کامل فایل <code>check_started.php</code> روی سرور ربات قبلی. این دقیقاً همان آدرسی است که ربات فعلی برای بررسی استارت کاربر صدا می‌زند.</small>
        </div>

        <div class="form-group">
            <label>۳) API Key</label>
            <input type="text" name="api_key" class="form-control" placeholder="ntrx_..." required autocomplete="off" maxlength="200">
            <small style="color:var(--text-muted);">یک API Key که از پنل ادمین ربات قبلی ساخته شده و مجوز <code>users:read</code> دارد. این کلید برای احراز هویت درخواست بررسی استارت استفاده می‌شود.</small>
        </div>

        <button type="submit" class="btn btn-primary" style="padding:12px 28px;margin-top:14px;">افزودن</button>
    </form>
</div>

<!-- List table -->
<div class="glass-card">
    <div class="card-header">
        <span class="card-title">لیست ربات‌ها (<?= count($bvs) ?>)</span>
    </div>
    <?php if (empty($bvs)): ?>
        <div class="empty-state">
            <div class="empty-icon"><svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="18" height="10" x="3" y="11" rx="2"/><circle cx="12" cy="5" r="2"/><path d="M12 7v4"/><line x1="8" x2="8" y1="16" y2="16"/><line x1="16" x2="16" y1="16" y2="16"/></svg></div>
            <div class="empty-text">هنوز رباتی برای بررسی ثبت نشده</div>
        </div>
    <?php else: ?>
    <div class="table-container">
        <table>
            <thead><tr><th>#</th><th>ربات</th><th>آدرس API</th><th>API Key</th><th>وضعیت</th><th>تاریخ افزودن</th><th>عملیات</th></tr></thead>
            <tbody>
                <?php foreach ($bvs as $bv):
                    $id       = (int)$bv['id'];
                    $username = (string)($bv['bot_username'] ?? '');
                    // Strip leading @ for the t.me link.
                    $usernameClean = ltrim($username, '@');
                    $startLink = 'https://t.me/' . rawurlencode($usernameClean) . '?start=netrex';

                    $apiUrlFull = (string)($bv['api_url'] ?? '');
                    $apiUrlShort = mb_strlen($apiUrlFull) > 50 ? mb_substr($apiUrlFull, 0, 50) . '…' : $apiUrlFull;

                    $apiKeyMasked = maskApiKey((string)($bv['api_key'] ?? ''));

                    $isActive = (bool)($bv['is_active'] ?? false);

                    // JSON payload for the edit modal (api_key exposed in full
                    // here because the owner needs to edit it; this is the
                    // admin panel, not the public API).
                    $editPayload = json_encode([
                        'id'           => $id,
                        'bot_username' => $username,
                        'api_url'      => $apiUrlFull,
                        'api_key'      => (string)($bv['api_key'] ?? ''),
                    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_APOS | JSON_HEX_QUOT);
                ?>
                <tr>
                    <td style="color:var(--text-muted);">#<?= $id ?></td>
                    <td style="font-weight:600;">
                        <?= e($username) ?>
                        <a href="<?= e($startLink) ?>" target="_blank" rel="noopener" title="باز کردن لینک استارت" style="margin-right:6px;color:#22d3ee;text-decoration:none;display:inline-flex;align-items:center;vertical-align:-2px;">
                            <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7 7h10v10"/><path d="M7 17 17 7"/></svg>
                        </a>
                    </td>
                    <td style="font-size:12px;max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="<?= e($apiUrlFull) ?>"><?= e($apiUrlShort) ?></td>
                    <td style="font-size:12px;font-family:monospace;"><?= e($apiKeyMasked) ?></td>
                    <td>
                        <span class="badge <?= $isActive ? 'badge-active' : 'badge-inactive' ?>">
                            <?= $isActive ? 'فعال' : 'غیرفعال' ?>
                        </span>
                    </td>
                    <td style="font-size:12px;color:var(--text-muted);"><?= e($bv['created_at'] ?? '') ?></td>
                    <td>
                        <div style="display:flex;gap:6px;flex-wrap:wrap;">
                            <form method="POST" style="display:inline;">
                                <?= csrf_field() ?>
                                <input type="hidden" name="action" value="bot_toggle">
                                <input type="hidden" name="id" value="<?= $id ?>">
                                <button class="btn btn-glass btn-xs" style="display:inline-flex;align-items:center;gap:4px;" title="<?= $isActive ? 'غیرفعال کردن' : 'فعال کردن' ?>">
                                    <?php if ($isActive): ?>
                                    <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/></svg>
                                    غیرفعال
                                    <?php else: ?>
                                    <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="6 3 20 12 6 21 6 3"/></svg>
                                    فعال
                                    <?php endif; ?>
                                </button>
                            </form>

                            <button class="btn btn-glass btn-xs" style="display:inline-flex;align-items:center;gap:4px;color:#22d3ee;"
                                    onclick='return openEditBvModal(this)'
                                    data-bv="<?= e($editPayload) ?>"
                                    title="ویرایش">
                                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.119 2.119 0 0 1 3 3L12 15l-4 1 1-4Z"/></svg>
                                ویرایش
                            </button>

                            <form method="POST" style="display:inline;" onsubmit="return confirm('این بررسی ربات حذف شود؟')">
                                <?= csrf_field() ?>
                                <input type="hidden" name="action" value="bot_delete">
                                <input type="hidden" name="id" value="<?= $id ?>">
                                <button class="btn btn-danger btn-xs" style="display:inline-flex;align-items:center;" title="حذف">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/><line x1="10" x2="10" y1="11" y2="17"/><line x1="14" x2="14" y1="11" y2="17"/></svg>
                                </button>
                            </form>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>

<!-- Edit modal -->
<div id="editBvModal" style="display:none;position:fixed;inset:0;z-index:100;align-items:center;justify-content:center;padding:16px;">
    <div onclick="closeEditBvModal()" style="position:absolute;inset:0;background:rgba(0,0,0,0.6);backdrop-filter:blur(4px);"></div>
    <div style="position:relative;width:100%;max-width:560px;background:rgba(10,12,26,0.95);border:1px solid rgba(34,211,238,0.2);backdrop-filter:blur(30px);border-radius:18px;padding:24px;box-shadow:0 20px 60px rgba(0,0,0,0.5);animation:nx-fade-up 0.4s both;">
        <button onclick="closeEditBvModal()" style="position:absolute;left:16px;top:16px;width:32px;height:32px;display:grid;place-items:center;border-radius:8px;background:transparent;border:none;color:#9fb0c9;cursor:pointer;">
            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
        </button>
        <h3 style="margin-bottom:18px;color:#e6f0ff;font-size:16px;font-weight:700;display:flex;align-items:center;gap:6px;">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.119 2.119 0 0 1 3 3L12 15l-4 1 1-4Z"/></svg>
            ویرایش بررسی ربات <span id="editBvId" style="color:#22d3ee;"></span>
        </h3>

        <form method="POST" id="editBvForm">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="bot_update">
            <input type="hidden" name="id" id="edit_bv_id" value="">

            <div class="form-group">
                <label>یوزرنیم ربات</label>
                <input type="text" name="bot_username" id="edit_bot_username" class="form-control" required maxlength="33">
            </div>

            <div class="form-group">
                <label>آدرس API</label>
                <input type="text" name="api_url" id="edit_api_url" class="form-control" required maxlength="500">
            </div>

            <div class="form-group">
                <label>API Key</label>
                <input type="text" name="api_key" id="edit_api_key" class="form-control" required autocomplete="off" maxlength="200">
                <small style="color:var(--text-muted);">کلید فعلی به‌صورت متن پر شده است. در صورت نیاز می‌توانید آن را ویرایش کنید.</small>
            </div>

            <div style="display:flex;gap:8px;justify-content:flex-end;">
                <button type="button" class="btn btn-glass btn-sm" onclick="closeEditBvModal()">لغو</button>
                <button type="submit" class="btn btn-primary btn-sm">ذخیره تغییرات</button>
            </div>
        </form>
    </div>
</div>

<script>
// ── Edit modal: open/close ─────────────────────────────────────────────
function openEditBvModal(btn) {
    var data = JSON.parse(btn.getAttribute('data-bv'));
    document.getElementById('edit_bv_id').value        = data.id;
    document.getElementById('edit_bot_username').value = data.bot_username || '';
    document.getElementById('edit_api_url').value      = data.api_url || '';
    document.getElementById('edit_api_key').value      = data.api_key || '';
    document.getElementById('editBvId').textContent    = '#' + data.id;

    var modal = document.getElementById('editBvModal');
    modal.style.display = 'flex';
    return false;
}
function closeEditBvModal() {
    document.getElementById('editBvModal').style.display = 'none';
}
</script>
</div><!-- /#tab-bots -->

<script>
// ═══ Tab switching (pure client-side; no network round-trip) ═══
function showTab(name) {
    var cEl = document.getElementById('tab-channels');
    var bEl = document.getElementById('tab-bots');
    var cBtn = document.getElementById('tabBtnChannels');
    var bBtn = document.getElementById('tabBtnBots');
    if (cEl) cEl.style.display = (name === 'channels') ? '' : 'none';
    if (bEl) bEl.style.display = (name === 'bots') ? '' : 'none';
    // Toggle the active button styling.
    if (cBtn) {
        cBtn.classList.remove('btn-primary');
        cBtn.classList.add('btn-glass');
    }
    if (bBtn) {
        bBtn.classList.remove('btn-primary');
        bBtn.classList.add('btn-glass');
    }
    if (name === 'channels' && cBtn) {
        cBtn.classList.remove('btn-glass');
        cBtn.classList.add('btn-primary');
    }
    if (name === 'bots' && bBtn) {
        bBtn.classList.remove('btn-glass');
        bBtn.classList.add('btn-primary');
    }
    // Update the URL hash so a refresh keeps the user on the same tab.
    try { history.replaceState(null, '', '#tab=' + encodeURIComponent(name)); } catch (e) {}
}

// ═══ Boot: pick the initial tab from URL hash > ?tab= > default 'channels' ═══
(function() {
    var initial = '<?= e($tab) ?>';
    try {
        var h = (window.location.hash || '').match(/tab=([a-z]+)/);
        if (h && (h[1] === 'channels' || h[1] === 'bots')) initial = h[1];
    } catch (e) {}
    showTab(initial);
})();
</script>

<?php require __DIR__ . '/layout_bottom.php'; ?>
