<?php
/**
 * SmartThink LMS - WhatsApp Class
 * 
 * Handles WhatsApp Business API integration, messaging, and automation
 */

class WhatsApp {
    private $db;
    private $apiUrl;
    private $phoneId;
    private $accessToken;
    private $webhookUrl;
    
    public function __construct() {
        $this->db = Database::getInstance();
        $this->apiUrl = WHATSAPP_API_URL;
        $this->phoneId = WHATSAPP_PHONE_ID;
        $this->accessToken = WHATSAPP_ACCESS_TOKEN;
        $this->webhookUrl = WHATSAPP_WEBHOOK_URL;
    }
    
    /**
     * Send text message
     */
    public function sendTextMessage($to, $message, $isTemplate = false) {
        $payload = [
            'messaging_product' => 'whatsapp',
            'to' => $this->formatPhoneNumber($to),
            'type' => 'text'
        ];
        
        if ($isTemplate) {
            $payload['text'] = [
                'preview_url' => false,
                'body' => $message
            ];
        } else {
            $payload['text'] = [
                'body' => $message
            ];
        }
        
        return $this->sendMessage($payload);
    }
    
    /**
     * Send template message
     */
    public function sendTemplateMessage($to, $templateName, $language = 'en_US', $components = []) {
        $payload = [
            'messaging_product' => 'whatsapp',
            'to' => $this->formatPhoneNumber($to),
            'type' => 'template',
            'template' => [
                'name' => $templateName,
                'language' => [
                    'code' => $language
                ],
                'components' => $components
            ]
        ];
        
        return $this->sendMessage($payload);
    }
    
    /**
     * Send media message
     */
    public function sendMediaMessage($to, $mediaType, $mediaUrl, $caption = '') {
        $payload = [
            'messaging_product' => 'whatsapp',
            'to' => $this->formatPhoneNumber($to),
            'type' => $mediaType,
            $mediaType => [
                'link' => $mediaUrl
            ]
        ];
        
        if ($caption) {
            $payload[$mediaType]['caption'] = $caption;
        }
        
        return $this->sendMessage($payload);
    }
    
    /**
     * Send location message
     */
    public function sendLocationMessage($to, $latitude, $longitude, $name = '', $address = '') {
        $payload = [
            'messaging_product' => 'whatsapp',
            'to' => $this->formatPhoneNumber($to),
            'type' => 'location',
            'location' => [
                'latitude' => $latitude,
                'longitude' => $longitude
            ]
        ];
        
        if ($name) {
            $payload['location']['name'] = $name;
        }
        
        if ($address) {
            $payload['location']['address'] = $address;
        }
        
        return $this->sendMessage($payload);
    }
    
    /**
     * Send contact message
     */
    public function sendContactMessage($to, $contacts) {
        $payload = [
            'messaging_product' => 'whatsapp',
            'to' => $this->formatPhoneNumber($to),
            'type' => 'contacts',
            'contacts' => $contacts
        ];
        
        return $this->sendMessage($payload);
    }
    
    /**
     * Send interactive message (buttons, list)
     */
    public function sendInteractiveMessage($to, $interactiveType, $header, $body, $footer, $action) {
        $payload = [
            'messaging_product' => 'whatsapp',
            'to' => $this->formatPhoneNumber($to),
            'type' => 'interactive',
            'interactive' => [
                'type' => $interactiveType
            ]
        ];
        
        if ($header) {
            $payload['interactive']['header'] = $header;
        }
        
        if ($body) {
            $payload['interactive']['body'] = $body;
        }
        
        if ($footer) {
            $payload['interactive']['footer'] = $footer;
        }
        
        $payload['interactive']['action'] = $action;
        
        return $this->sendMessage($payload);
    }
    
