<?php
/**
 * tasks.php — manage task system: channel-join tasks + free-form text tasks.
 *
 * Permission: owner OR 'tasks'.
 *
 * Three sections:
 *   1. Pending text-task answers (mini-review queue, links to task_detail).
 *   2. All tasks table (edit / delete actions).
 *   3. Create-task form (channel | text) with 3-currency rewards.
 *
 * Reward model: three independent amounts (reward_game_tokens, reward_toman,
 * reward_ntx) — 0 means "don't give that currency". Any combination is allowed.
 * The legacy reward_type/reward_amount params are passed as 'game_token'/0 for
 * backward compatibility; the three new params are the source of truth.
 *
 * POST actions (CSRF-guarded by index.php before this file loads):
 *   - create_task
 *   - update_task
 *   - delete_task
 */

$pageTitle = 'مدیریت تسک‌ها';

// ── Permission gate ──────────────────────────────────────────────────────
if (!$adminAuth->isOwner() && !$adminAuth->hasPermission('tasks')) {
    http_response_code(403);
    echo 'Access Denied';
    exit;
}

global $config;

// ── POST handlers ────────────────────────────────────────────────────────
if (isset($_POST['action'])) {
    if ($_POST['action'] === 'create_task') {
        $type             = $_POST['type'] ?? '';
        $title            = trim($_POST['title'] ?? '');
        $description      = trim($_POST['description'] ?? '');
        $rewardGameTokens = max(0, (int)($_POST['reward_game_tokens'] ?? 0));
        $rewardToman      = max(0, (int)($_POST['reward_toman']      ?? 0));
        $rewardNtx        = max(0, (int)($_POST['reward_ntx']        ?? 0));
        $channelId        = (int)($_POST['channel_id'] ?? 0);
        $botVerificationId = (int)($_POST['bot_verification_id'] ?? 0);

        // Validate type. T46-l: the seven configurable types join the list.
        if (!in_array($type, ['channel', 'text', 'bot', 'group_add', 'group_msgs', 'race', 'referrals', 'play_games', 'win_games', 'manual'], true)) {
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'نوع تسک نامعتبر است.'];
            header('Location: ?page=tasks');
            exit;
        }
        // Validate title.
        if ($title === '' || mb_strlen($title) > 255) {
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'عنوان تسک الزامی است (حداکثر ۲۵۵ کاراکتر).'];
            header('Location: ?page=tasks');
            exit;
        }

        try {
            if ($type === 'channel') {
                // Two paths: pick an existing channel, or create a new one
                // inline. When channel_new=1, the channel fields are present
                // in the POST and we create the channel first (always in
                // 'mandatory' mode — the task created below is what flips it
                // to 'task' mode via TaskSystem::createChannelTask).
                $isChannelNew = isset($_POST['channel_new']) && $_POST['channel_new'] === '1';

                if ($isChannelNew) {
                    $displayName = trim($_POST['new_channel_display_name'] ?? '');
                    $numericId   = trim($_POST['new_channel_numeric_id'] ?? '');
                    $chType      = ($_POST['new_channel_type'] ?? 'public') === 'private' ? 'private' : 'public';

                    if (mb_strlen($displayName) > 100) {
                        $_SESSION['flash'] = ['type' => 'error', 'msg' => 'نام نمایشی خیلی طولانی است (حداکثر ۱۰۰ کاراکتر).'];
                        header('Location: ?page=tasks');
                        exit;
                    }
                    if (mb_strlen($numericId) > 64) {
                        $_SESSION['flash'] = ['type' => 'error', 'msg' => 'شناسه عددی خیلی طولانی است (حداکثر ۶۴ کاراکتر).'];
                        header('Location: ?page=tasks');
                        exit;
                    }
                    if ($displayName === '' || $numericId === '') {
                        $_SESSION['flash'] = ['type' => 'error', 'msg' => 'نام نمایشی و شناسه عددی کانال الزامی هستند.'];
                        header('Location: ?page=tasks');
                        exit;
                    }

                    // Resolve handle + join_link from the chosen type.
                    $resolved = tasks_resolve_new_channel_handle_and_link($chType, $_POST);
                    if (is_array($resolved)) {
                        [$handle, $joinLink] = $resolved;
                    } else {
                        $_SESSION['flash'] = ['type' => 'error', 'msg' => $resolved];
                        header('Location: ?page=tasks');
                        exit;
                    }

                    // Create the channel in mandatory mode. createChannelTask
                    // below will transition it into 'task' mode + reward snapshot.
                    $channelId = Database::addChannel(
                        $handle, $displayName, $chType, $numericId, $joinLink,
                        'mandatory', null, null
                    );
                    AdminDB::logAction(
                        (int)$currentUser['user_id'], 'add_channel',
                        'channel', $displayName,
                        "type={$chType},mode=mandatory,id={$numericId},via=tasks"
                    );
                    if ($channelId <= 0) {
                        $_SESSION['flash'] = ['type' => 'error', 'msg' => 'خطا در ایجاد کانال.'];
                        header('Location: ?page=tasks');
                        exit;
                    }
                } else {
                    if ($channelId <= 0) {
                        $_SESSION['flash'] = ['type' => 'error', 'msg' => 'انتخاب کانال برای تسک کانالی الزامی است.'];
                        header('Location: ?page=tasks');
                        exit;
                    }
                    $channel = Database::getChannelById($channelId);
                    if ($channel === null) {
                        $_SESSION['flash'] = ['type' => 'error', 'msg' => 'کانال یافت نشد.'];
                        header('Location: ?page=tasks');
                        exit;
                    }
                }

                $newId = TaskSystem::createChannelTask(
                    $channelId, $title, $description !== '' ? $description : null,
                    'game_token', 0, (int)$currentUser['user_id'],
                    $rewardGameTokens, $rewardToman, $rewardNtx
                );
                AdminDB::logAction((int)$currentUser['user_id'], 'create_task', 'task', (string)$newId,
                    "type=channel,channel={$channelId},new=" . ($isChannelNew ? '1' : '0') . ",reward=gt:{$rewardGameTokens},to:{$rewardToman},ntx:{$rewardNtx}");
            } elseif ($type === 'bot') {
                // Same two-path approach: pick an existing bot_verification
                // or create one inline (always in 'mandatory' mode — the
                // task created below flips it to 'task' mode).
                $isBotNew = isset($_POST['bot_new']) && $_POST['bot_new'] === '1';

                if ($isBotNew) {
                    $botUsername = trim($_POST['new_bot_username'] ?? '');
                    $apiUrl      = trim($_POST['new_bot_api_url'] ?? '');
                    $apiKey      = trim($_POST['new_bot_api_key'] ?? '');

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

                    if ($botUsername[0] !== '@') {
                        $botUsername = '@' . $botUsername;
                    }

                    $botVerificationId = Database::addBotVerification(
                        $botUsername, $apiUrl, $apiKey, 'mandatory', null, null
                    );
                    AdminDB::logAction(
                        (int)$currentUser['user_id'], 'add_bot_verification',
                        'bot_verification', (string)$botVerificationId,
                        "mode=mandatory,bot={$botUsername},via=tasks"
                    );
                    if ($botVerificationId <= 0) {
                        $_SESSION['flash'] = ['type' => 'error', 'msg' => 'خطا در ایجاد ربات.'];
                        header('Location: ?page=tasks');
                        exit;
                    }
                } else {
                    if ($botVerificationId <= 0) {
                        $_SESSION['flash'] = ['type' => 'error', 'msg' => 'انتخاب ربات برای تسک ربات الزامی است.'];
                        header('Location: ?page=tasks');
                        exit;
                    }
                    $bv = Database::getBotVerification($botVerificationId);
                    if ($bv === null) {
                        $_SESSION['flash'] = ['type' => 'error', 'msg' => 'ربات یافت نشد.'];
                        header('Location: ?page=tasks');
                        exit;
                    }
                }

                $newId = TaskSystem::createBotTask(
                    $botVerificationId, $title, $description !== '' ? $description : null,
                    'game_token', 0, (int)$currentUser['user_id'],
                    $rewardGameTokens, $rewardToman, $rewardNtx
                );
                AdminDB::logAction((int)$currentUser['user_id'], 'create_task', 'task', (string)$newId,
                    "type=bot,bv={$botVerificationId},new=" . ($isBotNew ? '1' : '0') . ",reward=gt:{$rewardGameTokens},to:{$rewardToman},ntx:{$rewardNtx}");
            } elseif (in_array($type, ['group_add', 'group_msgs', 'race', 'referrals', 'play_games', 'win_games', 'manual'], true)) {
                // T46-l: configurable types — per-type params + (for group
                // types) the target group. createConfiguredTask validates and
                // stores the cleaned task_config JSON.
                $params = [];
                if (in_array($type, ['group_add', 'group_msgs', 'referrals', 'play_games', 'win_games', 'race'], true)) {
                    $params['count'] = max(1, (int)($_POST['task_count'] ?? 1));
                }
                if ($type === 'race') {
                    $params['action']   = (($_POST['race_action'] ?? 'message') === 'add') ? 'add' : 'message';
                    $params['count']    = max(1, (int)($_POST['race_goal'] ?? $params['count'] ?? 1));
                    $params['hours']    = max(1, (int)($_POST['race_hours'] ?? 24));
                    $params['place']    = max(1, min(10, (int)($_POST['race_place'] ?? 1)));
                    $params['race_key'] = trim((string)($_POST['race_key'] ?? ''));
                }
                $cid = 0;
                if (in_array($type, ['group_add', 'group_msgs', 'race'], true)) {
                    if ($channelId <= 0) {
                        $_SESSION['flash'] = ['type' => 'error', 'msg' => 'انتخاب گروه هدف برای این نوع تسک الزامی است.'];
                        header('Location: ?page=tasks');
                        exit;
                    }
                    $channel = Database::getChannelById($channelId);
                    if ($channel === null) {
                        $_SESSION['flash'] = ['type' => 'error', 'msg' => 'کانال/گروه هدف یافت نشد.'];
                        header('Location: ?page=tasks');
                        exit;
                    }
                    $cid = $channelId;
                }
                try {
                    $newId = TaskSystem::createConfiguredTask(
                        $type, $title, $description !== '' ? $description : null, $params,
                        $cid, $rewardGameTokens, $rewardToman, $rewardNtx, (int)$currentUser['user_id']
                    );
                    AdminDB::logAction((int)$currentUser['user_id'], 'create_task', 'task', (string)$newId,
                        "type={$type},channel={$cid},params=" . json_encode($params, JSON_UNESCAPED_UNICODE) . ",reward=gt:{$rewardGameTokens},to:{$rewardToman},ntx:{$rewardNtx}");
                    $_SESSION['flash'] = ['type' => 'success', 'msg' => "تسک #{$newId} ایجاد شد."];
                } catch (\Throwable $e) {
                    error_log('[tasks.php] create configured task failed: ' . $e->getMessage());
                    $_SESSION['flash'] = ['type' => 'error', 'msg' => 'خطا در ایجاد تسک.'];
                }
            } else { // text
                $newId = TaskSystem::createTextTask(
                    $title, $description !== '' ? $description : null,
                    'game_token', 0, (int)$currentUser['user_id'],
                    $rewardGameTokens, $rewardToman, $rewardNtx
                );
                AdminDB::logAction((int)$currentUser['user_id'], 'create_task', 'task', (string)$newId,
                    "type=text,reward=gt:{$rewardGameTokens},to:{$rewardToman},ntx:{$rewardNtx}");
            }
            $_SESSION['flash'] = ['type' => 'success', 'msg' => "تسک #{$newId} ایجاد شد."];
        } catch (\Throwable $e) {
            error_log('[tasks.php] create_task failed: ' . $e->getMessage());
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'خطا در ایجاد تسک.'];
        }
        header('Location: ?page=tasks');
        exit;
    }

    if ($_POST['action'] === 'update_task') {
        $taskId           = (int)($_POST['task_id'] ?? 0);
        $title            = trim($_POST['title'] ?? '');
        $description      = trim($_POST['description'] ?? '');
        $rewardGameTokens = max(0, (int)($_POST['reward_game_tokens'] ?? 0));
        $rewardToman      = max(0, (int)($_POST['reward_toman']      ?? 0));
        $rewardNtx        = max(0, (int)($_POST['reward_ntx']        ?? 0));
        $isActive         = isset($_POST['is_active']) && $_POST['is_active'] === '1';

        if ($taskId <= 0) {
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'شناسه تسک نامعتبر است.'];
            header('Location: ?page=tasks');
            exit;
        }
        if ($title === '' || mb_strlen($title) > 255) {
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'عنوان تسک الزامی است.'];
            header('Location: ?page=tasks');
            exit;
        }
        // Reward amounts already clamped to >= 0 above; any combination is valid.

        try {
            // T46-l: configurable tasks also merge their per-type params.
            $existingTaskRow = Database::getTask($taskId);
            $existingType = (string)($existingTaskRow['type'] ?? '');
            TaskSystem::updateTask(
                $taskId,
                $title,
                $description !== '' ? $description : null,
                'game_token',
                0,
                $isActive,
                $rewardGameTokens,
                $rewardToman,
                $rewardNtx
            );
            if (TaskSystem::isNewType($existingType)) {
                $params = [];
                if (in_array($existingType, ['group_add', 'group_msgs', 'referrals', 'play_games', 'win_games', 'race'], true)) {
                    $params['count'] = max(1, (int)($_POST['task_count'] ?? 1));
                }
                if ($existingType === 'race') {
                    $params['action']   = (($_POST['race_action'] ?? 'message') === 'add') ? 'add' : 'message';
                    $params['count']    = max(1, (int)($_POST['race_goal'] ?? $params['count'] ?? 1));
                    $params['hours']    = max(1, (int)($_POST['race_hours'] ?? 24));
                    $params['place']    = max(1, min(10, (int)($_POST['race_place'] ?? 1)));
                    $params['race_key'] = trim((string)($_POST['race_key'] ?? ''));
                }
                TaskSystem::updateConfiguredTaskParams($taskId, $params);
            }
            AdminDB::logAction(
                (int)$currentUser['user_id'],
                'update_task',
                'task',
                (string)$taskId,
                "active=" . ($isActive ? '1' : '0') . ",reward=gt:{$rewardGameTokens},to:{$rewardToman},ntx:{$rewardNtx}"
            );
            $_SESSION['flash'] = ['type' => 'success', 'msg' => "تسک #{$taskId} به‌روزرسانی شد."];
        } catch (\Throwable $e) {
            error_log('[tasks.php] update_task failed: ' . $e->getMessage());
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'خطا در به‌روزرسانی تسک.'];
        }
        header('Location: ?page=tasks');
        exit;
    }

    if ($_POST['action'] === 'delete_task') {
        $taskId = (int)($_POST['task_id'] ?? 0);
        if ($taskId <= 0) {
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'شناسه تسک نامعتبر است.'];
            header('Location: ?page=tasks');
            exit;
        }
        try {
            TaskSystem::deleteTask($taskId);
            AdminDB::logAction(
                (int)$currentUser['user_id'],
                'delete_task',
                'task',
                (string)$taskId
            );
            $_SESSION['flash'] = ['type' => 'success', 'msg' => "تسک #{$taskId} حذف شد."];
        } catch (\Throwable $e) {
            error_log('[tasks.php] delete_task failed: ' . $e->getMessage());
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'خطا در حذف تسک.'];
        }
        header('Location: ?page=tasks');
        exit;
    }
}

