<?php
/**
 * Force join channels check API
 */
require_once 'config.php';

$userId = $_GET['user_id'] ?? null;

if (!$userId) {
    echo json_encode(['ok' => false, 'error' => 'user_id required'], JSON_UNESCAPED_UNICODE);
    exit;
}

$userId = (int)$userId;

// Check if force join is enabled
$forceEnabled = getSetting('force_join_enabled', '0') === '1';

if (!$forceEnabled) {
    echo json_encode([
        'ok'   => true,
        'data' => [
            'force_enabled' => false,
            'is_member'     => true,
            'channels'      => [],
        ],
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

// Get active channels
$stmt = $pdo->query("SELECT * FROM forced_channels WHERE is_active = 1 ORDER BY id ASC");
$channels = $stmt->fetchAll();

if (empty($channels)) {
    echo json_encode([
        'ok'   => true,
        'data' => [
            'force_enabled' => true,
            'is_member'     => true,
            'channels'      => [],
        ],
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

// Check membership for each channel
$allMember = true;
$channelsData = [];

foreach ($channels as $channel) {
    $isMember = checkChannelMembership($userId, $channel['channel_username']);
    
    $channelsData[] = [
        'id'          => $channel['id'],
        'username'    => $channel['channel_username'],
        'title'       => $channel['channel_title'] ?? $channel['channel_username'],
        'invite_link' => $channel['invite_link'] ?? ('https://t.me/' . ltrim($channel['channel_username'], '@')),
        'is_member'   => $isMember,
    ];
    
    if (!$isMember) {
        $allMember = false;
    }
}

echo json_encode([
    'ok'   => true,
    'data' => [
        'force_enabled' => true,
        'is_member'     => $allMember,
        'channels'      => $channelsData,
    ],
], JSON_UNESCAPED_UNICODE);

function checkChannelMembership(int $userId, string $channelUsername): bool
{
    $result = tg('getChatMember', [
        'chat_id' => '@' . ltrim($channelUsername, '@'),
        'user_id' => $userId,
    ]);
    
    if (!$result || !($result['ok'] ?? false)) {
        return false;
    }
    
    $status = $result['result']['status'] ?? '';
    return in_array($status, ['creator', 'administrator', 'member']);
}

