<?php

namespace Modules\Dummy\Database\Seeders\Modules\MarketingBot\versions\v6_4_0;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Carbon\Carbon;

class InboxTableSeeder extends Seeder
{
    /**
     * Generate a random number string of specified length
     *
     * @param int $length
     * @return string
     */
    private function generateRandomNumberString(int $length): string
    {
        $number = '';
        for ($i = 0; $i < $length; $i++) {
            $number .= mt_rand(0, 9);
        }
        return $number;
    }

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $demoUser = DB::table('users')->where('email', 'user@techvill.net')->first();

        if (!$demoUser) {
            $this->command->warn('Demo user (user@techvill.net) not found. Skipping inbox seeder.');
            return;
        }

        $now = Carbon::now();

        // Get contacts and segments for connections
        $contacts = DB::table('contacts')
            ->where('user_id', $demoUser->id)
            ->get();
        
        $segments = DB::table('segments')
            ->where('user_id', $demoUser->id)
            ->get();

        // Get templates for bot replies
        $templates = DB::table('templates')
            ->where('user_id', $demoUser->id)
            ->where('status', 'approved')
            ->get();

        if ($contacts->isEmpty() && $segments->isEmpty()) {
            $this->command->warn('No contacts or segments found. Skipping inbox seeder.');
            return;
        }

        $conversations = [];
        $conversationMetas = [];
        $conversationReplies = [];

        // Create 15 conversations (mix of contacts and segments)
        $contactIndex = 0;
        $segmentIndex = 0;
        $maxConversations = 15;

