<?php
/**
 * Telegram Bot Controller
 * Handles user and admin bot interactions
 */

namespace App\Controller;

use App\Classes\Telegram\TelegramBot;

class TelegramBotController {
    protected $db;
    protected $userBot;
    protected $adminBot;
    
    public function __construct($db) {
        $this->db = $db;
        $this->userBot = new TelegramBot(env('TELEGRAM_USER_BOT_TOKEN'));
        $this->adminBot = new TelegramBot(env('TELEGRAM_ADMIN_BOT_TOKEN'));
    }
    
    /**
     * Handle user bot webhook
     */
    public function handleUserBotWebhook($update) {
        try {
            // Get chat ID and message
            $chatId = $update['message']['chat']['id'] ?? $update['callback_query']['from']['id'] ?? null;
            $userId = $update['message']['from']['id'] ?? $update['callback_query']['from']['id'] ?? null;
            $text = $update['message']['text'] ?? '';
            $callbackData = $update['callback_query']['data'] ?? '';
            
            if (!$chatId) {
                return ['ok' => false];
            }
            
            // Link Telegram account to database user
            $this->linkTelegramAccount($userId, $chatId, 'user_bot');
            
            // Handle commands
            if ($text) {
                return $this->handleUserCommand($chatId, $text, $userId);
            } elseif ($callbackData) {
                return $this->handleUserCallback($chatId, $callbackData, $userId);
            }
            
            return ['ok' => true];
            
        } catch (\Exception $e) {
            error_log('User Bot Error: ' . $e->getMessage());
            return ['ok' => false];
        }
    }
    
    /**
     * Handle admin bot webhook
     */
    public function handleAdminBotWebhook($update) {
        try {
            $chatId = $update['message']['chat']['id'] ?? $update['callback_query']['from']['id'] ?? null;
            $text = $update['message']['text'] ?? '';
            $callbackData = $update['callback_query']['data'] ?? '';
            
            if (!$chatId) {
                return ['ok' => false];
            }
            
            // Verify admin access
            if (!$this->isAdminChat($chatId)) {
                $this->adminBot->sendMessage($chatId, '❌ Unauthorized access');
                return ['ok' => false];
            }
            
            // Handle commands
            if ($text) {
                return $this->handleAdminCommand($chatId, $text);
            } elseif ($callbackData) {
                return $this->handleAdminCallback($chatId, $callbackData);
            }
            
            return ['ok' => true];
            
        } catch (\Exception $e) {
            error_log('Admin Bot Error: ' . $e->getMessage());
            return ['ok' => false];
        }
    }
    
    /**
     * Handle user commands
     */
    private function handleUserCommand($chatId, $command, $userId) {
        $cmd = strtolower(trim($command));
        
        if (strpos($cmd, '/start') === 0) {
            return $this->userStart($chatId, $userId);
        } elseif (strpos($cmd, '/help') === 0) {
            return $this->userHelp($chatId);
        } elseif (strpos($cmd, '/balance') === 0) {
            return $this->userBalance($chatId, $userId);
        } elseif (strpos($cmd, '/orders') === 0) {
            return $this->userOrders($chatId, $userId);
        } elseif (strpos($cmd, '/services') === 0) {
            return $this->userServices($chatId);
        } elseif (strpos($cmd, '/deposit') === 0) {
            return $this->userDeposit($chatId, $userId);
        } elseif (strpos($cmd, '/support') === 0) {
            return $this->userSupport($chatId, $userId);
        }
        
        $this->userBot->sendMessage($chatId, "❓ Unknown command. Type /help for available commands.");
        return ['ok' => true];
    }
    
    /**
     * User /start command
     */
    private function userStart($chatId, $userId) {
        $text = "👋 Welcome to <b>BoostWithKagujje</b>\n\n";
        $text .= "Your powerful SMM Services Bot\n\n";
        $text .= "/balance - Check your account balance\n";
        $text .= "/services - Browse services\n";
        $text .= "/orders - View your orders\n";
        $text .= "/deposit - Make a deposit\n";
        $text .= "/help - Get help\n\n";
        $text .= "Need support? Type /support";
        
        return $this->userBot->sendMessage($chatId, $text);
    }
    