    /**
     * Send course enrollment notification
     */
    public function sendEnrollmentNotification($userId, $courseId) {
        $user = $this->db->get("SELECT * FROM users WHERE id = ?", [$userId]);
        $course = $this->db->get("SELECT * FROM courses WHERE id = ?", [$courseId]);
        
        if (!$user || !$course) {
            return false;
        }
        
        $message = "ðŸŽ“ Enrollment Confirmed!\n\n" .
                 "You have been successfully enrolled in:\n" .
                 "ðŸ“š {$course['title']}\n\n" .
                 "Access your course from the dashboard:\n" .
                 APP_URL . "/lms/dashboard.php\n\n" .
                 "Happy learning! ðŸš€";
        
        return $this->sendTextMessage($user['phone'], $message);
    }
    
    /**
     * Send course completion notification
     */
    public function sendCompletionNotification($userId, $courseId) {
        $user = $this->db->get("SELECT * FROM users WHERE id = ?", [$userId]);
        $course = $this->db->get("SELECT * FROM courses WHERE id = ?", [$courseId]);
        
        if (!$user || !$course) {
            return false;
        }
        
        $message = "ðŸŽ‰ Congratulations!\n\n" .
                 "You have successfully completed:\n" .
                 "ðŸ“š {$course['title']}\n\n" .
                 "Your certificate is now available!\n" .
                 "View certificate: " . APP_URL . "/lms/certificate.php?id={$courseId}\n\n" .
                 "Great achievement! ðŸ†";
        
        return $this->sendTextMessage($user['phone'], $message);
    }
    
    /**
     * Send payment confirmation
     */
    public function sendPaymentConfirmation($userId, $amount, $currency, $courseTitle = '') {
        $user = $this->db->get("SELECT * FROM users WHERE id = ?", [$userId]);
        
        if (!$user) {
            return false;
        }
        
        $message = "ðŸ’³ Payment Confirmed!\n\n" .
                 "Amount: {$currency} {$amount}\n";
        
        if ($courseTitle) {
            $message .= "Course: {$courseTitle}\n";
        }
        
        $message .= "\nThank you for your payment! ðŸ™\n" .
                   "Transaction ID: " . strtoupper(generateToken(8));
        
        return $this->sendTextMessage($user['phone'], $message);
    }
    
    /**
     * Send welcome message
     */
    public function sendWelcomeMessage($userId) {
        $user = $this->db->get("SELECT * FROM users WHERE id = ?", [$userId]);
        
        if (!$user) {
            return false;
        }
        
        $message = "ðŸ‘‹ Welcome to SmartThink LMS!\n\n" .
                 "Hi {$user['first_name']},\n\n" .
                 "We're excited to have you join our learning community!\n\n" .
                 "ðŸŽ¯ What you can do:\n" .
                 "â€¢ Browse courses\n" .
                 "â€¢ Track progress\n" .
                 "â€¢ Earn certificates\n" .
                 "â€¢ Get 24/7 support\n\n" .
                 "Need help? Just reply to this message!\n\n" .
                 "Start learning: " . APP_URL . "/courses.php\n\n" .
                 "Happy learning! ðŸš€";
        
        return $this->sendTextMessage($user['phone'], $message);
    }
    
    /**
     * Send password reset notification
     */
    public function sendPasswordResetNotification($userId, $resetToken) {
        $user = $this->db->get("SELECT * FROM users WHERE id = ?", [$userId]);
        
        if (!$user) {
            return false;
        }
        
        $resetUrl = APP_URL . "/reset-password.php?token=" . $resetToken;
        
        $message = "ðŸ” Password Reset Request\n\n" .
                 "Hi {$user['first_name']},\n\n" .
                 "We received a request to reset your password.\n\n" .
                 "Click the link below to reset:\n" .
                 $resetUrl . "\n\n" .
                 "âš ï¸ This link expires in 1 hour.\n\n" .
                 "If you didn't request this, please ignore.\n\n" .
                 "Stay safe! ðŸ”’";
        
        return $this->sendTextMessage($user['phone'], $message);
    }
    