        for ($i = 0; $i < $maxConversations; $i++) {
            $isContactBased = false;
            $contact = null;
            $segment = null;
            $channel = 'whatsapp';
            $chatType = 'private';
            $title = '';
            $contactId = null;
            $segmentId = null;
            $telegramChatId = null;

            // Alternate between contacts and segments
            if ($contactIndex < $contacts->count() && ($i % 2 === 0 || $segmentIndex >= $segments->count())) {
                $contact = $contacts[$contactIndex];
                $contactIndex++;
                $isContactBased = true;
                $contactId = $contact->id;
                $channel = $contact->channel;
                $chatType = 'private';
                
                // WhatsApp: Always use phone number as title
                if ($channel === 'whatsapp') {
                    $title = $contact->phone ?? 'Unknown';
                } else {
                    // Telegram: Use contact name or segment name
                    $title = $contact ? $contact->name : ($segment ? $segment->name : 'Unknown');
                }
            } elseif ($segmentIndex < $segments->count()) {
                $segment = $segments[$segmentIndex];
                $segmentIndex++;
                $segmentId = $segment->id;
                
                // Get segment metadata for channel
                $segmentChannelMeta = DB::table('segment_metas')
                    ->where('owner_type', 'Modules\MarketingBot\Entities\Segment')
                    ->where('owner_id', $segment->id)
                    ->where('key', 'channel')
                    ->value('value');
                
                $channel = $segmentChannelMeta ?: 'whatsapp';
                $chatType = 'group';

                // WhatsApp groups: Use a phone-like identifier instead of segment name
                if ($channel === 'whatsapp') {
                    $title = '1' . mt_rand(5550000, 5559999); // Generate a fake US phone number for groups
                } else {
                    $title = $segment->name;
                }
                
                // For Telegram groups, get telegram_chat_id
                if ($channel === 'telegram') {
                    $telegramChatIdMeta = DB::table('segment_metas')
                        ->where('owner_type', 'Modules\MarketingBot\Entities\Segment')
                        ->where('owner_id', $segment->id)
                        ->where('key', 'telegram_chat_id')
                        ->value('value');
                    $telegramChatId = $telegramChatIdMeta;
                }
            } else {
                break; // No more contacts or segments
            }

            $conversationCreatedAt = $now->copy()->subDays(mt_rand(1, 15))->subHours(mt_rand(0, 23));
            $lastInteractionAt = $conversationCreatedAt->copy()->addHours(mt_rand(1, 48));
            
            // Create main conversation (parent)
            $archiveUniqueId = Str::uuid()->toString();
            $conversationData = [
                'parent_id' => null,
                'user_id' => $demoUser->id,
                'title' => $title,
                'content' => null,
                'filtered_content' => null,
                'raw_response' => null,
                'unique_identifier' => $archiveUniqueId,
                'provider' => null,
                'expense' => null,
                'expense_type' => null,
                'type' => 'marketing_bot',
                'status' => 'Active',
                'created_at' => $conversationCreatedAt->format('Y-m-d H:i:s'),
                'updated_at' => $lastInteractionAt->format('Y-m-d H:i:s'),
            ];

            $conversations[] = [
                'data' => $conversationData,
                'contact_id' => $contactId,
                'segment_id' => $segmentId,
                'telegram_chat_id' => $telegramChatId,
                'channel' => $channel,
                'chat_type' => $chatType,
                'last_interaction_at' => $lastInteractionAt,
                'has_unread' => mt_rand(0, 1),
                'unread_count' => mt_rand(0, 5),
            ];

            // Create reply messages based on channel behavior with realistic campaign conversations
            $replies = [];
            
            // Get a random template for this conversation
            $conversationTemplate = $templates->isNotEmpty() ? $templates->random() : null;
            $templateTitle = $conversationTemplate ? $conversationTemplate->title : null;

            if ($channel === 'whatsapp') {
                // WhatsApp: Start with template message from campaign (user)
                $replyCreatedAt = $conversationCreatedAt->copy();
                $botReplyContent = 'Welcome! This is an automated message from our marketing campaign.';

                if ($conversationTemplate) {
                    // Get template components
                    $templateComponents = DB::table('template_metas')
                        ->where('owner_type', 'Modules\MarketingBot\Entities\Template')
                        ->where('owner_id', $conversationTemplate->id)
                        ->where('key', 'components')
                        ->value('value');

                    if ($templateComponents) {
                        $botReplyContent = $templateComponents;
                    }
                }

                $replies[] = [
                    'is_bot_reply' => true,
                    'is_first_reply' => true,
                    'channel' => $channel,
                    'contact' => $contact,
                    'template' => $conversationTemplate,
                    'bot_reply' => $botReplyContent,
                    'created_at' => $replyCreatedAt,
                    'reply_by' => 'user', // Campaign messages are from user
                ];

                // Generate realistic conversation flow based on template type
                $conversationFlow = $this->generateCampaignConversation($templateTitle, $channel, $replyCreatedAt, $contact);
                $replies = array_merge($replies, $conversationFlow);
                
            } else {
                // Telegram: Start with user message
                $replyCreatedAt = $conversationCreatedAt->copy();
                $userMessages = [
                    'Hello, I saw your marketing campaign. Can you tell me more?',
                    'Hi! I\'m interested in your promotional offer.',
                    'I received your campaign message. What are the details?',
                    'Hello! Can you provide more information about this promotion?',
                    'Hi, your marketing message caught my attention!',
                ];
                $userMessage = $userMessages[array_rand($userMessages)];

                $replies[] = [
                    'is_bot_reply' => false,
                    'is_first_reply' => true,
                    'channel' => $channel,
                    'contact' => $contact,
                    'user_reply' => $userMessage,
                    'created_at' => $replyCreatedAt,
                ];

                // Generate realistic conversation flow
                $conversationFlow = $this->generateCampaignConversation($templateTitle, $channel, $replyCreatedAt, $contact);
                $replies = array_merge($replies, $conversationFlow);
            }
            
            // Add bot reply at the end if last message is from user
            if (!empty($replies)) {
                $lastReply = end($replies);
                if (!$lastReply['is_bot_reply']) {
                    // Last message is from user, add a bot reply (AI agent)
                    $replyCreatedAt = $lastReply['created_at']->copy()->addMinutes(mt_rand(5, 30));
                    $botReplies = [
                        'Thank you for your interest! We\'ll be in touch soon with more details.',
                        'Great! We appreciate your engagement. Our team will follow up shortly.',
                        'Thanks for reaching out! We\'ll get back to you with more information.',
                        'We\'re glad you\'re interested! Stay tuned for exciting updates.',
                    ];
                    $botReplyContent = $botReplies[array_rand($botReplies)];
                    
                    $replies[] = [
                        'is_bot_reply' => true,
                        'is_first_reply' => false,
                        'channel' => $channel,
                        'contact' => $contact,
                        'template' => null,
                        'bot_reply' => $botReplyContent,
                        'created_at' => $replyCreatedAt,
                        'reply_by' => 'ai_agent', // AI agent replies
                    ];
                }
            }


            // Process replies
            foreach ($replies as $reply) {
                $replyData = [
                    'parent_unique_id' => $archiveUniqueId, // Will be replaced with parent_id after insert
                    'user_id' => $reply['is_bot_reply'] ? $demoUser->id : null,
                    'title' => null,
                    'content' => null,
                    'filtered_content' => null,
                    'raw_response' => null,
                    'unique_identifier' => '',
                    'provider' => null,
                    'expense' => null,
                    'expense_type' => null,
                    'type' => 'marketing_bot_chat_reply',
                    'status' => 'Active',
                    'created_at' => $reply['created_at']->format('Y-m-d H:i:s'),
                    'updated_at' => $reply['created_at']->format('Y-m-d H:i:s'),
                ];

                if ($reply['is_bot_reply']) {
                    // Bot reply processing
                    $replyMeta = [
                        'is_bot_reply' => true,
                        'is_first_reply' => $reply['is_first_reply'],
                        'channel' => $reply['channel'],
                        'contact' => $reply['contact'],
                        'template' => $reply['template'] ?? null,
                        'bot_reply' => $reply['bot_reply'],
                        'message_type' => $reply['template'] ? 'template' : 'text',
                        'reply_by' => isset($reply['reply_by']) ? $reply['reply_by'] : ($reply['is_first_reply'] && isset($reply['template']) ? 'user' : 'ai_agent'),
                    ];

                    if ($reply['channel'] === 'whatsapp') {
                        $phoneNumber = $isContactBased && $contact && $contact->phone ? $contact->phone : '15551234567';
                        $messageId = 'wamid.' . strtoupper(Str::random(32)) . '=';
                        $replyMeta['message_id'] = $messageId;
                        $replyMeta['message_response_raw'] = json_encode([
                            'messaging_product' => 'whatsapp',
                            'contacts' => [['input' => $phoneNumber, 'wa_id' => $phoneNumber]],
                            'messages' => [['id' => $messageId, 'message_status' => 'accepted']]
                        ]);
                    }
                } else {
                    // User reply processing
                    $replyMeta = [
                        'is_bot_reply' => false,
                        'is_first_reply' => $reply['is_first_reply'],
                        'channel' => $reply['channel'],
                        'contact' => $reply['contact'],
                        'user_reply' => $reply['user_reply'],
                    ];

                    if ($reply['channel'] === 'whatsapp') {
                        $phoneNumber = $isContactBased && $contact && $contact->phone ? $contact->phone : '15551234567';
                        $messageId = 'wamid.' . strtoupper(Str::random(32)) . '=';
                        $replyMeta['message_id'] = $messageId;

                        $replyData['raw_response'] = json_encode([
                            'object' => 'whatsapp_business_account',
                            'entry' => [[
                                'id' => $this->generateRandomNumberString(15),
                                'changes' => [[
                                    'value' => [
                                        'messaging_product' => 'whatsapp',
                                        'metadata' => [
                                            'display_phone_number' => '15556300101',
                                            'phone_number_id' => $this->generateRandomNumberString(15)
                                        ],
                                        'contacts' => [[
                                            'profile' => ['name' => $isContactBased && $contact ? $contact->name : 'User'],
                                            'wa_id' => $phoneNumber
                                        ]],
                                        'messages' => [[
                                            'from' => $phoneNumber,
                                            'id' => $messageId,
                                            'timestamp' => (string)$reply['created_at']->timestamp,
                                            'text' => ['body' => $reply['user_reply']],
                                            'type' => 'text'
                                        ]]
                                    ],
                                    'field' => 'messages'
                                ]]
                            ]]
                        ]);
                    }
                }

                $conversationReplies[] = [
                    'data' => $replyData,
                    'meta' => $replyMeta,
                ];
            }
        }

