<?php

/**
 * Feature Integration Examples
 * 
 * This file contains code snippets showing how to integrate
 * the newly implemented features into your existing Laravel app.
 */

namespace App\Examples;

use App\Models\Chatbot;
use App\Models\CustomVariable;
use App\Models\Invoice;
use App\Notifications\MessageSentNotification;
use App\Services\DeviceRotationService;

class FeatureIntegrationExamples
{
    /**
     * Example 1: Send notification when message is sent
     * Add this to your SendmsgController or WebhookController
     */
    public function sendMessageWithNotification($user, $message, $receiver, $status)
    {
        // Send the actual message (your existing code)
        // ...

        // Send notification to user
        $user->notify(new MessageSentNotification($message, $receiver, $status));
    }

    /**
     * Example 2: Use custom variables in message text
     * Add this to your message processing logic
     */
    public function replaceVariablesInMessage($userId, $messageText, $additionalVars = [])
    {
        // Replace user's custom variables
        $processedText = CustomVariable::replaceVariables($messageText, $userId, $additionalVars);
        
        return $processedText;
    }

    /**
     * Example 3: Process message through chatbot
     * Add this to your WebhookController before other autoreply logic
     */
    public function processChatbotMessage($sender, $phone, $message)
    {
        // Find active chatbot for this device
        $chatbot = Chatbot::where('sender', $sender)
            ->where('is_active', true)
            ->orderBy('priority', 'desc')
            ->first();

        if ($chatbot) {
            $response = $chatbot->processMessage($phone, $message);
            return $response;
        }

        return null;
    }

    /**
     * Example 4: Generate invoice after successful transaction
     * Add this to your TransactionController after payment success
     */
    public function generateInvoiceAfterPayment($transaction)
    {
        $invoice = Invoice::create([
            'user_id' => $transaction->user_id,
            'invoice_number' => Invoice::generateInvoiceNumber(),
            'invoice_type' => 'transaction',
            'transaction_id' => $transaction->id,
            'amount' => $transaction->amount,
            'tax' => 0,
            'discount' => 0,
            'total' => $transaction->amount,
            'currency' => 'USD',
            'status' => 'paid',
            'description' => 'Payment for ' . $transaction->description,
            'issued_at' => now(),
            'paid_at' => now(),
        ]);

        // Optionally send invoice notification
        $transaction->user->notify(new \App\Notifications\InvoiceGeneratedNotification($invoice));

        return $invoice;
    }

    /**
     * Example 5: Use device rotation when sending bulk messages
     * Add this to your SendmsgController for bulk sending
     */
    public function sendWithDeviceRotation($userId, $receivers, $message, $enableRotation = true)
    {
        if (!$enableRotation) {
            // Use existing single-device logic
            return;
        }

        // Get available devices
        $availableDevices = DeviceRotationService::getAvailableDevices($userId);

        if (count($availableDevices) < 2) {
            // Not enough devices for rotation, use normal flow
            return;
        }

        // Distribute receivers across devices
        $distribution = DeviceRotationService::distributeMessages($receivers, $availableDevices);

        foreach ($distribution as $deviceSender => $deviceReceivers) {
            foreach ($deviceReceivers as $receiver) {
                // Create outbox entry
                $outbox = new \App\Models\Outbox();
                $outbox->user_id = $userId;
                $outbox->sender = $deviceSender;
                $outbox->receiver = $receiver;
                $outbox->msgtext = $message;
                $outbox->use_device_rotation = true;
                $outbox->rotation_devices = $availableDevices;
                $outbox->current_rotation_device = $deviceSender;
                $outbox->save();
            }
        }
    }

    /**
     * Example 6: Enhanced message sending with all features
     * Complete integration example
     */
    public function sendEnhancedMessage($userId, $receiver, $messageText, $options = [])
    {
        $user = \App\Models\User::find($userId);

        // 1. Replace custom variables
        $customVars = $options['variables'] ?? [];
        $processedMessage = CustomVariable::replaceVariables($messageText, $userId, $customVars);

        // 2. Check if chatbot should handle this (for incoming messages)
        if (isset($options['is_incoming']) && $options['is_incoming']) {
            $chatbotResponse = $this->processChatbotMessage(
                $options['sender'],
                $receiver,
                $processedMessage
            );
            
            if ($chatbotResponse) {
                return $chatbotResponse;
            }
        }

        // 3. Select device (with or without rotation)
        $device = null;
        if ($options['use_rotation'] ?? false) {
            $devices = DeviceRotationService::getAvailableDevices($userId);
            $deviceSender = DeviceRotationService::getLeastBusyDevice($devices);
            $device = \App\Models\Device::where('sender', $deviceSender)->first();
        } else {
            $device = \App\Models\Device::where('user_id', $userId)
                ->where('status', 'ONLINE')
                ->first();
        }

        if (!$device) {
            return ['error' => 'No available device'];
        }

        // 4. Create outbox entry
        $outbox = new \App\Models\Outbox();
        $outbox->user_id = $userId;
        $outbox->sender = $device->sender;
        $outbox->receiver = $receiver;
        $outbox->msgtext = $processedMessage;
        $outbox->schedule = $options['schedule'] ?? now();
        $outbox->msgdelay = $options['delay'] ?? rand(1, 3);
        $outbox->recurring = $options['recurring'] ?? null;
        
        if ($options['use_rotation'] ?? false) {
            $outbox->use_device_rotation = true;
            $outbox->rotation_devices = DeviceRotationService::getAvailableDevices($userId);
        }
        
        $outbox->save();

        // 5. Send notification
        $user->notify(new MessageSentNotification(
            $processedMessage,
            $receiver,
            'PENDING'
        ));

        return ['success' => true, 'outbox_id' => $outbox->id];
    }