// ── Read data ────────────────────────────────────────────────────────────
$pendingAnswers = [];
try {
    $pendingAnswers = TaskSystem::getPendingTextAnswers();
} catch (\Throwable $e) {
    $pendingAnswers = [];
}

$tasks = [];
try {
    $tasks = TaskSystem::listAllTasks();
} catch (\Throwable $e) {
    $tasks = [];
}

// Channels NOT already linked to a task (channel_mode != 'task' AND task_id IS NULL).
// These are the candidates for the "create channel task" dropdown.
$availableChannels = [];
try {
    $allChannels = Database::getAllChannelsList();
    foreach ($allChannels as $ch) {
        $mode  = $ch['channel_mode'] ?? 'mandatory';
        $tlink = $ch['task_id'] ?? null;
        if ($mode === 'task' || $tlink !== null) continue;
        $availableChannels[] = $ch;
    }
} catch (\Throwable $e) {
    $availableChannels = [];
}

// Helper: currency name for display.
$currencyName = function (string $rewardType): string {
    global $config;
    return Settings::getMessage('currency_' . $rewardType, $config) ?: $rewardType;
};

/**
 * Format combined reward text from the three independent currency amounts.
 * Lists every non-zero currency as "{amount} {currency_name}" joined by " + ".
 * Returns "بدون پاداش" if all three are zero.
 */