        // Insert main conversations first
        if (!empty($conversations)) {
            $archiveData = array_map(function($conv) {
                return $conv['data'];
            }, $conversations);

            DB::table('archives')->upsert($archiveData, ['unique_identifier'], [
                'parent_id', 'user_id', 'title', 'content', 'filtered_content', 'raw_response',
                'provider', 'expense', 'expense_type', 'type', 'status', 'updated_at'
            ]);

            // Get inserted archive IDs
            $insertedArchives = DB::table('archives')
                ->whereIn('unique_identifier', array_column($archiveData, 'unique_identifier'))
                ->get()
                ->keyBy('unique_identifier');

            // Create and insert archive metadata
            $archiveMetas = [];
            foreach ($conversations as $index => $conv) {
                $archiveUniqueId = $conv['data']['unique_identifier'];
                $archiveId = $insertedArchives[$archiveUniqueId]->id ?? null;
                
                if (!$archiveId) continue;

                $archiveMetas[] = [
                    'owner_type' => 'Modules\OpenAI\Entities\Archive',
                    'owner_id' => $archiveId,
                    'key' => 'channel',
                    'value' => $conv['channel'],
                    'type' => 'string',
                    'created_at' => $conv['data']['created_at'],
                    'updated_at' => $conv['data']['created_at'],
                ];

                if ($conv['contact_id']) {
                    $archiveMetas[] = [
                        'owner_type' => 'Modules\OpenAI\Entities\Archive',
                        'owner_id' => $archiveId,
                        'key' => 'contact_id',
                        'value' => (string)$conv['contact_id'],
                        'type' => 'integer',
                        'created_at' => $conv['data']['created_at'],
                        'updated_at' => $conv['data']['created_at'],
                    ];
                }

                if ($conv['segment_id']) {
                    $archiveMetas[] = [
                        'owner_type' => 'Modules\OpenAI\Entities\Archive',
                        'owner_id' => $archiveId,
                        'key' => 'segment_id',
                        'value' => (string)$conv['segment_id'],
                        'type' => 'integer',
                        'created_at' => $conv['data']['created_at'],
                        'updated_at' => $conv['data']['created_at'],
                    ];
                }

                if ($conv['telegram_chat_id']) {
                    $archiveMetas[] = [
                        'owner_type' => 'Modules\OpenAI\Entities\Archive',
                        'owner_id' => $archiveId,
                        'key' => 'telegram_chat_id',
                        'value' => $conv['telegram_chat_id'],
                        'type' => 'string',
                        'created_at' => $conv['data']['created_at'],
                        'updated_at' => $conv['data']['created_at'],
                    ];
                }

                $archiveMetas[] = [
                    'owner_type' => 'Modules\OpenAI\Entities\Archive',
                    'owner_id' => $archiveId,
                    'key' => 'chat_type',
                    'value' => $conv['chat_type'],
                    'type' => 'string',
                    'created_at' => $conv['data']['created_at'],
                    'updated_at' => $conv['data']['created_at'],
                ];

                $archiveMetas[] = [
                    'owner_type' => 'Modules\OpenAI\Entities\Archive',
                    'owner_id' => $archiveId,
                    'key' => 'last_interaction_at',
                    'value' => $conv['last_interaction_at']->format('Y-m-d H:i:s'),
                    'type' => 'datetime',
                    'created_at' => $conv['data']['created_at'],
                    'updated_at' => $conv['last_interaction_at']->format('Y-m-d H:i:s'),
                ];

                $archiveMetas[] = [
                    'owner_type' => 'Modules\OpenAI\Entities\Archive',
                    'owner_id' => $archiveId,
                    'key' => 'has_unread_message',
                    'value' => (string)$conv['has_unread'],
                    'type' => 'boolean',
                    'created_at' => $conv['data']['created_at'],
                    'updated_at' => $conv['last_interaction_at']->format('Y-m-d H:i:s'),
                ];

                $archiveMetas[] = [
                    'owner_type' => 'Modules\OpenAI\Entities\Archive',
                    'owner_id' => $archiveId,
                    'key' => 'has_unread_message_count',
                    'value' => (string)$conv['unread_count'],
                    'type' => 'integer',
                    'created_at' => $conv['data']['created_at'],
                    'updated_at' => $conv['last_interaction_at']->format('Y-m-d H:i:s'),
                ];
            }

            if (!empty($archiveMetas)) {
                DB::table('archives_meta')->upsert($archiveMetas, ['owner_type', 'owner_id', 'key'], [
                    'value', 'type', 'updated_at'
                ]);
            }
        }

