<?php
/**
 * بررسی عضویت اجباری کاربر در کانال‌ها
 */

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

/**
 * لیست کانال‌هایی که کاربر عضوشون نیست رو برمی‌گردونه
 */
function get_not_joined_channels($user_id) {
    $not_joined = [];
    foreach (FORCE_JOIN_CHANNELS as $channel) {
        $res = tg_get_chat_member($channel['username'], $user_id);
        if (!$res || !isset($res['ok']) || $res['ok'] !== true) {
            // اگه ربات ادمین کانال نباشه یا خطایی بخوره، برای امنیت جزو عضو نشده‌ها حساب میشه
            $not_joined[] = $channel;
            continue;
        }
        $status = $res['result']['status'] ?? 'left';
        if (in_array($status, ['left', 'kicked'], true)) {
            $not_joined[] = $channel;
        }
    }
    return $not_joined;
}

function is_user_joined_all($user_id) {
    if (empty(FORCE_JOIN_CHANNELS)) {
        return true;
    }
    return count(get_not_joined_channels($user_id)) === 0;
}

function build_join_keyboard($not_joined_channels, $callback_data = 'check_join') {
    $rows = [];
    foreach ($not_joined_channels as $ch) {
        $rows[] = [[ 'text' => '📢 ' . $ch['title'], 'url' => $ch['url'] ]];
    }
    $rows[] = [[ 'text' => '✅ عضو شدم', 'callback_data' => $callback_data ]];
    return ['inline_keyboard' => $rows];
}

function send_join_prompt($chat_id, $not_joined_channels, $pending_code = null) {
    $list = '';
    foreach ($not_joined_channels as $ch) {
        $list .= '• ' . $ch['title'] . "\n";
    }
    $text = sprintf(TEXT_NOT_JOINED, rtrim($list, "\n"));
    $callback_data = $pending_code ? ('check_join:' . $pending_code) : 'check_join';
    $keyboard = build_join_keyboard($not_joined_channels, $callback_data);
    tg_send_message($chat_id, $text, $keyboard);
}
