<?php
/**
 * Subscription Handler
 * Version: 2.0
 */

declare(strict_types=1);

class SubscriptionHandler {
    private Bot $bot;
    private Telegram $telegram;
    private Database $db;
    private SubscriptionManager $subManager;
    
    public function __construct(Bot $bot) {
        $this->bot = $bot;
        $this->telegram = $bot->getTelegram();
        $this->db = $bot->getDb();
        $this->subManager = SubscriptionManager::getInstance();
    }
    
    /**
     * Handle subscription commands
     */
    public function handle(): void {
        $text = $this->bot->getText();
        $command = $this->parseCommand($text);
        
        switch ($command) {
            case 'subscribe':
            case 'اشتراک':
                $this->showPlans();
                break;
                
            case 'mysubscription':
            case 'اشتراک_من':
                $this->showMySubscription();
                break;
                
            case 'payment':
            case 'پرداخت':
                $this->showPaymentInfo();
                break;
        }
    }
    
    /**
     * Handle callback queries
     */
    public function handleCallback(): void {
        $data = $this->bot->getCallbackData();
        
        if (preg_match('/^plan_(\d+)$/', $data, $matches)) {
            $this->showPlanDetails((int)$matches[1]);
        } elseif (preg_match('/^buy_(\d+)$/', $data, $matches)) {
            $this->startPaymentProcess((int)$matches[1]);
        } elseif ($data === 'my_subscription') {
            $this->showMySubscription();
        }
    }
    
    /**
     * Show available plans
     */
    private function showPlans(): void {
        $plans = $this->subManager->getAllPlans();
        
        if (empty($plans)) {
            $this->telegram->sendMessage(
                $this->bot->getChatId(),
                "⚠️ در حال حاضر پلنی موجود نیست!"
            );
            return;
        }
        
        $keyboard = [];
        foreach ($plans as $plan) {
            $keyboard[] = [
                ['text' => "💎 {$plan['name']} - {$plan['price']} تومان", 'callback_data' => "plan_{$plan['id']}"]
            ];
        }
        
        $keyboard[] = [['text' => '📊 اشتراک من', 'callback_data' => 'my_subscription']];
        
        $message = "💎 *پلن‌های اشتراک*\n\n" .
                   "لطفاً یکی از پلن‌های زیر را انتخاب کنید:";
        
        $this->telegram->sendMessage(
            $this->bot->getChatId(),
            $message,
            'Markdown',
            ['inline_keyboard' => $keyboard]
        );
    }
    
    /**
     * Show plan details
     */
    private function showPlanDetails(int $planId): void {
        $plan = $this->subManager->getPlan($planId);
        
        if (!$plan) {
            $this->telegram->answerCallbackQuery(
                $this->bot->getCallbackQuery()->id,
                "❌ پلن یافت نشد!",
                true
            );
            return;
        }
        
        $features = json_decode($plan['features'], true) ?? [];
        $featuresList = '';
        
        foreach ($features as $feature) {
            $featuresList .= "✅ {$feature}\n";
        }
        
        $message = "💎 *{$plan['name']}*\n\n" .
                   "⏱ مدت: {$plan['duration_days']} روز\n" .
                   "💰 قیمت: " . number_format($plan['price']) . " تومان\n\n" .
                   "*ویژگی‌ها:*\n{$featuresList}";
        
        $keyboard = [
            'inline_keyboard' => [
                [['text' => '💳 خرید این پلن', 'callback_data' => "buy_{$planId}"]],
                [['text' => '🔙 بازگشت', 'callback_data' => 'back_to_plans']]
            ]
        ];
        
        $this->telegram->editMessageText(
            $this->bot->getChatId(),
            $this->bot->getMessageId(),
            $message,
            'Markdown',
            $keyboard
        );
    }
    
    /**
     * Start payment process
     */
    private function startPaymentProcess(int $planId): void {
        $plan = $this->subManager->getPlan($planId);
        $paymentSettings = $this->subManager->getPaymentSettings();
        
        if (!$plan || !$paymentSettings) {
            $this->telegram->answerCallbackQuery(
                $this->bot->getCallbackQuery()->id,
                "❌ خطا در دریافت اطلاعات!",
                true
            );
            return;
        }
        
        // Format card number
        $cardNumber = chunk_split($paymentSettings['card_number'], 4, '-');
        $cardNumber = rtrim($cardNumber, '-');
        
        $message = "💳 *اطلاعات پرداخت*\n\n" .
                   "📦 پلن: {$plan['name']}\n" .
                   "💰 مبلغ: " . number_format($plan['price']) . " تومان\n\n" .
                   "🏦 *اطلاعات کارت:*\n" .
                   "شماره کارت: `{$cardNumber}`\n" .
                   "به نام: {$paymentSettings['card_holder']}\n";
        
        if ($paymentSettings['bank_name']) {
            $message .= "بانک: {$paymentSettings['bank_name']}\n";
        }
        
        $message .= "\n📝 *مراحل پرداخت:*\n" .
                    "1️⃣ مبلغ را به شماره کارت بالا واریز کنید\n" .
                    "2️⃣ عکس رسید واریزی را ارسال کنید\n" .
                    "3️⃣ منتظر تأیید ادمین بمانید\n\n" .
                    "⚠️ لطفاً عکس رسید را واضح و خوانا ارسال کنید.";
        
        // Save state
        $this->saveUserState($this->bot->getUserId(), 'waiting_receipt', $planId);
        
        $this->telegram->sendMessage(
            $this->bot->getChatId(),
            $message,
            'Markdown'
        );
    }
    