    /**
     * Handle webhook
     */
    public function handleWebhook() {
        $input = file_get_contents('php://input');
        $data = json_decode($input, true);
        
        if (!$data) {
            return false;
        }
        
        // Verify webhook
        if (isset($_GET['hub_challenge']) && isset($_GET['hub_verify_token'])) {
            $this->verifyWebhook($_GET['hub_challenge'], $_GET['hub_verify_token']);
            return true;
        }
        
        // Process messages
        if (isset($data['entry'])) {
            foreach ($data['entry'] as $entry) {
                if (isset($entry['changes'])) {
                    foreach ($entry['changes'] as $change) {
                        if ($change['field'] === 'messages') {
                            $this->processMessage($change['value']);
                        }
                    }
                }
            }
        }
        
        return true;
    }
    
    /**
     * Process incoming message
     */
    private function processMessage($messageData) {
        if (!isset($messageData['messages'])) {
            return;
        }
        
        foreach ($messageData['messages'] as $message) {
            $from = $message['from'];
            $messageId = $message['id'];
            $timestamp = $message['timestamp'];
            $messageType = $message['type'];
            
            // Get user by phone number
            $user = $this->db->get("SELECT * FROM users WHERE phone = ?", [$from]);
            
            if (!$user) {
                // Handle unknown user
                $this->handleUnknownUser($from, $message);
                continue;
            }
            
            // Store message
            $this->storeMessage($messageId, $from, $messageType, $message, $timestamp, $user['id']);
            
            // Process message based on type
            switch ($messageType) {
                case 'text':
                    $this->processTextMessage($user, $message['text']['body']);
                    break;
                case 'interactive':
                    $this->processInteractiveMessage($user, $message['interactive']);
                    break;
                case 'button':
                    $this->processButtonMessage($user, $message['button']);
                    break;
                case 'list':
                    $this->processListMessage($user, $message['list']);
                    break;
            }
        }
    }
    
    /**
     * Process text message
     */
    private function processTextMessage($user, $text) {
        $text = strtolower(trim($text));
        
        // Check for keywords
        if (in_array($text, ['hi', 'hello', 'hey'])) {
            $this->sendGreeting($user['id']);
        } elseif (in_array($text, ['help', 'support'])) {
            $this->sendHelpMenu($user['id']);
        } elseif (in_array($text, ['courses', 'course'])) {
            $this->sendCoursesMenu($user['id']);
        } elseif (in_array($text, ['profile', 'account'])) {
            $this->sendProfileInfo($user['id']);
        } elseif (in_array($text, ['certificates', 'certificate'])) {
            $this->sendCertificatesInfo($user['id']);
        } else {
            // Use AI to generate response
            $this->generateAIResponse($user['id'], $text);
        }
    }
    
    /**
     * Send greeting message
     */
    private function sendGreeting($userId) {
        $user = $this->db->get("SELECT * FROM users WHERE id = ?", [$userId]);
        
        $message = "ðŸ‘‹ Hello {$user['first_name']}!\n\n" .
                 "How can I help you today?\n\n" .
                 "ðŸ“š Courses\n" .
                 "ðŸ‘¤ Profile\n" .
                 "ðŸ† Certificates\n" .
                 "â“ Help\n\n" .
                 "Type any keyword or just tell me what you need!";
        
        return $this->sendTextMessage($user['phone'], $message);
    }
    