    /**
     * Example 7: Create a simple chatbot
     */
    public function createSimpleChatbot($userId, $deviceSender)
    {
        $chatbot = Chatbot::create([
            'user_id' => $userId,
            'sender' => $deviceSender,
            'name' => 'FAQ Bot',
            'description' => 'Answers frequently asked questions',
            'type' => 'rule-based',
            'is_active' => true,
            'priority' => 10,
            'intents' => [
                [
                    'name' => 'greeting',
                    'patterns' => ['hello', 'hi', 'hey', 'good morning', 'good afternoon'],
                    'responses' => [
                        'Hello! How can I help you today?',
                        'Hi there! What can I do for you?',
                        'Hey! How may I assist you?'
                    ]
                ],
                [
                    'name' => 'hours',
                    'patterns' => ['hours', 'open', 'working hours', 'when open', 'timing'],
                    'responses' => [
                        'We are open Monday to Friday, 9 AM to 6 PM.',
                        'Our working hours are 9:00 AM - 6:00 PM, Monday through Friday.'
                    ]
                ],
                [
                    'name' => 'pricing',
                    'patterns' => ['price', 'cost', 'how much', 'pricing', 'rate'],
                    'responses' => [
                        'Our prices start from $10. Please contact our sales team for a detailed quote.',
                        'Pricing varies based on your needs. Would you like to speak with our sales team?'
                    ]
                ],
                [
                    'name' => 'support',
                    'patterns' => ['help', 'support', 'problem', 'issue', 'not working'],
                    'responses' => [
                        'I\'m here to help! Please describe your issue in detail.',
                        'Let me assist you. What seems to be the problem?'
                    ]
                ]
            ],
            'fallback_message' => 'I\'m sorry, I didn\'t understand that. Please type "menu" to see available options or contact our support team.',
        ]);

        return $chatbot;
    }

    /**
     * Example 8: Bulk create custom variables
     */
    public function createCustomVariables($userId)
    {
        $variables = [
            ['key' => 'company_name', 'value' => 'Acme Corporation', 'type' => 'text'],
            ['key' => 'support_email', 'value' => 'support@acme.com', 'type' => 'text'],
            ['key' => 'support_phone', 'value' => '+1-800-123-4567', 'type' => 'text'],
            ['key' => 'website', 'value' => 'https://acme.com', 'type' => 'text'],
            ['key' => 'office_hours', 'value' => '9 AM - 6 PM, Mon-Fri', 'type' => 'text'],
            ['key' => 'discount_rate', 'value' => '10', 'type' => 'number'],
            ['key' => 'trial_days', 'value' => '30', 'type' => 'number'],
        ];

        foreach ($variables as $var) {
            CustomVariable::create([
                'user_id' => $userId,
                'key' => $var['key'],
                'value' => $var['value'],
                'type' => $var['type'],
                'is_global' => true,
            ]);
        }
    }

    /**
     * Example 9: Message template with variables
     */
    public function createWelcomeTemplate($userId)
    {
        $template = "Hello {name}! 👋\n\n";
        $template .= "Welcome to {company_name}!\n\n";
        $template .= "We're excited to have you on board. Here's what you need to know:\n\n";
        $template .= "📧 Support Email: {support_email}\n";
        $template .= "📞 Phone: {support_phone}\n";
        $template .= "🌐 Website: {website}\n";
        $template .= "⏰ Office Hours: {office_hours}\n\n";
        $template .= "🎁 Special Offer: Get {discount_rate}% off your first purchase!\n";
        $template .= "✨ Free Trial: {trial_days} days\n\n";
        $template .= "Reply with 'help' if you need assistance!";

        // When sending, replace variables:
        // $finalMessage = CustomVariable::replaceVariables($template, $userId, ['name' => 'John']);
        
        return $template;
    }

    /**
     * Example 10: Get rotation statistics for monitoring
     */
    public function getDeviceRotationStats($userId, $jobId)
    {
        $stats = DeviceRotationService::getRotationStats($userId, $jobId);

        /*
        Returns array like:
        [
            'device1' => [
                'total' => 100,
                'sent' => 85,
                'failed' => 5,
                'pending' => 10
            ],
            'device2' => [
                'total' => 100,
                'sent' => 90,
                'failed' => 3,
                'pending' => 7
            ]
        ]
        */

        return $stats;
    }
}