    /**
     * User /balance command
     */
    private function userBalance($chatId, $userId) {
        try {
            $stmt = $this->db->prepare('SELECT balance, primary_currency FROM users WHERE telegram_user_id = ?');
            $stmt->execute([$userId]);
            $user = $stmt->fetch(\PDO::FETCH_ASSOC);
            
            if (!$user) {
                return $this->userBot->sendMessage($chatId, "❌ Account not found. Reply with /start");
            }
            
            $balance = TelegramBot::formatPrice($user['balance'], $user['primary_currency']);
            $text = "💰 <b>Your Balance</b>\n\n$balance";
            
            return $this->userBot->sendMessage($chatId, $text);
            
        } catch (\Exception $e) {
            return $this->userBot->sendMessage($chatId, "❌ Error: " . $e->getMessage());
        }
    }
    
    /**
     * User /orders command
     */
    private function userOrders($chatId, $userId) {
        try {
            $stmt = $this->db->prepare('
                SELECT o.id, o.order_id, s.name, o.quantity, o.status, o.created_at
                FROM orders o
                JOIN services s ON o.service_id = s.id
                JOIN users u ON o.user_id = u.id
                WHERE u.telegram_user_id = ?
                ORDER BY o.created_at DESC
                LIMIT 5
            ');
            $stmt->execute([$userId]);
            $orders = $stmt->fetchAll(\PDO::FETCH_ASSOC);
            
            if (empty($orders)) {
                return $this->userBot->sendMessage($chatId, "📭 No orders yet.");
            }
            
            $text = "📋 <b>Your Recent Orders</b>\n\n";
            foreach ($orders as $order) {
                $status = '🔄';
                if ($order['status'] === 'completed') $status = '✅';
                elseif ($order['status'] === 'cancelled') $status = '❌';
                
                $text .= "$status <b>{$order['order_id']}</b>\n";
                $text .= "Service: {$order['name']}\n";
                $text .= "Quantity: {$order['quantity']}\n";
                $text .= "Status: {$order['status']}\n\n";
            }
            
            return $this->userBot->sendMessage($chatId, $text);
            
        } catch (\Exception $e) {
            return $this->userBot->sendMessage($chatId, "❌ Error: " . $e->getMessage());
        }
    }
    
    /**
     * User /services command
     */
    private function userServices($chatId) {
        try {
            $stmt = $this->db->query('
                SELECT id, name, category, base_price FROM services 
                WHERE status = "active" 
                LIMIT 5
            ');
            $services = $stmt->fetchAll(\PDO::FETCH_ASSOC);
            
            if (empty($services)) {
                return $this->userBot->sendMessage($chatId, "📭 No services available.");
            }
            
            $text = "🛍️ <b>Available Services</b>\n\n";
            foreach ($services as $service) {
                $price = TelegramBot::formatPrice($service['base_price'] * 1.80, 'UGX');
                $text .= "• <b>{$service['name']}</b>\n";
                $text .= "  Price: $price\n";
                $text .= "  Category: {$service['category']}\n\n";
            }
            
            $text .= "Visit the website to place orders";
            
            return $this->userBot->sendMessage($chatId, $text);
            
        } catch (\Exception $e) {
            return $this->userBot->sendMessage($chatId, "❌ Error: " . $e->getMessage());
        }
    }
    
    /**
     * User /help command
     */
    private function userHelp($chatId) {
        $text = "<b>🤖 Available Commands</b>\n\n";
        $text .= "/start - Welcome message\n";
        $text .= "/balance - Check balance\n";
        $text .= "/services - Browse services\n";
        $text .= "/orders - View your orders\n";
        $text .= "/deposit - Make a deposit\n";
        $text .= "/support - Contact support\n\n";
        $text .= "Visit: <b>https://boost.kagujje.com</b>";
        
        return $this->userBot->sendMessage($chatId, $text);
    }
    
    /**
     * User /deposit command
     */
    private function userDeposit($chatId, $userId) {
        $text = "💳 <b>How to Deposit</b>\n\n";
        $text .= "1. Visit: <b>https://boost.kagujje.com</b>\n";
        $text .= "2. Go to Wallet → Add Funds\n";
        $text .= "3. Select amount and currency\n";
        $text .= "4. Follow payment instructions\n\n";
        $text .= "Need help? /support";
        
        return $this->userBot->sendMessage($chatId, $text);
    }
    
    /**
     * User /support command
     */
    private function userSupport($chatId, $userId) {
        $text = "📞 <b>Contact Support</b>\n\n";
        $text .= "Email: admin@kagujje.com\n";
        $text .= "Website: https://boost.kagujje.com\n";
        $text .= "Telegram: @boostwithkagujje\n\n";
        $text .= "We respond within 24 hours";
        
        return $this->userBot->sendMessage($chatId, $text);
    }
    
    /**
     * Handle admin commands
     */
    private function handleAdminCommand($chatId, $command) {
        $cmd = strtolower(trim($command));
        
        if (strpos($cmd, '/start') === 0) {
            return $this->adminStart($chatId);
        } elseif (strpos($cmd, '/stats') === 0) {
            return $this->adminStats($chatId);
        } elseif (strpos($cmd, '/orders') === 0) {
            return $this->adminOrders($chatId);
        } elseif (strpos($cmd, '/users') === 0) {
            return $this->adminUsers($chatId);
        } elseif (strpos($cmd, '/settings') === 0) {
            return $this->adminSettings($chatId);
        }
        
        $this->adminBot->sendMessage($chatId, "❓ Admin command not recognized.");
        return ['ok' => true];
    }
    
    /**
     * Admin /start command
     */
    private function adminStart($chatId) {
        $text = "👋 <b>Admin Dashboard Started</b>\n\n";
        $text .= "Available commands:\n";
        $text .= "/stats - Platform statistics\n";
        $text .= "/orders - Recent orders\n";
        $text .= "/users - Total users\n";
        $text .= "/settings - Configuration\n";
        
        return $this->adminBot->sendMessage($chatId, $text);
    }
    
    /**
     * Admin /stats command
     */
    private function adminStats($chatId) {
        try {
            // Get statistics
            $userCount = $this->db->query('SELECT COUNT(*) as count FROM users')->fetch(\PDO::FETCH_ASSOC)['count'];
            $totalBalance = $this->db->query('SELECT SUM(balance) as total FROM users')->fetch(\PDO::FETCH_ASSOC)['total'] ?? 0;
            $todayOrders = $this->db->query('SELECT COUNT(*) as count FROM orders WHERE DATE(created_at) = CURDATE()')->fetch(\PDO::FETCH_ASSOC)['count'];
            $todayRevenue = $this->db->query('SELECT SUM(price) as total FROM orders WHERE DATE(created_at) = CURDATE()')->fetch(\PDO::FETCH_ASSOC)['total'] ?? 0;
            
            $text = "📊 <b>Platform Statistics</b>\n\n";
            $text .= "👥 Total Users: $userCount\n";
            $text .= "💰 Total Balance: " . TelegramBot::formatPrice($totalBalance, 'UGX') . "\n";
            $text .= "📦 Today's Orders: $todayOrders\n";
            $text .= "💵 Today's Revenue: " . TelegramBot::formatPrice($todayRevenue, 'UGX') . "\n";
            
            return $this->adminBot->sendMessage($chatId, $text);
            
        } catch (\Exception $e) {
            return $this->adminBot->sendMessage($chatId, "❌ Error: " . $e->getMessage());
        }
    }
    
    /**
     * Admin /orders command
     */
    private function adminOrders($chatId) {
        try {
            $stmt = $this->db->query('
                SELECT o.order_id, s.name, o.quantity, o.status, o.price
                FROM orders o
                JOIN services s ON o.service_id = s.id
                ORDER BY o.created_at DESC
                LIMIT 5
            ');
            $orders = $stmt->fetchAll(\PDO::FETCH_ASSOC);
            
            $text = "📋 <b>Recent Orders</b>\n\n";
            foreach ($orders as $order) {
                $text .= "• {$order['order_id']}\n";
                $text .= "  Service: {$order['name']}\n";
                $text .= "  Amount: " . TelegramBot::formatPrice($order['price'], 'UGX') . "\n";
                $text .= "  Status: {$order['status']}\n\n";
            }
            
            return $this->adminBot->sendMessage($chatId, $text);
            
        } catch (\Exception $e) {
            return $this->adminBot->sendMessage($chatId, "❌ Error");
        }
    }
    
    /**
     * Admin /users command
     */
    private function adminUsers($chatId) {
        try {
            $total = $this->db->query('SELECT COUNT(*) as count FROM users')->fetch(\PDO::FETCH_ASSOC)['count'];
            $active = $this->db->query('SELECT COUNT(*) as count FROM users WHERE status = "active"')->fetch(\PDO::FETCH_ASSOC)['count'];
            $suspended = $this->db->query('SELECT COUNT(*) as count FROM users WHERE status = "suspended"')->fetch(\PDO::FETCH_ASSOC)['count'];
            
            $text = "👥 <b>User Statistics</b>\n\n";
            $text .= "Total: $total\n";
            $text .= "Active: $active\n";
            $text .= "Suspended: $suspended\n";
            
            return $this->adminBot->sendMessage($chatId, $text);
            
        } catch (\Exception $e) {
            return $this->adminBot->sendMessage($chatId, "❌ Error");
        }
    }
    
    /**
     * Admin /settings command
     */
    private function adminSettings($chatId) {
        $text = "⚙️ <b>Settings</b>\n\n";
        $text .= "Manage through web panel: https://boost.kagujje.com/admin/";
        
        return $this->adminBot->sendMessage($chatId, $text);
    }
    
    /**
     * Link Telegram account to user
     */
    private function linkTelegramAccount($telegramUserId, $chatId, $botType) {
        try {
            // Check if already linked
            $stmt = $this->db->prepare('SELECT id FROM users WHERE telegram_user_id = ?');
            $stmt->execute([$telegramUserId]);
            
            if (!$stmt->fetch()) {
                // Insert telegram mapping
                $insertStmt = $this->db->prepare('
                    INSERT INTO users (telegram_user_id, telegram_chat_id, status, account_type)
                    VALUES (?, ?, "active", "user")
                    ON DUPLICATE KEY UPDATE telegram_chat_id = ?
                ');
                $insertStmt->execute([$telegramUserId, $chatId, $chatId]);
            }
        } catch (\Exception $e) {
            error_log('Telegram Account Link Error: ' . $e->getMessage());
        }
    }
    
    /**
     * Check if chat is admin
     */
    private function isAdminChat($chatId) {
        try {
            $adminChatIds = explode(',', env('TELEGRAM_ADMIN_CHAT_IDS', ''));
            return in_array($chatId, $adminChatIds);
        } catch (\Exception $e) {
            return false;
        }
    }
    
    /**
     * Handle user callback (button presses)
     */
    private function handleUserCallback($chatId, $callbackData, $userId) {
        // Can be expanded for button interactions
        return $this->userBot->answerCallbackQuery($callbackData);
    }
    
    /**
     * Handle admin callback (button presses)
     */
    private function handleAdminCallback($chatId, $callbackData) {
        // Can be expanded for button interactions
        return $this->adminBot->answerCallbackQuery($callbackData);
    }
}
?>