    /**
     * Send help menu
     */
    private function sendHelpMenu($userId) {
        $user = $this->db->get("SELECT * FROM users WHERE id = ?", [$userId]);
        
        $buttons = [
            [
                'type' => 'reply',
                'reply' => [
                    'id' => 'courses_help',
                    'title' => 'ðŸ“š Course Help'
                ]
            ],
            [
                'type' => 'reply',
                'reply' => [
                    'id' => 'payment_help',
                    'title' => 'ðŸ’³ Payment Help'
                ]
            ],
            [
                'type' => 'reply',
                'reply' => [
                    'id' => 'technical_help',
                    'title' => 'ðŸ”§ Technical Help'
                ]
            ],
            [
                'type' => 'reply',
                'reply' => [
                    'id' => 'human_support',
                    'title' => 'ðŸ‘¨â€ðŸ’¼ Talk to Human'
                ]
            ]
        ];
        
        $payload = [
            'messaging_product' => 'whatsapp',
            'to' => $this->formatPhoneNumber($user['phone']),
            'type' => 'interactive',
            'interactive' => [
                'type' => 'button',
                'body' => [
                    'text' => 'ðŸ†˜ How can I help you? Choose an option below:'
                ],
                'action' => [
                    'buttons' => $buttons
                ]
            ]
        ];
        
        return $this->sendMessage($payload);
    }
    
    /**
     * Send courses menu
     */
    private function sendCoursesMenu($userId) {
        $user = $this->db->get("SELECT * FROM users WHERE id = ?", [$userId]);
        
        // Get user's enrolled courses
        $enrollments = $this->db->getAll(
            "SELECT c.title, c.id FROM course_enrollments ce
             JOIN courses c ON ce.course_id = c.id
             WHERE ce.student_id = ? AND ce.status = 'active'
             LIMIT 5",
            [$userId]
        );
        
        if ($enrollments) {
            $message = "ðŸ“š Your Courses:\n\n";
            foreach ($enrollments as $enrollment) {
                $message .= "â€¢ {$enrollment['title']}\n";
            }
            $message .= "\nContinue learning: " . APP_URL . "/lms/dashboard.php";
        } else {
            $message = "ðŸ“š You haven't enrolled in any courses yet!\n\n" .
                     "Browse courses: " . APP_URL . "/courses.php\n\n" .
                     "Need help choosing? Just ask! ðŸŽ¯";
        }
        
        return $this->sendTextMessage($user['phone'], $message);
    }
    
    /**
     * Generate AI response
     */
    private function generateAIResponse($userId, $message) {
        $user = $this->db->get("SELECT * FROM users WHERE id = ?", [$userId]);
        
        // Simple AI responses (in production, use a real AI service)
        $responses = [
            'how are you' => "I'm doing great, thanks for asking! ðŸ˜Š How can I help you with your learning journey?",
            'thank you' => "You're welcome! Happy to help! ðŸŒŸ",
            'goodbye' => "Goodbye! Have a great day and happy learning! ðŸ‘‹",
            'default' => "I understand you're asking about: '{$message}'. Let me help you with that! ðŸ¤”\n\n" .
                       "You can ask me about:\n" .
                       "â€¢ Courses and enrollments\n" .
                       "â€¢ Payments and billing\n" .
                       "â€¢ Technical issues\n" .
                       "â€¢ Account settings\n\n" .
                       "Or type 'help' for more options!"
        ];
        
        $lowerMessage = strtolower($message);
        $response = $responses['default'];
        
        foreach ($responses as $key => $value) {
            if ($key !== 'default' && strpos($lowerMessage, $key) !== false) {
                $response = $value;
                break;
            }
        }
        
        return $this->sendTextMessage($user['phone'], $response);
    }
    