$formatCombinedReward = function (int $gt, int $to, int $nx) use ($currencyName): string {
    $parts = [];
    if ($gt > 0) $parts[] = $gt . ' ' . e($currencyName('game_token'));
    if ($to > 0) $parts[] = $to . ' ' . e($currencyName('toman'));
    if ($nx > 0) $parts[] = $nx . ' ' . e($currencyName('ntx'));
    return $parts ? implode(' + ', $parts) : 'بدون پاداش';
};

/**
 * Resolve a NEW channel's handle + join_link from the POST payload based on
 * the chosen channel_type (uses the new_channel_* field prefix that the
 * "add new channel" inline form posts). Returns [handle, joinLink] on
 * success, or a Persian error string on failure.
 *
 * Local self-contained copy of the resolveChannelHandleAndLink helper that
 * lives in channels.php — kept local so tasks.php works without depending
 * on a shared include.
 *
 * @return array{0:string,1:?string}|string
 */
function tasks_resolve_new_channel_handle_and_link(string $type, array $post): array|string
{
    if ($type === 'private') {
        $joinLink = trim($post['new_channel_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 (mirrors channels.php behaviour).
        return [(string)($post['new_channel_numeric_id'] ?? ''), $joinLink];
    }

    // Public channel/group: handle is the @username.
    $handle = trim($post['new_channel_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];
}

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

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

<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="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></svg> مدیریت تسک‌ها</h1>
    <span class="breadcrumb">خانه / تسک‌ها</span>
</div>

<?php
// ── Section 1: Pending text-task answers ────────────────────────────────
if (!empty($pendingAnswers)):
?>
<div class="glass-card" style="margin-bottom:24px;border-color:rgba(251,191,36,0.25);">
    <div class="card-header">
        <span class="card-title" style="color:#fbbf24;">
            <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="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" x2="12" y1="9" y2="13"/><line x1="12" x2="12.01" y1="17" y2="17"/></svg>
            پاسخ‌های در انتظار بررسی
        </span>
        <span class="badge badge-claimed"><?= count($pendingAnswers) ?> مورد</span>
    </div>
    <div class="table-container">
        <table>
            <thead>
                <tr style="background:rgba(251,191,36,0.04);">
                    <th>کاربر</th><th>تسک</th><th>پیش‌نمایش پاسخ</th><th>زمان</th><th>عملیات</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($pendingAnswers as $row):
                    $preview = mb_substr((string)($row['answer_text'] ?? ''), 0, 40);
                    if (mb_strlen((string)($row['answer_text'] ?? '')) > 40) $preview .= '…';
                    $uname = $row['display_name'] ?? ('user ' . $row['user_id']);
                ?>
                <tr>
                    <td>
                        <div style="font-weight:600;color:#e6f0ff;"><?= e($uname) ?></div>
                        <div style="font-size:11px;color:#5a6b85;">
                            <a href="?page=user_detail&id=<?= (int)$row['user_id'] ?>" style="color:#5a6b85;text-decoration:none;"><?= (int)$row['user_id'] ?></a>
                        </div>
                    </td>
                    <td style="font-weight:600;color:#e6f0ff;"><?= e($row['title'] ?? '') ?></td>
                    <td style="max-width:280px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#9fb0c9;font-family:monospace;font-size:12px;"><?= e($preview) ?></td>
                    <td style="font-size:11px;color:#5a6b85;"><?= e($row['created_at'] ?? '') ?></td>
                    <td>
                        <a href="?page=task_detail&id=<?= (int)$row['id'] ?>" class="btn btn-primary btn-xs" 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"><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></svg>
                            بررسی
                        </a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<?php
// ── Section 2: Create task 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="createTaskForm">
        <?= csrf_field() ?>
        <input type="hidden" name="action" value="create_task">

        <div class="grid-2">
            <div class="form-group">
                <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="type" value="text" checked onchange="switchTaskType('text')">
                        <span style="display:inline-flex;align-items:center;gap:6px;">
                            <span class="badge" style="background:rgba(167,139,250,0.15);color:#a78bfa;">متنی</span>
                            پاسخ آزاد کاربر — نیاز به تأیید ادمین
                        </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="type" value="channel" onchange="switchTaskType('channel')">
                        <span style="display:inline-flex;align-items:center;gap:6px;">
                            <span class="badge" style="background:rgba(34,211,238,0.15);color:#22d3ee;">کانال</span>
                            عضویت در کانال — تأیید خودکار
                        </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="type" value="bot" onchange="switchTaskType('bot')">
                        <span style="display:inline-flex;align-items:center;gap:6px;">
                            <span class="badge" style="background:rgba(52,211,153,0.15);color:#34d399;">ربات</span>
                            استارت ربات قبلی — تأیید خودکار
                        </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="type" value="group_add" onchange="switchTaskType('group_add')">
                        <span style="display:inline-flex;align-items:center;gap:6px;">
                            <span class="badge" style="background:rgba(251,146,60,0.15);color:#fb923c;">اد گروه</span>
                            افزودن عضو به گروه هدف — تأیید خودکار
                        </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="type" value="group_msgs" onchange="switchTaskType('group_msgs')">
                        <span style="display:inline-flex;align-items:center;gap:6px;">
                            <span class="badge" style="background:rgba(251,146,60,0.15);color:#fb923c;">پیام گروه</span>
                            ارسال پیام در گروه هدف — تأیید خودکار
                        </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="type" value="race" onchange="switchTaskType('race')">
                        <span style="display:inline-flex;align-items:center;gap:6px;">
                            <span class="badge" style="background:rgba(248,113,113,0.15);color:#f87171;">مسابقه</span>
                            نفر اول/دوم/سوم شدن — تأیید خودکار
                        </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="type" value="referrals" onchange="switchTaskType('referrals')">
                        <span style="display:inline-flex;align-items:center;gap:6px;">
                            <span class="badge" style="background:rgba(34,211,238,0.15);color:#22d3ee;">دعوت</span>
                            دعوت N دوست به ربات — تأیید خودکار
                        </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="type" value="play_games" onchange="switchTaskType('play_games')">
                        <span style="display:inline-flex;align-items:center;gap:6px;">
                            <span class="badge" style="background:rgba(129,140,248,0.15);color:#a5b4fc;">بازی</span>
                            تمام کردن N بازی — تأیید خودکار
                        </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="type" value="win_games" onchange="switchTaskType('win_games')">
                        <span style="display:inline-flex;align-items:center;gap:6px;">
                            <span class="badge" style="background:rgba(129,140,248,0.15);color:#a5b4fc;">برد</span>
                            بردن N بازی — تأیید خودکار
                        </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="type" value="manual" onchange="switchTaskType('manual')">
                        <span style="display:inline-flex;align-items:center;gap:6px;">
                            <span class="badge" style="background:rgba(167,139,250,0.15);color:#a78bfa;">تاییدی</span>
                            انجام آزاد — کاربر دکمه تایید می‌زند، ادمین بررسی می‌کند
                        </span>
                    </label>
                </div>
            </div>

            <div class="form-group" id="channel_select_group" style="display:none;">
                <label>کانال / گروه هدف</label>
                <small style="color:var(--text-muted);display:block;margin-bottom:8px;">برای تسک کانالی، عضویت اجباری می‌شود؛ برای تسک‌های گروهی (اد/پیام/مسابقه) فقط به‌عنوان گروه هدف استفاده می‌شود و حالت کانال تغییر نمی‌کند.</small>
                <?php
                $allChannels = Database::getAllChannelsList();
                $channelModeDefault = empty($allChannels) ? 'new' : 'existing';
                ?>
                <!-- Sub-toggle: pick an existing channel vs add a new one inline -->
                <div style="display:flex;gap:12px;flex-wrap:wrap;margin-bottom:10px;">
                    <label style="display:flex;align-items:center;gap:6px;cursor:pointer;padding:8px 14px;border:1px solid var(--border);border-radius:8px;font-size:13px;">
                        <input type="radio" name="channel_mode" value="existing" <?= $channelModeDefault === 'existing' ? 'checked' : '' ?> onchange="switchChannelMode('existing')">
                        انتخاب کانال موجود
                    </label>
                    <label style="display:flex;align-items:center;gap:6px;cursor:pointer;padding:8px 14px;border:1px solid var(--border);border-radius:8px;font-size:13px;">
                        <input type="radio" name="channel_mode" value="new" <?= $channelModeDefault === 'new' ? 'checked' : '' ?> onchange="switchChannelMode('new')">
                        <span style="display:inline-flex;align-items:center;gap:6px;color:var(--accent-cyan);">
                            <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="M12 5v14"/></svg>
                            افزودن کانال جدید
                        </span>
                    </label>
                </div>
                <!-- Hidden flag so the POST handler knows which path was taken -->
                <input type="hidden" name="channel_new" id="channel_new_flag" value="<?= $channelModeDefault === 'new' ? '1' : '0' ?>">

                <div id="channel_existing_block" style="<?= $channelModeDefault === 'existing' ? '' : 'display:none;' ?>">
                    <?php if (empty($allChannels)): ?>
                        <div class="form-control" style="background:rgba(248,113,113,0.06);color:#f87171;font-style:italic;">هیچ کانالی موجود نیست — گزینهٔ «افزودن کانال جدید» را انتخاب کنید.</div>
                    <?php else: ?>
                    <select name="channel_id" id="channel_id_input" class="form-control">
                        <option value="">— انتخاب کانال —</option>
                        <?php foreach ($allChannels as $ch):
                            $name = $ch['display_name'] !== '' && $ch['display_name'] !== null ? $ch['display_name'] : $ch['channel_handle'];
                        ?>
                        <option value="<?= (int)$ch['id'] ?>"><?= e($name) ?> (<?= e($ch['channel_handle']) ?>)</option>
                        <?php endforeach; ?>
                    </select>
                    <?php endif; ?>
                </div>
            </div>

            <div class="form-group" id="bot_select_group" style="display:none;">
                <label>ربات هدف</label>
                <?php
                $allBots = Database::getAllBotVerifications();
                $botModeDefault = empty($allBots) ? 'new' : 'existing';
                ?>
                <div style="display:flex;gap:12px;flex-wrap:wrap;margin-bottom:10px;">
                    <label style="display:flex;align-items:center;gap:6px;cursor:pointer;padding:8px 14px;border:1px solid var(--border);border-radius:8px;font-size:13px;">
                        <input type="radio" name="bot_mode" value="existing" <?= $botModeDefault === 'existing' ? 'checked' : '' ?> onchange="switchBotMode('existing')">
                        انتخاب ربات موجود
                    </label>
                    <label style="display:flex;align-items:center;gap:6px;cursor:pointer;padding:8px 14px;border:1px solid var(--border);border-radius:8px;font-size:13px;">
                        <input type="radio" name="bot_mode" value="new" <?= $botModeDefault === 'new' ? 'checked' : '' ?> onchange="switchBotMode('new')">
                        <span style="display:inline-flex;align-items:center;gap:6px;color:#34d399;">
                            <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="M12 5v14"/></svg>
                            افزودن ربات جدید
                        </span>
                    </label>
                </div>
                <input type="hidden" name="bot_new" id="bot_new_flag" value="<?= $botModeDefault === 'new' ? '1' : '0' ?>">

                <div id="bot_existing_block" style="<?= $botModeDefault === 'existing' ? '' : 'display:none;' ?>">
                    <?php if (empty($allBots)): ?>
                        <div class="form-control" style="background:rgba(248,113,113,0.06);color:#f87171;font-style:italic;">هیچ رباتی موجود نیست — گزینهٔ «افزودن ربات جدید» را انتخاب کنید.</div>
                    <?php else: ?>
                    <select name="bot_verification_id" id="bot_verification_id_input" class="form-control">
                        <option value="">— انتخاب ربات —</option>
                        <?php foreach ($allBots as $bv): ?>
                        <option value="<?= (int)$bv['id'] ?>"><?= e($bv['bot_username']) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- ═══ Inline "add new channel" block (full-width, shown when channel_mode=new) ═══ -->
        <div id="channel_new_block" style="display:none;margin-bottom:20px;padding:16px 18px;border:1px dashed rgba(34,211,238,0.3);border-radius:12px;background:rgba(34,211,238,0.03);">
            <div style="display:flex;align-items:center;gap:8px;margin-bottom:14px;font-weight:600;color:var(--accent-cyan);">
                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="M12 5v14"/></svg>
                افزودن کانال جدید (همراه با تسک)
            </div>
            <small style="color:var(--text-muted);display:block;margin-bottom:12px;">کانال به‌صورت اجباری ساخته می‌شود و سپس تسکِ پاداش‌دار روی آن فعال می‌گردد. پاداش زیر را نیز پر کنید.</small>

            <div class="grid-2" style="gap:12px;">
                <div class="form-group" style="margin:0;">
                    <label>نام نمایشی</label>
                    <input type="text" name="new_channel_display_name" id="new_channel_display_name" class="form-control" placeholder="مثال: کانال رسمی نترکس" maxlength="100">
                </div>
                <div class="form-group" style="margin:0;">
                    <label>شناسه عددی چت (Numeric ID)</label>
                    <input type="text" name="new_channel_numeric_id" id="new_channel_numeric_id" class="form-control" placeholder="مثال: -1001676284133" maxlength="64">
                </div>
            </div>

            <div class="form-group" style="margin-top:12px;">
                <label>نوع (عمومی / خصوصی)</label>
                <div style="display:flex;gap:12px;flex-wrap:wrap;">
                    <label style="display:flex;align-items:center;gap:6px;cursor:pointer;padding:8px 14px;border:1px solid var(--border);border-radius:8px;font-size:13px;">
                        <input type="radio" name="new_channel_type" value="public" checked onchange="switchNewChannelType('public')">
                        عمومی (Public) — دارای @username
                    </label>
                    <label style="display:flex;align-items:center;gap:6px;cursor:pointer;padding:8px 14px;border:1px solid var(--border);border-radius:8px;font-size:13px;">
                        <input type="radio" name="new_channel_type" value="private" onchange="switchNewChannelType('private')">
                        خصوصی (Private) — با لینک دعوت
                    </label>
                </div>
            </div>

            <div class="form-group" id="new_channel_public_fields" style="margin-top:12px;">
                <label>یوزرنیم عمومی</label>
                <input type="text" name="new_channel_handle" id="new_channel_handle" class="form-control" placeholder="@channel_or_group_username">
            </div>

            <div class="form-group" id="new_channel_private_fields" style="display:none;margin-top:12px;">
                <label>لینک عضویت (دعوت)</label>
                <input type="text" name="new_channel_join_link" id="new_channel_join_link" class="form-control" placeholder="https://t.me/+AbCdEfGhIjKl">
            </div>
        </div>

        <!-- ═══ Inline "add new bot" block (full-width, shown when bot_mode=new) ═══ -->
        <div id="bot_new_block" style="display:none;margin-bottom:20px;padding:16px 18px;border:1px dashed rgba(52,211,153,0.3);border-radius:12px;background:rgba(52,211,153,0.03);">
            <div style="display:flex;align-items:center;gap:8px;margin-bottom:14px;font-weight:600;color:#34d399;">
                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="M12 5v14"/></svg>
                افزودن ربات جدید (همراه با تسک)
            </div>
            <small style="color:var(--text-muted);display:block;margin-bottom:12px;">ربات به‌صورت اجباری ساخته می‌شود و سپس تسکِ پاداش‌دار روی آن فعال می‌گردد. پاداش زیر را نیز پر کنید.</small>

            <div class="form-group" style="margin:0;">
                <label>یوزرنیم ربات</label>
                <input type="text" name="new_bot_username" id="new_bot_username" class="form-control" placeholder="@OldNetrexBot" maxlength="33">
                <small style="color:var(--text-muted);display:block;margin-top:4px;">یوزرنیم تلگرام ربات قبلی (با @ شروع شود).</small>
            </div>
            <div class="form-group" style="margin-top:12px;">
                <label>آدرس API (check_started.php)</label>
                <input type="text" name="new_bot_api_url" id="new_bot_api_url" class="form-control" placeholder="https://your-old-site.com/admin/api/check_started.php" maxlength="500">
            </div>
            <div class="form-group" style="margin-top:12px;">
                <label>API Key</label>
                <input type="text" name="new_bot_api_key" id="new_bot_api_key" class="form-control" placeholder="ntrx_..." maxlength="200" autocomplete="off">
                <small style="color:var(--text-muted);display:block;margin-top:4px;">کلیدی با مجوز <code>users:read</code> از پنل ادمین ربات قبلی.</small>
            </div>
        </div>

        <!-- ═══ T46-l: per-type parameters ═══ -->
        <div class="form-group" id="params_count_block" style="display:none;margin-bottom:14px;">
            <label id="params_count_label">تعداد</label>
            <input type="number" name="task_count" id="task_count_input" class="form-control" min="1" max="100000" step="1" value="5">
            <small style="color:var(--text-muted);display:block;margin-top:4px;" id="params_count_hint"></small>
        </div>

        <div id="params_race_block" style="display:none;margin-bottom:14px;padding:16px 18px;border:1px dashed rgba(248,113,113,0.3);border-radius:12px;background:rgba(248,113,113,0.03);">
            <div style="display:flex;align-items:center;gap:8px;margin-bottom:14px;font-weight:600;color:#f87171;">
                پارامترهای مسابقه
            </div>
            <div class="form-group">
                <label>مسابقه روی چه اقدامی؟</label>
                <div style="display:flex;gap:12px;flex-wrap:wrap;">
                    <label style="display:flex;align-items:center;gap:6px;cursor:pointer;padding:8px 14px;border:1px solid var(--border);border-radius:8px;font-size:13px;">
                        <input type="radio" name="race_action" value="message" checked>
                        ارسال پیام در گروه (شرط: ۱ پیام)
                    </label>
                    <label style="display:flex;align-items:center;gap:6px;cursor:pointer;padding:8px 14px;border:1px solid var(--border);border-radius:8px;font-size:13px;">
                        <input type="radio" name="race_action" value="add">
                        اد کردن عضو در گروه (شرط: N عضو)
                    </label>
                </div>
            </div>
            <div class="grid-3" style="gap:12px;">
                <div class="form-group" style="margin:0;">
                    <label>شرط اد (برای مسابقه اد)</label>
                    <input type="number" name="race_goal" id="race_goal_input" class="form-control" min="1" max="100000" step="1" value="1">
                    <small style="color:var(--text-muted);display:block;margin-top:4px;">برای مسابقه پیام همان ۱ بماند.</small>
                </div>
                <div class="form-group" style="margin:0;">
                    <label>مهلت (ساعت)</label>
                    <input type="number" name="race_hours" class="form-control" min="1" max="8760" step="1" value="24">
                </div>
                <div class="form-group" style="margin:0;">
                    <label>جایگاه این تسک</label>
                    <select name="race_place" class="form-control">
                        <option value="1">نفر اول</option>
                        <option value="2">نفر دوم</option>
                        <option value="3">نفر سوم</option>
                        <option value="4">نفر چهارم</option>
                        <option value="5">نفر پنجم</option>
                        <option value="6">نفر ششم</option>
                        <option value="7">نفر هفتم</option>
                        <option value="8">نفر هشتم</option>
                        <option value="9">نفر نهم</option>
                        <option value="10">نفر دهم</option>
                    </select>
                </div>
            </div>
            <div class="form-group" style="margin-top:12px;">
                <label>شناسه مسابقه (اختیاری)</label>
                <input type="text" name="race_key" class="form-control" placeholder="مثال: race1" maxlength="32">
                <small style="color:var(--text-muted);display:block;margin-top:4px;">برای هر جایگاه یک تسک بسازید و همه را با «همین شناسه» یکی کنید — ترتیب نفرات بین همه جایگاه‌های یک شناسه مشترک است. خالی = مسابقه تک‌جایگاهی مستقل.</small>
            </div>
        </div>

        <div class="grid-2">
            <div class="form-group">
                <label>عنوان تسک</label>
                <input type="text" name="title" class="form-control" placeholder="مثال: عضویت در کانال رسمی" required maxlength="255">
            </div>
            <div class="form-group">
                <label>توضیحات (اختیاری)</label>
                <input type="text" name="description" class="form-control" placeholder="توضیح کوتاه برای کاربر" maxlength="1000">
            </div>
        </div>

        <div class="form-group">
            <label>پاداش (هر مقدار ۰ یعنی بدون پاداش آن ارز)</label>
            <div class="grid-3" style="gap:12px;">
                <div class="form-group" style="margin:0;">
                    <label>پاداش <?= e($currencyName('game_token')) ?></label>
                    <input type="number" name="reward_game_tokens" class="form-control" min="0" step="1" value="0" required>
                </div>
                <div class="form-group" style="margin:0;">
                    <label>پاداش <?= e($currencyName('toman')) ?></label>
                    <input type="number" name="reward_toman" class="form-control" min="0" step="1" value="0" required>
                </div>
                <div class="form-group" style="margin:0;">
                    <label>پاداش <?= e($currencyName('ntx')) ?></label>
                    <input type="number" name="reward_ntx" class="form-control" min="0" step="1" value="0" required>
                </div>
            </div>
            <small style="color:var(--text-muted);display:block;margin-top:6px;">می‌توانید هر ترکیبی را پر کنید — مثلاً فقط توکن بازی یا همزمان تومان + NTX. همه ۰ یعنی «بدون پاداش».</small>
        </div>

        <button type="submit" class="btn btn-primary" style="padding:12px 28px;">
            <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-left:6px;"><path d="M5 12h14"/><path d="M12 5v14"/></svg>
            ایجاد تسک
        </button>
    </form>
</div>

<script>
// T46-l: type groups — the channel/group picker is shared by the
// channel task AND the three group-based configurable tasks.
var TASK_CHANNEL_TYPES = ['channel', 'group_add', 'group_msgs', 'race'];
var TASK_COUNT_TYPES = ['group_add', 'group_msgs', 'referrals', 'play_games', 'win_games', 'race'];
var TASK_COUNT_LABELS = {
    group_add:  'تعداد عضو مورد نیاز',
    group_msgs: 'تعداد پیام مورد نیاز',
    referrals:  'تعداد دعوت مورد نیاز',
    play_games: 'تعداد بازی مورد نیاز',
    win_games:  'تعداد برد مورد نیاز',
    race:       'شرط هر جایگاه (تعداد)'
};
var TASK_COUNT_HINTS = {
    group_add:  'هر عضو جدید گروه فقط یک بار شمرده می‌شود.',
    group_msgs: 'هر پیام متنی جدید فقط یک بار شمرده می‌شود.',
    referrals:  'دعوت‌های قبلی کاربر هم محاسبه می‌شود.',
    play_games: 'بازی‌های تمام‌شده از تاریخچه شمرده می‌شود.',
    win_games:  'بردها از تاریخچه برندگان شمرده می‌شود.',
    race:       'برای مسابقه پیام همان ۱ بماند؛ برای مسابقه اد تعداد اد لازم را بگذارید.'
};

function switchTaskType(type) {
    var channelGroup = document.getElementById('channel_select_group');
    var channelNewBlock = document.getElementById('channel_new_block');
    var channelInput = document.getElementById('channel_id_input');
    var botGroup = document.getElementById('bot_select_group');
    var botNewBlock = document.getElementById('bot_new_block');
    var botInput = document.getElementById('bot_verification_id_input');
    var countBlock = document.getElementById('params_count_block');
    var raceBlock = document.getElementById('params_race_block');

    // Hide all first
    if (channelGroup) channelGroup.style.display = 'none';
    if (channelNewBlock) channelNewBlock.style.display = 'none';
    if (channelInput) channelInput.required = false;
    if (botGroup) botGroup.style.display = 'none';
    if (botNewBlock) botNewBlock.style.display = 'none';
    if (botInput) botInput.required = false;
    if (countBlock) countBlock.style.display = 'none';
    if (raceBlock) raceBlock.style.display = 'none';

    // Show the relevant one + re-sync the inner existing/new toggle.
    if (TASK_CHANNEL_TYPES.indexOf(type) !== -1) {
        if (channelGroup) channelGroup.style.display = '';
        var mode = (function() {
            var el = document.querySelector('input[name="channel_mode"]:checked');
            return el ? el.value : 'existing';
        })();
        switchChannelMode(mode);
    } else if (type === 'bot') {
        if (botGroup) botGroup.style.display = '';
        var modeB = (function() {
            var el = document.querySelector('input[name="bot_mode"]:checked');
            return el ? el.value : 'existing';
        })();
        switchBotMode(modeB);
    }

    // T46-l: per-type parameter blocks.
    if (TASK_COUNT_TYPES.indexOf(type) !== -1 && countBlock) {
        countBlock.style.display = '';
        var lbl = document.getElementById('params_count_label');
        var hint = document.getElementById('params_count_hint');
        if (lbl) lbl.textContent = TASK_COUNT_LABELS[type] || 'تعداد';
        if (hint) hint.textContent = TASK_COUNT_HINTS[type] || '';
    }
    if (type === 'race' && raceBlock) {
        raceBlock.style.display = '';
    }
}

// Toggle between "pick an existing channel" and "add a new channel inline".
function switchChannelMode(mode) {
    var existing = document.getElementById('channel_existing_block');
    var newBlock = document.getElementById('channel_new_block');
    var flag     = document.getElementById('channel_new_flag');
    var channelInput = document.getElementById('channel_id_input');

    if (existing) existing.style.display = (mode === 'existing') ? '' : 'none';
    if (newBlock) newBlock.style.display = (mode === 'new') ? '' : 'none';
    if (flag) flag.value = (mode === 'new') ? '1' : '0';
    // The existing-channel dropdown is only required when in "existing" mode.
    if (channelInput) channelInput.required = (mode === 'existing');
}

// Toggle between "pick an existing bot" and "add a new bot inline".
function switchBotMode(mode) {
    var existing = document.getElementById('bot_existing_block');
    var newBlock = document.getElementById('bot_new_block');
    var flag     = document.getElementById('bot_new_flag');
    var botInput = document.getElementById('bot_verification_id_input');

    if (existing) existing.style.display = (mode === 'existing') ? '' : 'none';
    if (newBlock) newBlock.style.display = (mode === 'new') ? '' : 'none';
    if (flag) flag.value = (mode === 'new') ? '1' : '0';
    if (botInput) botInput.required = (mode === 'existing');
}

// Toggle public/private fields inside the inline "add new channel" block.
function switchNewChannelType(type) {
    var pub = document.getElementById('new_channel_public_fields');
    var prv = document.getElementById('new_channel_private_fields');
    if (type === 'private') {
        if (pub) pub.style.display = 'none';
        if (prv) prv.style.display = '';
    } else {
        if (pub) pub.style.display = '';
        if (prv) prv.style.display = 'none';
    }
}
</script>

<?php
// ── Section 3: All tasks table ──────────────────────────────────────────
?>
<div class="glass-card">
    <div class="card-header">
        <span class="card-title">
            <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="M3 3h18v18H3z"/><path d="M3 9h18"/><path d="M3 15h18"/><path d="M9 3v18"/><path d="M15 3v18"/></svg>
            همهٔ تسک‌ها (<span style="color:#22d3ee;"><?= count($tasks) ?></span>)
        </span>
    </div>

    <?php if (empty($tasks)): ?>
        <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="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></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><th>عملیات</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($tasks as $t):
                    $type = $t['type'] ?? 'text';
                    // T46-l: badge colors for all ten task types.
                    $badgeMap = [
                        'channel'    => ['rgba(34,211,238,0.15)', '#22d3ee', 'کانال'],
                        'bot'        => ['rgba(52,211,153,0.15)', '#34d399', 'ربات'],
                        'text'       => ['rgba(167,139,250,0.15)', '#a78bfa', 'متنی'],
                        'group_add'  => ['rgba(251,146,60,0.15)', '#fb923c', 'اد گروه'],
                        'group_msgs' => ['rgba(251,146,60,0.15)', '#fb923c', 'پیام گروه'],
                        'race'       => ['rgba(248,113,113,0.15)', '#f87171', 'مسابقه'],
                        'referrals'  => ['rgba(34,211,238,0.15)', '#22d3ee', 'دعوت'],
                        'play_games' => ['rgba(129,140,248,0.15)', '#a5b4fc', 'بازی'],
                        'win_games'  => ['rgba(129,140,248,0.15)', '#a5b4fc', 'برد'],
                        'manual'     => ['rgba(167,139,250,0.15)', '#a78bfa', 'تاییدی'],
                    ];
                    $bm = $badgeMap[$type] ?? $badgeMap['text'];
                    $typeBadge = '<span class="badge" style="background:' . $bm[0] . ';color:' . $bm[1] . ';">' . e($bm[2]) . '</span>';
                    $taskSummaryText = TaskSystem::taskSummary($t);
                    $isActive    = (bool)($t['is_active'] ?? 1);
                    $rGameTokens = (int)($t['reward_game_tokens'] ?? 0);
                    $rToman      = (int)($t['reward_toman']      ?? 0);
                    $rNtx        = (int)($t['reward_ntx']        ?? 0);
                    $reward      = $formatCombinedReward($rGameTokens, $rToman, $rNtx);
                    $taskJson = htmlspecialchars(json_encode([
                        'id'                 => (int)$t['id'],
                        'type'               => $type,
                        'title'              => (string)($t['title'] ?? ''),
                        'description'        => (string)($t['description'] ?? ''),
                        'reward_game_tokens' => $rGameTokens,
                        'reward_toman'       => $rToman,
                        'reward_ntx'         => $rNtx,
                        'is_active'          => $isActive,
                        'task_config'        => TaskSystem::taskConfig(isset($t['task_config']) ? (string)$t['task_config'] : null, (string)$type),
                    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), ENT_QUOTES);
                ?>
                <tr>
                    <td style="font-weight:700;color:#22d3ee;">#<?= (int)$t['id'] ?></td>
                    <td><?= $typeBadge ?></td>
                    <td style="font-weight:600;color:#e6f0ff;">
                        <?= e($t['title'] ?? '') ?>
                        <?php if ($taskSummaryText !== ''): ?>
                            <div style="font-size:11px;color:#8aa0bf;"><?= e($taskSummaryText) ?></div>
                        <?php endif; ?>
                        <?php if (!empty($t['target'])): ?>
                            <div style="font-size:11px;color:#5a6b85;"><?= e($t['target']) ?></div>
                        <?php endif; ?>
                    </td>
                    <td style="font-weight:600;color:#2dd4bf;"><?= $reward ?></td>
                    <td>
                        <span class="badge <?= $isActive ? 'badge-active' : 'badge-inactive' ?>">
                            <?= $isActive ? 'فعال' : 'غیرفعال' ?>
                        </span>
                    </td>
                    <td style="font-size:11px;color:#5a6b85;"><?= e($t['created_at'] ?? '') ?></td>
                    <td>
                        <div style="display:flex;gap:6px;">
                            <button type="button"
                                class="btn btn-glass btn-xs"
                                data-task='<?= $taskJson ?>'
                                onclick="openEditTaskModal(this)"
                                style="display:inline-flex;align-items:center;gap:4px;">
                                <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('حذف تسک #<?= (int)$t['id'] ?>؟ تمام پاسخ‌های ثبت‌شده نیز حذف می‌شوند.')">
                                <?= csrf_field() ?>
                                <input type="hidden" name="action" value="delete_task">
                                <input type="hidden" name="task_id" value="<?= (int)$t['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"/></svg>
                                </button>
                            </form>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>

<!-- ═══ Edit task modal ═══ -->
<div id="editTaskModal" style="display:none;position:fixed;inset:0;z-index:100;align-items:center;justify-content:center;padding:16px;">
    <div onclick="closeEditTaskModal()" 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:540px;max-height:calc(100vh - 32px);overflow-y:auto;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;"><!-- T46-r: max-height+scroll added — edit modal overflowed short phones (save/checkbox clipped) -->
        <button onclick="closeEditTaskModal()" 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="editTaskId" style="color:#22d3ee;"></span>
        </h3>

        <form method="POST" id="editTaskForm">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="update_task">
            <input type="hidden" name="task_id" id="edit_task_id" value="">

            <div class="form-group">
                <label>عنوان</label>
                <input type="text" name="title" id="edit_title" class="form-control" required maxlength="255">
            </div>

            <div class="form-group">
                <label>توضیحات</label>
                <textarea name="description" id="edit_description" class="form-control" rows="3" style="resize:vertical;"></textarea>
            </div>

            <!-- T46-l: per-type params in the edit modal -->
            <div class="form-group" id="edit_params_count_block" style="display:none;">
                <label id="edit_count_label">تعداد</label>
                <input type="number" name="task_count" id="edit_task_count" class="form-control" min="1" max="100000" step="1" value="5">
            </div>

            <div id="edit_race_block" style="display:none;margin-bottom:14px;padding:14px 16px;border:1px dashed rgba(248,113,113,0.3);border-radius:12px;background:rgba(248,113,113,0.03);">
                <div class="form-group">
                    <label>اقدام مسابقه</label>
                    <div style="display:flex;gap:12px;flex-wrap:wrap;">
                        <label style="display:flex;align-items:center;gap:6px;cursor:pointer;font-size:13px;">
                            <input type="radio" name="edit_race_action" value="message">
                            پیام در گروه
                        </label>
                        <label style="display:flex;align-items:center;gap:6px;cursor:pointer;font-size:13px;">
                            <input type="radio" name="edit_race_action" value="add">
                            اد عضو
                        </label>
                    </div>
                </div>
                <div class="grid-3" style="gap:12px;">
                    <div class="form-group" style="margin:0;">
                        <label>شرط اد</label>
                        <input type="number" name="race_goal" id="edit_race_goal" class="form-control" min="1" max="100000" step="1" value="1">
                    </div>
                    <div class="form-group" style="margin:0;">
                        <label>مهلت (ساعت)</label>
                        <input type="number" name="race_hours" id="edit_race_hours" class="form-control" min="1" max="8760" step="1" value="24">
                    </div>
                    <div class="form-group" style="margin:0;">
                        <label>جایگاه</label>
                        <select name="race_place" id="edit_race_place" class="form-control">
                            <?php for ($i = 1; $i <= 10; $i++): ?>
                            <option value="<?= $i ?>">نفر <?= ['اول','دوم','سوم','چهارم','پنجم','ششم','هفتم','هشتم','نهم','دهم'][$i-1] ?></option>
                            <?php endfor; ?>
                        </select>
                    </div>
                </div>
                <div class="form-group" style="margin-top:12px;">
                    <label>شناسه مسابقه</label>
                    <input type="text" name="race_key" id="edit_race_key" class="form-control" maxlength="32">
                </div>
            </div>

            <div class="form-group">
                <label>پاداش (هر مقدار ۰ یعنی بدون پاداش آن ارز)</label>
                <div class="grid-3" style="gap:12px;">
                    <div class="form-group" style="margin:0;">
                        <label>پاداش <?= e($currencyName('game_token')) ?></label>
                        <input type="number" name="reward_game_tokens" id="edit_reward_game_tokens" class="form-control" min="0" step="1" value="0" required>
                    </div>
                    <div class="form-group" style="margin:0;">
                        <label>پاداش <?= e($currencyName('toman')) ?></label>
                        <input type="number" name="reward_toman" id="edit_reward_toman" class="form-control" min="0" step="1" value="0" required>
                    </div>
                    <div class="form-group" style="margin:0;">
                        <label>پاداش <?= e($currencyName('ntx')) ?></label>
                        <input type="number" name="reward_ntx" id="edit_reward_ntx" class="form-control" min="0" step="1" value="0" required>
                    </div>
                </div>
            </div>

            <div class="form-group">
                <label class="form-check" style="display:flex;align-items:center;gap:10px;cursor:pointer;">
                    <input type="checkbox" name="is_active" id="edit_is_active" value="1" style="width:18px;height:18px;accent-color:var(--accent-cyan);">
                    <span>تسک فعال باشد</span>
                </label>
            </div>

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

<script>
var EDIT_COUNT_TYPES = ['group_add', 'group_msgs', 'referrals', 'play_games', 'win_games', 'race'];
var EDIT_COUNT_LABELS = {
    group_add: 'تعداد عضو مورد نیاز', group_msgs: 'تعداد پیام مورد نیاز',
    referrals: 'تعداد دعوت مورد نیاز', play_games: 'تعداد بازی مورد نیاز',
    win_games: 'تعداد برد مورد نیاز', race: 'شرط هر جایگاه (تعداد)'
};
function openEditTaskModal(btn) {
    var data = JSON.parse(btn.getAttribute('data-task'));
    document.getElementById('edit_task_id').value            = data.id;
    document.getElementById('edit_title').value              = data.title;
    document.getElementById('edit_description').value        = data.description || '';
    document.getElementById('edit_reward_game_tokens').value = data.reward_game_tokens || 0;
    document.getElementById('edit_reward_toman').value       = data.reward_toman || 0;
    document.getElementById('edit_reward_ntx').value         = data.reward_ntx || 0;
    document.getElementById('edit_is_active').checked        = !!data.is_active;
    document.getElementById('editTaskId').textContent        = '#' + data.id;

    // T46-l: per-type param blocks.
    var cfg = data.task_config || {};
    var type = data.type || 'text';
    var countBlock = document.getElementById('edit_params_count_block');
    var raceBlock = document.getElementById('edit_race_block');
    countBlock.style.display = 'none';
    raceBlock.style.display = 'none';
    if (EDIT_COUNT_TYPES.indexOf(type) !== -1) {
        countBlock.style.display = '';
        document.getElementById('edit_count_label').textContent = EDIT_COUNT_LABELS[type] || 'تعداد';
        document.getElementById('edit_task_count').value = cfg.count || 1;
    }
    if (type === 'race') {
        raceBlock.style.display = '';
        var act = (cfg.action === 'add') ? 'add' : 'message';
        var msgRadio = document.querySelector('input[name="edit_race_action"][value="message"]');
        var addRadio = document.querySelector('input[name="edit_race_action"][value="add"]');
        if (msgRadio) msgRadio.checked = (act === 'message');
        if (addRadio) addRadio.checked = (act === 'add');
        document.getElementById('edit_race_goal').value  = cfg.count || 1;
        document.getElementById('edit_race_hours').value = cfg.hours || 24;
        document.getElementById('edit_race_place').value = String(cfg.place || 1);
        document.getElementById('edit_race_key').value   = cfg.race_key || '';
    }

    var modal = document.getElementById('editTaskModal');
    modal.style.display = 'flex';
}
function closeEditTaskModal() {
    document.getElementById('editTaskModal').style.display = 'none';
}
</script>

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