        // Insert reply messages
        if (!empty($conversationReplies)) {
            // Map parent unique IDs to actual archive IDs
            $parentArchiveMap = [];
            foreach ($conversations as $conv) {
                $parentArchiveMap[$conv['data']['unique_identifier']] = $insertedArchives[$conv['data']['unique_identifier']]->id ?? null;
            }

            // Prepare reply data with actual parent_ids
            $replyData = [];
            foreach ($conversationReplies as $reply) {
                $parentId = $parentArchiveMap[$reply['data']['parent_unique_id']] ?? null;
                if (!$parentId) continue;

                $replyRecord = $reply['data'];
                $replyRecord['parent_id'] = $parentId;
                unset($replyRecord['parent_unique_id']);
                $replyData[] = $replyRecord;
            }

            if (!empty($replyData)) {
                // Insert replies in batches to maintain order
                $insertedReplyIds = [];
                foreach ($replyData as $reply) {
                    $replyId = DB::table('archives')->insertGetId($reply);
                    $insertedReplyIds[] = $replyId;
                }

                // Get inserted replies in the same order
                $insertedReplies = DB::table('archives')
                    ->whereIn('id', $insertedReplyIds)
                    ->orderBy('id')
                    ->get()
                    ->keyBy('id');

                // Create and insert reply metadata
                $replyMetas = [];
                $replyDataIndex = 0;
                
                foreach ($conversationReplies as $reply) {
                    $parentId = $parentArchiveMap[$reply['data']['parent_unique_id']] ?? null;
                    if (!$parentId) continue;

                    // Get the inserted reply by index
                    if ($replyDataIndex >= count($insertedReplyIds)) {
                        continue;
                    }
                    
                    $replyId = $insertedReplyIds[$replyDataIndex];
                    $insertedReply = $insertedReplies[$replyId] ?? null;
                    $replyDataIndex++;
                    
                    if (!$insertedReply) continue;

                    $meta = $reply['meta'];
                    $createdAt = $reply['data']['created_at'];

                if ($meta['is_bot_reply']) {
                    // Check if bot_reply contains JSON components (template structure)
                    $botReplyValue = is_array($meta['bot_reply']) ? json_encode($meta['bot_reply']) : $meta['bot_reply'];
                    $isTemplateMessage = false;
                    
                    // Try to decode and check if it's a template components array
                    $decoded = json_decode($botReplyValue, true);
                    if (is_array($decoded) && !empty($decoded) && isset($decoded[0]['type'])) {
                        // It's a template components array
                        $isTemplateMessage = true;
                    }
                    
                    // Use reply_by from reply meta if set, otherwise determine from template
                    $replyBy = isset($meta['reply_by']) ? $meta['reply_by'] : ($isTemplateMessage ? 'user' : 'ai_agent');
                        
                        $replyMetas[] = [
                            'owner_type' => 'Modules\OpenAI\Entities\Archive',
                            'owner_id' => $insertedReply->id,
                            'key' => 'reply_by',
                            'value' => $replyBy,
                            'type' => 'string',
                            'created_at' => $createdAt,
                            'updated_at' => $createdAt,
                        ];

                        // Set message_type to 'template' if it contains template components
                        if ($isTemplateMessage) {
                            $replyMetas[] = [
                                'owner_type' => 'Modules\OpenAI\Entities\Archive',
                                'owner_id' => $insertedReply->id,
                                'key' => 'message_type',
                                'value' => 'template',
                                'type' => 'string',
                                'created_at' => $createdAt,
                                'updated_at' => $createdAt,
                            ];
                        }

                        // Store bot_reply
                        $replyMetas[] = [
                            'owner_type' => 'Modules\OpenAI\Entities\Archive',
                            'owner_id' => $insertedReply->id,
                            'key' => 'bot_reply',
                            'value' => $botReplyValue,
                            'type' => 'string',
                            'created_at' => $createdAt,
                            'updated_at' => $createdAt,
                        ];

                        if (isset($meta['message_id'])) {
                            $replyMetas[] = [
                                'owner_type' => 'Modules\OpenAI\Entities\Archive',
                                'owner_id' => $insertedReply->id,
                                'key' => 'message_id',
                                'value' => $meta['message_id'],
                                'type' => 'string',
                                'created_at' => $createdAt,
                                'updated_at' => $createdAt,
                            ];
                        }

                        if (isset($meta['message_response_raw'])) {
                            $replyMetas[] = [
                                'owner_type' => 'Modules\OpenAI\Entities\Archive',
                                'owner_id' => $insertedReply->id,
                                'key' => 'message_response_raw',
                                'value' => is_array($meta['message_response_raw']) ? json_encode($meta['message_response_raw']) : $meta['message_response_raw'],
                                'type' => 'string',
                                'created_at' => $createdAt,
                                'updated_at' => $createdAt,
                            ];
                        }
                    } else {
                        if (isset($meta['user_reply'])) {
                            $replyMetas[] = [
                                'owner_type' => 'Modules\OpenAI\Entities\Archive',
                                'owner_id' => $insertedReply->id,
                                'key' => 'user_reply',
                                'value' => $meta['user_reply'],
                                'type' => 'string',
                                'created_at' => $createdAt,
                                'updated_at' => $createdAt,
                            ];
                        }

                        if (isset($meta['message_id'])) {
                            $replyMetas[] = [
                                'owner_type' => 'Modules\OpenAI\Entities\Archive',
                                'owner_id' => $insertedReply->id,
                                'key' => 'message_id',
                                'value' => $meta['message_id'],
                                'type' => 'string',
                                'created_at' => $createdAt,
                                'updated_at' => $createdAt,
                            ];
                        }

                        if ($meta['channel'] === 'whatsapp') {
                            $replyMetas[] = [
                                'owner_type' => 'Modules\OpenAI\Entities\Archive',
                                'owner_id' => $insertedReply->id,
                                'key' => 'channel',
                                'value' => 'whatsapp',
                                'type' => 'string',
                                'created_at' => $createdAt,
                                'updated_at' => $createdAt,
                            ];
                        }
                    }
                }

                if (!empty($replyMetas)) {
                    DB::table('archives_meta')->upsert($replyMetas, ['owner_type', 'owner_id', 'key'], [
                        'value', 'type', 'updated_at'
                    ]);
                }
            }
        }
    }

    /**
     * Generate realistic campaign conversation based on template type
     *
     * @param string|null $templateTitle
     * @param string $channel
     * @param Carbon $startTime
     * @param object|null $contact
     * @return array
     */
    private function generateCampaignConversation(?string $templateTitle, string $channel, Carbon $startTime, $contact = null): array
    {
        $replies = [];
        $currentTime = $startTime->copy();
        
        // Define campaign-specific questions and responses based on template type
        $conversationData = $this->getConversationDataByTemplate($templateTitle);
        
        // Generate 2-4 additional messages in the conversation
        $messageCount = mt_rand(2, 4);
        
        for ($i = 0; $i < $messageCount; $i++) {
            $currentTime = $currentTime->copy()->addMinutes(mt_rand(5, 180));
            $isUserQuestion = ($i % 2 === 0); // Alternate between user questions and bot replies
            
            if ($isUserQuestion) {
                // User asks a question
                $questions = $conversationData['questions'] ?? [
                    'Can you tell me more about this offer?',
                    'What are the terms and conditions?',
                    'How do I redeem this?',
                    'Is this still available?',
                ];
                $userMessage = $questions[array_rand($questions)];
                
                $replies[] = [
                    'is_bot_reply' => false,
                    'is_first_reply' => false,
                    'channel' => $channel,
                    'contact' => $contact,
                    'user_reply' => $userMessage,
                    'created_at' => $currentTime,
                ];
            } else {
                // Bot replies (either AI agent or user)
                $isAiAgentReply = mt_rand(0, 1); // 50% chance AI agent, 50% user
                
                if ($isAiAgentReply) {
                    // AI Agent reply
                    $aiResponses = $conversationData['ai_responses'] ?? [
                        'Great question! Let me help you with that.',
                        'I can provide more details about this offer.',
                        'The promotion is valid until the end of the month.',
                        'You can redeem this by using the code provided.',
                    ];
                    $botReplyContent = $aiResponses[array_rand($aiResponses)];
                    
                    $replies[] = [
                        'is_bot_reply' => true,
                        'is_first_reply' => false,
                        'channel' => $channel,
                        'contact' => $contact,
                        'template' => null,
                        'bot_reply' => $botReplyContent,
                        'created_at' => $currentTime,
                        'reply_by' => 'ai_agent',
                    ];
                } else {
                    // User (campaign manager) reply
                    $userResponses = $conversationData['user_responses'] ?? [
                        'Thank you for your interest! The offer is valid for all customers.',
                        'You can use this promotion code at checkout.',
                        'The terms are simple: just apply the code during purchase.',
                        'Yes, this offer is still available and valid until the end of the month.',
                    ];
                    $botReplyContent = $userResponses[array_rand($userResponses)];
                    
                    $replies[] = [
                        'is_bot_reply' => true,
                        'is_first_reply' => false,
                        'channel' => $channel,
                        'contact' => $contact,
                        'template' => null,
                        'bot_reply' => $botReplyContent,
                        'created_at' => $currentTime,
                        'reply_by' => 'user',
                    ];
                }
            }
        }
        
        return $replies;
    }

    /**
     * Get conversation data based on template type
     *
     * @param string|null $templateTitle
     * @return array
     */
    private function getConversationDataByTemplate(?string $templateTitle): array
    {
        $data = [
            'questions' => [],
            'ai_responses' => [],
            'user_responses' => [],
        ];

        switch ($templateTitle) {
            case 'summer_sale_announcement':
                $data['questions'] = [
                    'What products are included in the summer sale?',
                    'How long is this sale valid?',
                    'Can I combine this with other discounts?',
                    'What\'s the maximum discount I can get?',
                    'Are there any exclusions?',
                ];
                $data['ai_responses'] = [
                    'The summer sale includes all products in our catalog!',
                    'The sale is valid until July 31st, so you have plenty of time.',
                    'Yes, you can stack this discount with other promotions.',
                    'The maximum discount varies by product category.',
                ];
                $data['user_responses'] = [
                    'All products are included! The sale runs until July 31st.',
                    'You can save up to 50% on selected items. Check our website for details.',
                    'Yes, this discount can be combined with other offers.',
                    'The sale includes everything except clearance items.',
                ];
                break;

            case 'discount_code_promo':
                $data['questions'] = [
                    'How do I use this discount code?',
                    'What\'s the discount percentage?',
                    'Is there a minimum purchase amount?',
                    'Can I share this code with friends?',
                    'When does this code expire?',
                ];
                $data['ai_responses'] = [
                    'Simply enter the code at checkout to apply the discount.',
                    'The discount is 25% off your total purchase.',
                    'There\'s no minimum purchase required.',
                    'Yes, feel free to share with your friends and family!',
                ];
                $data['user_responses'] = [
                    'Enter the code SAVE25 at checkout for 25% off.',
                    'The code gives you 25% off with no minimum purchase.',
                    'You can share this code - it\'s valid for everyone!',
                    'This code expires on December 31st.',
                ];
                break;

            case 'referral_program':
                $data['questions'] = [
                    'How does the referral program work?',
                    'What do I get for referring someone?',
                    'How many people can I refer?',
                    'When will I receive my reward?',
                ];
                $data['ai_responses'] = [
                    'Refer friends and both you and your friend get rewards!',
                    'You\'ll receive a $10 credit for each successful referral.',
                    'There\'s no limit to how many people you can refer.',
                    'Rewards are credited within 24 hours of your friend\'s first purchase.',
                ];
                $data['user_responses'] = [
                    'Share your unique referral link. When your friend makes a purchase, you both get $10 credit!',
                    'You get $10 for each referral, and there\'s no limit.',
                    'Rewards are processed automatically after your friend\'s first order.',
                ];
                break;

            case 'product_launch_notification':
                $data['questions'] = [
                    'When will this product be available?',
                    'What\'s the price?',
                    'Can I pre-order?',
                    'What features does it have?',
                ];
                $data['ai_responses'] = [
                    'The product launches next week on Monday!',
                    'Pricing details will be announced on launch day.',
                    'Yes, pre-orders are available now.',
                    'It includes all the features we mentioned in our campaign.',
                ];
                $data['user_responses'] = [
                    'Launch date is next Monday. Pre-orders are open now!',
                    'Pricing starts at $99. Pre-order now to get early access.',
                    'You can pre-order today and get it delivered on launch day.',
                ];
                break;

            case 'welcome_message':
                $data['questions'] = [
                    'What should I do first?',
                    'How do I get started?',
                    'What features are available?',
                ];
                $data['ai_responses'] = [
                    'Start by exploring our platform and checking out the features.',
                    'You can begin by setting up your profile.',
                    'We have many features available - check out our help section.',
                ];
                $data['user_responses'] = [
                    'Welcome! Start by exploring the dashboard and setting up your preferences.',
                    'Check out our getting started guide for step-by-step instructions.',
                ];
                break;

            default:
                $data['questions'] = [
                    'Can you tell me more about this offer?',
                    'What are the terms and conditions?',
                    'How do I redeem this?',
                    'Is this still available?',
                ];
                $data['ai_responses'] = [
                    'I\'d be happy to provide more details about this promotion.',
                    'The terms are available on our website.',
                    'You can redeem this offer by following the instructions in the message.',
                ];
                $data['user_responses'] = [
                    'The offer is valid for all customers. Check our website for full terms.',
                    'You can redeem this at checkout using the provided code.',
                ];
                break;
        }

        return $data;
    }
}