    /**
     * Send message via WhatsApp API
     */
    private function sendMessage($payload) {
        $url = $this->apiUrl . $this->phoneId . '/messages';
        
        $headers = [
            'Authorization: Bearer ' . $this->accessToken,
            'Content-Type: application/json'
        ];
        
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode === 200) {
            $responseData = json_decode($response, true);
            $messageId = $responseData['messages'][0]['id'] ?? null;
            
            // Store sent message
            $this->storeMessage($messageId, $payload['to'], $payload['type'], $payload, time(), null, 'outgoing');
            
            return [
                'success' => true,
                'message_id' => $messageId,
                'response' => $responseData
            ];
        } else {
            return [
                'success' => false,
                'error' => $response,
                'http_code' => $httpCode
            ];
        }
    }
    
    /**
     * Store message in database
     */
    private function storeMessage($messageId, $from, $messageType, $messageContent, $timestamp, $userId = null, $direction = 'incoming') {
        $data = [
            'message_id' => $messageId,
            'from_number' => $from,
            'to_number' => $this->phoneId,
            'message_type' => $messageType,
            'message_content' => json_encode($messageContent),
            'timestamp' => date('Y-m-d H:i:s', $timestamp),
            'status' => 'delivered',
            'direction' => $direction,
            'user_id' => $userId,
            'is_bot_response' => $direction === 'outgoing' ? 1 : 0
        ];
        
        $this->db->insert('whatsapp_messages', $data);
    }
    
    /**
     * Format phone number
     */
    private function formatPhoneNumber($phone) {
        // Remove all non-numeric characters
        $phone = preg_replace('/[^0-9]/', '', $phone);
        
        // Add country code if missing (assuming US/Canada)
        if (strlen($phone) === 10) {
            $phone = '1' . $phone;
        }
        
        return $phone;
    }
    
    /**
     * Verify webhook
     */
    private function verifyWebhook($challenge, $verifyToken) {
        $expectedToken = 'SmartThink_webhook_token'; // Should be stored securely
        
        if ($verifyToken === $expectedToken) {
            echo $challenge;
            exit;
        }
        
        http_response_code(403);
        exit;
    }
    
    /**
     * Handle unknown user
     */
    private function handleUnknownUser($phone, $message) {
        $message = "ðŸ‘‹ Welcome to SmartThink LMS!\n\n" .
                 "It seems you're not registered with us yet.\n\n" .
                 "ðŸ“ Register here: " . APP_URL . "/lms/register.php\n\n" .
                 "Already registered? Make sure we have your correct phone number.\n\n" .
                 "Type 'help' for assistance!";
        
        return $this->sendTextMessage($phone, $message);
    }
    
    /**
     * Get conversation history
     */
    public function getConversationHistory($userId, $limit = 50) {
        $user = $this->db->get("SELECT phone FROM users WHERE id = ?", [$userId]);
        
        if (!$user) {
            return [];
        }
        
        return $this->db->getAll(
            "SELECT * FROM whatsapp_messages 
             WHERE from_number = ? OR to_number = ?
             ORDER BY timestamp DESC
             LIMIT ?",
            [$user['phone'], $user['phone'], $limit]
        );
    }
    
    /**
     * Get message statistics
     */
    public function getMessageStats($period = '24 hours') {
        $sql = "SELECT 
                    COUNT(*) as total_messages,
                    SUM(CASE WHEN direction = 'incoming' THEN 1 ELSE 0 END) as incoming,
                    SUM(CASE WHEN direction = 'outgoing' THEN 1 ELSE 0 END) as outgoing,
                    SUM(CASE WHEN is_bot_response = 1 THEN 1 ELSE 0 END) as bot_responses,
                    COUNT(DISTINCT from_number) as unique_users
                FROM whatsapp_messages 
                WHERE created_at >= DATE_SUB(NOW(), INTERVAL 1 DAY)";
        
        return $this->db->get($sql);
    }
    
    /**
     * Create message template
     */
    public function createTemplate($name, $category, $language, $components) {
        $url = $this->apiUrl . 'message_templates';
        
        $payload = [
            'name' => $name,
            'category' => $category,
            'language' => $language,
            'components' => $components
        ];
        
        $headers = [
            'Authorization: Bearer ' . $this->accessToken,
            'Content-Type: application/json'
        ];
        
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        return [
            'success' => $httpCode === 200,
            'response' => json_decode($response, true),
            'http_code' => $httpCode
        ];
    }
}
?>