    /**
     * Handle receipt photo
     */
    public function handleReceiptPhoto(string $fileId): void {
        $state = $this->getUserState($this->bot->getUserId());
        
        if (!$state || $state['action'] !== 'waiting_receipt') {
            return;
        }
        
        $planId = (int)$state['data'];
        
        // Submit receipt
        $receiptId = $this->subManager->submitReceipt(
            $this->bot->getUserId(),
            $planId,
            $fileId
        );
        
        if ($receiptId) {
            $this->clearUserState($this->bot->getUserId());
            
            $message = "✅ *رسید شما با موفقیت ثبت شد!*\n\n" .
                       "🔢 شماره پیگیری: `{$receiptId}`\n\n" .
                       "⏳ رسید شما در حال بررسی است.\n" .
                       "پس از تأیید، اشتراک شما فعال خواهد شد.\n\n" .
                       "📞 در صورت سوال با پشتیبانی تماس بگیرید.";
            
            $this->telegram->sendMessage(
                $this->bot->getChatId(),
                $message
            );
            
            // Notify admins
            $this->notifyAdminsNewReceipt($receiptId);
        }
    }
    
    /**
     * Show user's subscription
     */
    private function showMySubscription(): void {
        $subscription = $this->subManager->getUserSubscription($this->bot->getUserId());
        
        if (!$subscription) {
            $message = "⚠️ شما اشتراک فعالی ندارید!\n\n" .
                       "برای خرید اشتراک از دستور /subscribe استفاده کنید.";
            
            $this->telegram->sendMessage(
                $this->bot->getChatId(),
                $message
            );
            return;
        }
        
        $endDate = date('Y/m/d H:i', strtotime($subscription['end_date']));
        $daysLeft = ceil((strtotime($subscription['end_date']) - time()) / 86400);
        
        $message = "✅ *اشتراک فعال*\n\n" .
                   "📦 پلن: {$subscription['name']}\n" .
                   "📅 تاریخ انقضا: {$endDate}\n" .
                   "⏳ روزهای باقیمانده: {$daysLeft} روز\n\n";
        
        $features = json_decode($subscription['features'], true) ?? [];
        if (!empty($features)) {
            $message .= "*ویژگی‌های فعال:*\n";
            foreach ($features as $feature) {
                $message .= "✅ {$feature}\n";
            }
        }
        
        $keyboard = [
            'inline_keyboard' => [
                [['text' => '🔄 تمدید اشتراک', 'callback_data' => 'back_to_plans']],
                [['text' => '📜 تاریخچه پرداخت', 'callback_data' => 'payment_history']]
            ]
        ];
        
        $this->telegram->sendMessage(
            $this->bot->getChatId(),
            $message,
            'Markdown',
            $keyboard
        );
    }
    
    /**
     * Show payment info
     */
    private function showPaymentInfo(): void {
        $paymentSettings = $this->subManager->getPaymentSettings();
        
        if (!$paymentSettings) {
            $this->telegram->sendMessage(
                $this->bot->getChatId(),
                "⚠️ اطلاعات پرداخت تنظیم نشده است!"
            );
            return;
        }
        
        $cardNumber = chunk_split($paymentSettings['card_number'], 4, '-');
        $cardNumber = rtrim($cardNumber, '-');
        
        $message = "💳 *اطلاعات پرداخت*\n\n" .
                   "شماره کارت: `{$cardNumber}`\n" .
                   "به نام: {$paymentSettings['card_holder']}\n";
        
        if ($paymentSettings['bank_name']) {
            $message .= "بانک: {$paymentSettings['bank_name']}\n";
        }
        
        $this->telegram->sendMessage(
            $this->bot->getChatId(),
            $message
        );
    }
    
    /**
     * Notify admins about new receipt
     */
    private function notifyAdminsNewReceipt(int $receiptId): void {
        $receipt = $this->subManager->getReceipt($receiptId);
        
        if (!$receipt) {
            return;
        }
        
        $message = "🔔 *رسید جدید*\n\n" .
                   "🔢 شماره: {$receiptId}\n" .
                   "👤 کاربر: {$receipt['user_id']}\n" .
                   "📦 پلن: {$receipt['plan_name']}\n" .
                   "💰 مبلغ: " . number_format($receipt['amount']) . " تومان\n\n" .
                   "برای بررسی از پنل ادمین استفاده کنید.";
        
        foreach (ADMIN_IDS as $adminId) {
            $this->telegram->sendMessage($adminId, $message);
        }
    }
    
    /**
     * Save user state
     */
    private function saveUserState(int $userId, string $action, $data): void {
        $cacheFile = CACHE_PATH . "/user_state_{$userId}.json";
        file_put_contents($cacheFile, json_encode([
            'action' => $action,
            'data' => $data,
            'time' => time()
        ]));
    }
    
    /**
     * Get user state
     */
    private function getUserState(int $userId): ?array {
        $cacheFile = CACHE_PATH . "/user_state_{$userId}.json";
        
        if (file_exists($cacheFile)) {
            $state = json_decode(file_get_contents($cacheFile), true);
            
            // Check if state is not expired (1 hour)
            if ($state && (time() - $state['time']) < 3600) {
                return $state;
            }
        }
        
        return null;
    }
    
    /**
     * Clear user state
     */
    private function clearUserState(int $userId): void {
        $cacheFile = CACHE_PATH . "/user_state_{$userId}.json";
        if (file_exists($cacheFile)) {
            unlink($cacheFile);
        }
    }
    
    /**
     * Parse command
     */
    private function parseCommand(string $text): string {
        $text = trim($text);
        $text = preg_replace('/^[\/\!\?#@]+/', '', $text);
        $text = preg_replace('/@' . BOT_USERNAME . '$/i', '', $text);
        return strtolower($text);
    }
}
