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

namespace GemAcc;

use PDO;

class ForceJoin
{
    private PDO $pdo;
    
    public function __construct(PDO $pdo)
    {
        $this->pdo = $pdo;
    }
    
    /**
     * بررسی فعال بودن سیستم Force Join
     */
    public function isEnabled(): bool
    {
        $stmt = $this->pdo->query("SELECT value FROM settings WHERE key_name = 'force_join_enabled'");
        $val = $stmt->fetchColumn();
        return $val === '1' || $val === 'true';
    }
    
    /**
     * فعال/غیرفعال کردن سیستم
     */
    public function setEnabled(bool $enabled): bool
    {
        $stmt = $this->pdo->prepare("
            INSERT INTO settings (key_name, value, updated_at) 
            VALUES ('force_join_enabled', :val, NOW()) 
            ON DUPLICATE KEY UPDATE value = VALUES(value), updated_at = NOW()
        ");
        return $stmt->execute([':val' => $enabled ? '1' : '0']);
    }
    
    /**
     * افزودن کانال جدید
     */
    public function addChannel(string $username, ?string $title = null, ?string $inviteLink = null): int
    {
        // پاک‌سازی username - اطمینان از فرمت @username
        $username = ltrim(trim($username), '@');
        $username = '@' . $username;
        
        $stmt = $this->pdo->prepare("
            INSERT INTO forced_channels (channel_username, channel_title, invite_link, is_active)
            VALUES (:username, :title, :invite, 1)
            ON DUPLICATE KEY UPDATE 
                channel_title = COALESCE(VALUES(channel_title), channel_title),
                invite_link = COALESCE(VALUES(invite_link), invite_link),
                is_active = 1
        ");
        
        $stmt->execute([
            ':username' => $username,
            ':title'    => $title,
            ':invite'   => $inviteLink,
        ]);
        
        return (int)$this->pdo->lastInsertId();
    }
    
    /**
     * گرفتن کانال با آیدی
     */
    public function getById(int $id): ?array
    {
        $stmt = $this->pdo->prepare("SELECT * FROM forced_channels WHERE id = ?");
        $stmt->execute([$id]);
        return $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
    }
    
    /**
     * حذف کانال
     */
    public function removeChannel(int $id): bool
    {
        $stmt = $this->pdo->prepare("DELETE FROM forced_channels WHERE id = ?");
        return $stmt->execute([$id]);
    }
    
    /**
     * فعال/غیرفعال کردن کانال
     */
    public function toggleChannel(int $id, bool $active): bool
    {
        $stmt = $this->pdo->prepare("UPDATE forced_channels SET is_active = ? WHERE id = ?");
        return $stmt->execute([$active ? 1 : 0, $id]);
    }
    
    /**
     * لیست همه کانال‌ها
     */
    public function getAllChannels(): array
    {
        $stmt = $this->pdo->query("SELECT * FROM forced_channels ORDER BY id ASC");
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    
    /**
     * لیست کانال‌های فعال
     */
    public function getActiveChannels(): array
    {
        $stmt = $this->pdo->query("SELECT * FROM forced_channels WHERE is_active = 1 ORDER BY id ASC");
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    
    /**
     * بررسی عضویت کاربر در همه کانال‌های فعال
     * @param int $userId آیدی کاربر تلگرام
     * @param callable $checkMembershipFn تابع چک عضویت
     * @return array ['joined' => bool, 'missing_channels' => array]
     */
    public function checkUserMembership(int $userId, callable $checkMembershipFn): array
    {
        if (!$this->isEnabled()) {
            return ['joined' => true, 'missing_channels' => []];
        }
        
        $channels = $this->getActiveChannels();
        if (empty($channels)) {
            return ['joined' => true, 'missing_channels' => []];
        }
        
        $missingChannels = [];
        
        foreach ($channels as $channel) {
            $isMember = $checkMembershipFn($channel['channel_username'], $userId);
            if (!$isMember) {
                $missingChannels[] = $channel;
            }
        }
        
        return [
            'joined'           => empty($missingChannels),
            'missing_channels' => $missingChannels,
        ];
    }
    
    /**
     * ساخت پیام و کیبورد عضویت
     */
    public function buildJoinMessage(array $missingChannels): array
    {
        $text = "⚠️ **برای استفاده از ربات ابتدا در کانال‌های زیر عضو شوید:**\n\n";
        
        $buttons = [];
        
        foreach ($missingChannels as $ch) {
            $title = $ch['channel_title'] ?: $ch['channel_username'];
            $link = $ch['invite_link'] ?: "https://t.me/" . ltrim($ch['channel_username'], '@');
            
            $text .= "📢 " . $title . "\n";
            $buttons[] = [['text' => '📢 ' . $title, 'url' => $link]];
        }
        
        $text .= "\n✅ پس از عضویت، دکمه بررسی عضویت را بزنید.";
        
        $buttons[] = [['text' => '✅ بررسی عضویت', 'callback_data' => 'CHECK_MEMBERSHIP']];
        
        return [
            'text'     => $text,
            'keyboard' => ['inline_keyboard' => $buttons],
        ];
    }
}

