<?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 CampaignsTableSeeder extends Seeder
{
    /**
     * 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 campaigns seeder.');
            return;
        }

        $now = Carbon::now();
        $campaigns = [];

        // 4 Scheduled campaigns (future dates)
        $scheduledCampaigns = [
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'title' => 'Summer Sale Promotion 2024',
                'content' => 'Get ready for our biggest summer sale! Enjoy up to 50% off on all products. Limited time offer. Shop now and save big!',
                'channel' => 'whatsapp',
                'status' => 'scheduled',
                'starts_at' => $now->copy()->addDays(3)->format('Y-m-d H:i:s'),
                'ends_at' => $now->copy()->addDays(10)->format('Y-m-d H:i:s'),
                'created_at' => $now->format('Y-m-d H:i:s'),
                'updated_at' => $now->format('Y-m-d H:i:s'),
            ],
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'title' => 'New Product Launch Announcement',
                'content' => 'We are excited to announce our latest product launch! Be among the first to experience innovation. Pre-order now and get exclusive benefits.',
                'channel' => 'telegram',
                'status' => 'scheduled',
                'starts_at' => $now->copy()->addDays(5)->format('Y-m-d H:i:s'),
                'ends_at' => $now->copy()->addDays(12)->format('Y-m-d H:i:s'),
                'created_at' => $now->format('Y-m-d H:i:s'),
                'updated_at' => $now->format('Y-m-d H:i:s'),
            ],
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'title' => 'Customer Appreciation Week',
                'content' => 'Thank you for being a valued customer! This week, enjoy special discounts and exclusive offers just for you. We appreciate your loyalty!',
                'channel' => 'whatsapp',
                'status' => 'scheduled',
                'starts_at' => $now->copy()->addDays(7)->format('Y-m-d H:i:s'),
                'ends_at' => $now->copy()->addDays(14)->format('Y-m-d H:i:s'),
                'created_at' => $now->format('Y-m-d H:i:s'),
                'updated_at' => $now->format('Y-m-d H:i:s'),
            ],
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'title' => 'Flash Sale - Electronics',
                'content' => 'Flash sale alert! Get amazing deals on electronics. Limited stock available. Don\'t miss out on these incredible prices!',
                'channel' => 'telegram',
                'status' => 'scheduled',
                'starts_at' => $now->copy()->addDays(10)->format('Y-m-d H:i:s'),
                'ends_at' => $now->copy()->addDays(17)->format('Y-m-d H:i:s'),
                'created_at' => $now->format('Y-m-d H:i:s'),
                'updated_at' => $now->format('Y-m-d H:i:s'),
            ],
        ];

        // 4 Running campaigns (current dates)
        $runningCampaigns = [
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'title' => 'Weekly Newsletter Update',
                'content' => 'Stay updated with our weekly newsletter! Get the latest news, tips, and exclusive offers delivered to your inbox every week.',
                'channel' => 'whatsapp',
                'status' => 'running',
                'starts_at' => $now->copy()->subDays(2)->format('Y-m-d H:i:s'),
                'ends_at' => $now->copy()->addDays(5)->format('Y-m-d H:i:s'),
                'created_at' => $now->copy()->subDays(3)->format('Y-m-d H:i:s'),
                'updated_at' => $now->format('Y-m-d H:i:s'),
            ],
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'title' => 'Birthday Special Offers',
                'content' => 'Celebrate your special day with us! Show this message and get a special birthday discount. Valid for the entire month.',
                'channel' => 'telegram',
                'status' => 'running',
                'starts_at' => $now->copy()->subDays(1)->format('Y-m-d H:i:s'),
                'ends_at' => $now->copy()->addDays(6)->format('Y-m-d H:i:s'),
                'created_at' => $now->copy()->subDays(2)->format('Y-m-d H:i:s'),
                'updated_at' => $now->format('Y-m-d H:i:s'),
            ],
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'title' => 'Referral Program Launch',
                'content' => 'Invite friends and earn rewards! For every friend you refer, you both get amazing benefits. Start referring today!',
                'channel' => 'whatsapp',
                'status' => 'running',
                'starts_at' => $now->copy()->subDays(3)->format('Y-m-d H:i:s'),
                'ends_at' => $now->copy()->addDays(4)->format('Y-m-d H:i:s'),
                'created_at' => $now->copy()->subDays(4)->format('Y-m-d H:i:s'),
                'updated_at' => $now->format('Y-m-d H:i:s'),
            ],
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'title' => 'Holiday Season Greetings',
                'content' => 'Wishing you a wonderful holiday season! Enjoy special holiday discounts and make your celebrations even more memorable.',
                'channel' => 'telegram',
                'status' => 'running',
                'starts_at' => $now->copy()->subDays(5)->format('Y-m-d H:i:s'),
                'ends_at' => $now->copy()->addDays(2)->format('Y-m-d H:i:s'),
                'created_at' => $now->copy()->subDays(6)->format('Y-m-d H:i:s'),
                'updated_at' => $now->format('Y-m-d H:i:s'),
            ],
        ];

        // 4 Completed campaigns (past dates)
        $completedCampaigns = [
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'title' => 'Spring Collection Launch',
                'content' => 'Our spring collection is here! Discover the latest trends and styles. Shop now and refresh your wardrobe for the season.',
                'channel' => 'whatsapp',
                'status' => 'published',
                'starts_at' => $now->copy()->subDays(30)->format('Y-m-d H:i:s'),
                'ends_at' => $now->copy()->subDays(20)->format('Y-m-d H:i:s'),
                'created_at' => $now->copy()->subDays(31)->format('Y-m-d H:i:s'),
                'updated_at' => $now->copy()->subDays(20)->format('Y-m-d H:i:s'),
            ],
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'title' => 'Black Friday Mega Sale',
                'content' => 'Black Friday is here! Get unbeatable deals on everything. Shop early for the best selection. Limited time only!',
                'channel' => 'telegram',
                'status' => 'published',
                'starts_at' => $now->copy()->subDays(45)->format('Y-m-d H:i:s'),
                'ends_at' => $now->copy()->subDays(38)->format('Y-m-d H:i:s'),
                'created_at' => $now->copy()->subDays(46)->format('Y-m-d H:i:s'),
                'updated_at' => $now->copy()->subDays(38)->format('Y-m-d H:i:s'),
            ],
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'title' => 'Customer Feedback Survey',
                'content' => 'Help us improve! Share your feedback and get a chance to win exciting prizes. Your opinion matters to us.',
                'channel' => 'whatsapp',
                'status' => 'published',
                'starts_at' => $now->copy()->subDays(25)->format('Y-m-d H:i:s'),
                'ends_at' => $now->copy()->subDays(18)->format('Y-m-d H:i:s'),
                'created_at' => $now->copy()->subDays(26)->format('Y-m-d H:i:s'),
                'updated_at' => $now->copy()->subDays(18)->format('Y-m-d H:i:s'),
            ],
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'title' => 'New Year Celebration Offer',
                'content' => 'Ring in the new year with amazing offers! Start 2024 with great deals and special promotions. Happy New Year!',
                'channel' => 'telegram',
                'status' => 'published',
                'starts_at' => $now->copy()->subDays(60)->format('Y-m-d H:i:s'),
                'ends_at' => $now->copy()->subDays(53)->format('Y-m-d H:i:s'),
                'created_at' => $now->copy()->subDays(61)->format('Y-m-d H:i:s'),
                'updated_at' => $now->copy()->subDays(53)->format('Y-m-d H:i:s'),
            ],
        ];

        $failedCampaigns = [
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'title' => 'Weekend Special Promotion',
                'content' => 'Weekend special! Get exclusive discounts this weekend only. Don\'t miss out on these limited-time offers.',
                'channel' => 'whatsapp',
                'status' => 'published',
                'starts_at' => $now->copy()->subDays(15)->format('Y-m-d H:i:s'),
                'ends_at' => $now->copy()->subDays(12)->format('Y-m-d H:i:s'),
                'created_at' => $now->copy()->subDays(16)->format('Y-m-d H:i:s'),
                'updated_at' => $now->copy()->subDays(12)->format('Y-m-d H:i:s'),
            ],
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'title' => 'Early Bird Discount Campaign',
                'content' => 'Early bird gets the best deals! Sign up early and enjoy exclusive discounts. Limited spots available.',
                'channel' => 'telegram',
                'status' => 'published',
                'starts_at' => $now->copy()->subDays(22)->format('Y-m-d H:i:s'),
                'ends_at' => $now->copy()->subDays(19)->format('Y-m-d H:i:s'),
                'created_at' => $now->copy()->subDays(23)->format('Y-m-d H:i:s'),
                'updated_at' => $now->copy()->subDays(19)->format('Y-m-d H:i:s'),
            ],
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'title' => 'Loyalty Points Redemption',
                'content' => 'Redeem your loyalty points now! Use your accumulated points for amazing rewards and discounts.',
                'channel' => 'whatsapp',
                'status' => 'published',
                'starts_at' => $now->copy()->subDays(18)->format('Y-m-d H:i:s'),
                'ends_at' => $now->copy()->subDays(15)->format('Y-m-d H:i:s'),
                'created_at' => $now->copy()->subDays(19)->format('Y-m-d H:i:s'),
                'updated_at' => $now->copy()->subDays(15)->format('Y-m-d H:i:s'),
            ],
        ];

        $campaigns = array_merge($scheduledCampaigns, $runningCampaigns, $completedCampaigns, $failedCampaigns);

        // Upsert campaigns
        DB::table('marketing_campaigns')->upsert($campaigns, ['unique_identifier'], [
            'user_id', 'title', 'content', 'channel', 'status', 'starts_at', 'ends_at', 'updated_at'
        ]);

        // Create campaign metadata
        $campaignMetas = [];
        
        // Get available segments and contacts for recipients
        $segmentIds = DB::table('segments')->where('user_id', $demoUser->id)->pluck('id')->toArray();
        $contactIds = DB::table('contacts')->where('user_id', $demoUser->id)->pluck('id')->toArray();
        
        // Get available templates for WhatsApp campaigns
        $templateIds = DB::table('templates')
            ->where('user_id', $demoUser->id)
            ->where('channel', 'whatsapp')
            ->where('status', 'approved')
            ->pluck('id')
            ->toArray();
        
        foreach ($campaigns as $campaign) {
            $campaignId = DB::table('marketing_campaigns')->where('unique_identifier', $campaign['unique_identifier'])->value('id');
            
            if ($campaignId) {
                $isScheduled = $campaign['status'] === 'scheduled';
                $hasAiReply = mt_rand(0, 1); // Randomly enable AI reply for some campaigns
                $isWhatsApp = $campaign['channel'] === 'whatsapp';
                
                // Schedule metadata
                $campaignMetas[] = [
                    'owner_type' => 'Modules\MarketingBot\Entities\Campaign',
                    'owner_id' => $campaignId,
                    'key' => 'schedule',
                    'value' => $isScheduled ? 'on' : 'off',
                    'type' => 'string',
                    'created_at' => $now->format('Y-m-d H:i:s'),
                    'updated_at' => $now->format('Y-m-d H:i:s'),
                ];
                
                // Schedule details if scheduled
                if ($isScheduled && isset($campaign['starts_at'])) {
                    $scheduleDate = Carbon::parse($campaign['starts_at'])->format('Y-m-d');
                    $scheduleTime = Carbon::parse($campaign['starts_at'])->format('H:i');
                    $timezone = preference('default_timezone') ?? config('app.timezone');
                    
                    $campaignMetas[] = [
                        'owner_type' => 'Modules\MarketingBot\Entities\Campaign',
                        'owner_id' => $campaignId,
                        'key' => 'schedule_date',
                        'value' => $scheduleDate,
                        'type' => 'string',
                        'created_at' => $now->format('Y-m-d H:i:s'),
                        'updated_at' => $now->format('Y-m-d H:i:s'),
                    ];
                    
                    $campaignMetas[] = [
                        'owner_type' => 'Modules\MarketingBot\Entities\Campaign',
                        'owner_id' => $campaignId,
                        'key' => 'schedule_time',
                        'value' => $scheduleTime,
                        'type' => 'string',
                        'created_at' => $now->format('Y-m-d H:i:s'),
                        'updated_at' => $now->format('Y-m-d H:i:s'),
                    ];
                    
                    $campaignMetas[] = [
                        'owner_type' => 'Modules\MarketingBot\Entities\Campaign',
                        'owner_id' => $campaignId,
                        'key' => 'schedule_at',
                        'value' => $campaign['starts_at'],
                        'type' => 'datetime',
                        'created_at' => $now->format('Y-m-d H:i:s'),
                        'updated_at' => $now->format('Y-m-d H:i:s'),
                    ];
                    
                    $campaignMetas[] = [
                        'owner_type' => 'Modules\MarketingBot\Entities\Campaign',
                        'owner_id' => $campaignId,
                        'key' => 'timezone',
                        'value' => $timezone,
                        'type' => 'string',
                        'created_at' => $now->format('Y-m-d H:i:s'),
                        'updated_at' => $now->format('Y-m-d H:i:s'),
                    ];
                }
                
                // AI Reply metadata (for some campaigns)
                if ($hasAiReply) {
                    $campaignMetas[] = [
                        'owner_type' => 'Modules\MarketingBot\Entities\Campaign',
                        'owner_id' => $campaignId,
                        'key' => 'ai_reply',
                        'value' => 'on',
                        'type' => 'string',
                        'created_at' => $now->format('Y-m-d H:i:s'),
                        'updated_at' => $now->format('Y-m-d H:i:s'),
                    ];
                    
                    $campaignMetas[] = [
                        'owner_type' => 'Modules\MarketingBot\Entities\Campaign',
                        'owner_id' => $campaignId,
                        'key' => 'chat_provider',
                        'value' => 'openai',
                        'type' => 'string',
                        'created_at' => $now->format('Y-m-d H:i:s'),
                        'updated_at' => $now->format('Y-m-d H:i:s'),
                    ];
                    
                    $campaignMetas[] = [
                        'owner_type' => 'Modules\MarketingBot\Entities\Campaign',
                        'owner_id' => $campaignId,
                        'key' => 'chat_model',
                        'value' => 'gpt-4o',
                        'type' => 'string',
                        'created_at' => $now->format('Y-m-d H:i:s'),
                        'updated_at' => $now->format('Y-m-d H:i:s'),
                    ];
                    
                    $campaignMetas[] = [
                        'owner_type' => 'Modules\MarketingBot\Entities\Campaign',
                        'owner_id' => $campaignId,
                        'key' => 'embedding_provider',
                        'value' => 'openai',
                        'type' => 'string',
                        'created_at' => $now->format('Y-m-d H:i:s'),
                        'updated_at' => $now->format('Y-m-d H:i:s'),
                    ];
                    
                    $campaignMetas[] = [
                        'owner_type' => 'Modules\MarketingBot\Entities\Campaign',
                        'owner_id' => $campaignId,
                        'key' => 'embedding_model',
                        'value' => 'text-embedding-ada-002',
                        'type' => 'string',
                        'created_at' => $now->format('Y-m-d H:i:s'),
                        'updated_at' => $now->format('Y-m-d H:i:s'),
                    ];
                }
                
                // Create recipients data structure
                $segmentCount = !empty($segmentIds) ? min(3, count($segmentIds)) : 0;
                $contactCount = !empty($contactIds) ? min(5, count($contactIds)) : 0;
                
                $recipients = [
                    'segments' => $segmentCount > 0 ? array_slice($segmentIds, 0, mt_rand(1, $segmentCount)) : [],
                    'contacts' => $contactCount > 0 ? array_slice($contactIds, 0, mt_rand(1, $contactCount)) : [],
                ];
                
                $campaignMetas[] = [
                    'owner_type' => 'Modules\MarketingBot\Entities\Campaign',
                    'owner_id' => $campaignId,
                    'key' => 'recipients',
                    'value' => json_encode($recipients),
                    'type' => 'string',
                    'created_at' => $now->format('Y-m-d H:i:s'),
                    'updated_at' => $now->format('Y-m-d H:i:s'),
                ];
                
                // WhatsApp template metadata
                if ($isWhatsApp && !empty($templateIds)) {
                    $templateId = $templateIds[array_rand($templateIds)];
                    $template = DB::table('templates')->where('id', $templateId)->first();
                    
                    if ($template) {
                        $campaignMetas[] = [
                            'owner_type' => 'Modules\MarketingBot\Entities\Campaign',
                            'owner_id' => $campaignId,
                            'key' => 'template_id',
                            'value' => (string)$templateId,
                            'type' => 'string',
                            'created_at' => $now->format('Y-m-d H:i:s'),
                            'updated_at' => $now->format('Y-m-d H:i:s'),
                        ];
                        
                        // Template name can be NULL (as per reference)
                        $campaignMetas[] = [
                            'owner_type' => 'Modules\MarketingBot\Entities\Campaign',
                            'owner_id' => $campaignId,
                            'key' => 'template_name',
                            'value' => null,
                            'type' => 'NULL',
                            'created_at' => $now->format('Y-m-d H:i:s'),
                            'updated_at' => $now->format('Y-m-d H:i:s'),
                        ];
                        
                        // Get template components
                        $templateComponents = DB::table('template_metas')
                            ->where('owner_type', 'Modules\MarketingBot\Entities\Template')
                            ->where('owner_id', $templateId)
                            ->where('key', 'components')
                            ->value('value');
                        
                        if ($templateComponents) {
                            $campaignMetas[] = [
                                'owner_type' => 'Modules\MarketingBot\Entities\Campaign',
                                'owner_id' => $campaignId,
                                'key' => 'template',
                                'value' => $templateComponents,
                                'type' => 'string',
                                'created_at' => $now->format('Y-m-d H:i:s'),
                                'updated_at' => $now->format('Y-m-d H:i:s'),
                            ];
                        }
                    }
                }
                
                // Add training_status metadata (some campaigns trained, some not)
                // Only set 'trained' for some campaigns, others won't have this meta (considered not trained)
                if (mt_rand(0, 1)) {
                    $campaignMetas[] = [
                        'owner_type' => 'Modules\MarketingBot\Entities\Campaign',
                        'owner_id' => $campaignId,
                        'key' => 'training_status',
                        'value' => 'trained',
                        'type' => 'string',
                        'created_at' => $now->format('Y-m-d H:i:s'),
                        'updated_at' => $now->format('Y-m-d H:i:s'),
                    ];
                }
            }
        }

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

