<?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 TemplatesTableSeeder 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 templates seeder.');
            return;
        }

        $now = Carbon::now();
        
        $templates = [
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'title' => 'welcome_message',
                'channel' => 'whatsapp',
                'status' => 'approved',
                'category' => 'MARKETING',
                'langauge' => null,
                'created_at' => $now->copy()->subDays(70)->format('Y-m-d H:i:s'),
                'updated_at' => $now->copy()->subDays(65)->format('Y-m-d H:i:s'),
            ],
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'title' => 'summer_sale_announcement',
                'channel' => 'whatsapp',
                'status' => 'approved',
                'category' => 'MARKETING',
                'langauge' => null,
                'created_at' => $now->copy()->subDays(60)->format('Y-m-d H:i:s'),
                'updated_at' => $now->copy()->subDays(55)->format('Y-m-d H:i:s'),
            ],
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'title' => 'product_launch_notification',
                'channel' => 'telegram',
                'status' => 'pending',
                'category' => 'MARKETING',
                'langauge' => null,
                'created_at' => $now->copy()->subDays(20)->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' => 'feedback_request',
                'channel' => 'telegram',
                'status' => 'approved',
                'category' => 'MARKETING',
                'langauge' => null,
                'created_at' => $now->copy()->subDays(50)->format('Y-m-d H:i:s'),
                'updated_at' => $now->copy()->subDays(45)->format('Y-m-d H:i:s'),
            ],
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'title' => 'birthday_greeting',
                'channel' => 'whatsapp',
                'status' => 'pending',
                'category' => 'MARKETING',
                'langauge' => null,
                'created_at' => $now->copy()->subDays(15)->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' => 'discount_code_promo',
                'channel' => 'whatsapp',
                'status' => 'approved',
                'category' => 'MARKETING',
                'langauge' => null,
                'created_at' => $now->copy()->subDays(45)->format('Y-m-d H:i:s'),
                'updated_at' => $now->copy()->subDays(40)->format('Y-m-d H:i:s'),
            ],
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'title' => 'weekly_newsletter',
                'channel' => 'whatsapp',
                'status' => 'approved',
                'category' => 'MARKETING',
                'langauge' => null,
                'created_at' => $now->copy()->subDays(40)->format('Y-m-d H:i:s'),
                'updated_at' => $now->copy()->subDays(35)->format('Y-m-d H:i:s'),
            ],
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'title' => 'event_invitation',
                'channel' => 'telegram',
                'status' => 'pending',
                'category' => 'MARKETING',
                'langauge' => null,
                'created_at' => $now->copy()->subDays(12)->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',
                'channel' => 'whatsapp',
                'status' => 'approved',
                'category' => 'MARKETING',
                'langauge' => null,
                'created_at' => $now->copy()->subDays(30)->format('Y-m-d H:i:s'),
                'updated_at' => $now->copy()->subDays(25)->format('Y-m-d H:i:s'),
            ],
            [
                'unique_identifier' => Str::uuid()->toString(),
                'user_id' => $demoUser->id,
                'title' => 'holiday_greeting',
                'channel' => 'telegram',
                'status' => 'pending',
                'category' => 'MARKETING',
                'langauge' => null,
                'created_at' => $now->copy()->subDays(8)->format('Y-m-d H:i:s'),
                'updated_at' => $now->format('Y-m-d H:i:s'),
            ],
        ];

        // Upsert templates
        DB::table('templates')->upsert($templates, ['unique_identifier'], [
            'user_id', 'title', 'channel', 'status', 'category', 'langauge', 'updated_at'
        ]);

        // Create template metadata
        $templateMetas = [];
        foreach ($templates as $index => $template) {
            $templateId = DB::table('templates')->where('unique_identifier', $template['unique_identifier'])->value('id');
            
            if ($templateId) {
                // Language metadata
                $templateMetas[] = [
                    'owner_type' => 'Modules\MarketingBot\Entities\Template',
                    'owner_id' => $templateId,
                    'key' => 'language',
                    'value' => 'en',
                    'type' => 'string',
                    'created_at' => $now->format('Y-m-d H:i:s'),
                    'updated_at' => $now->format('Y-m-d H:i:s'),
                ];
                
                // For WhatsApp templates, add components, original_template_id, and parameter_format
                if ($template['channel'] === 'whatsapp') {
                    // Generate fake original_template_id (WhatsApp template ID format)
                    $originalTemplateId = $this->generateRandomNumberString(16);
                    
                    $templateMetas[] = [
                        'owner_type' => 'Modules\MarketingBot\Entities\Template',
                        'owner_id' => $templateId,
                        'key' => 'original_template_id',
                        'value' => $originalTemplateId,
                        'type' => 'string',
                        'created_at' => $now->format('Y-m-d H:i:s'),
                        'updated_at' => $now->format('Y-m-d H:i:s'),
                    ];
                    
                    $templateMetas[] = [
                        'owner_type' => 'Modules\MarketingBot\Entities\Template',
                        'owner_id' => $templateId,
                        'key' => 'parameter_format',
                        'value' => 'POSITIONAL',
                        'type' => 'string',
                        'created_at' => $now->format('Y-m-d H:i:s'),
                        'updated_at' => $now->format('Y-m-d H:i:s'),
                    ];
                    
                    // Add components based on template type
                    $components = $this->getTemplateComponents($template['title'], $index);
                    $templateMetas[] = [
                        'owner_type' => 'Modules\MarketingBot\Entities\Template',
                        'owner_id' => $templateId,
                        'key' => 'components',
                        'value' => json_encode($components),
                        'type' => 'string',
                        'created_at' => $now->format('Y-m-d H:i:s'),
                        'updated_at' => $now->format('Y-m-d H:i:s'),
                    ];
                }
            }
        }

        if (!empty($templateMetas)) {
            DB::table('template_metas')->upsert($templateMetas, ['owner_type', 'owner_id', 'key'], [
                'value', 'updated_at'
            ]);
        }
    }
    
    /**
     * Get template components based on template title
     */
    private function getTemplateComponents(string $title, int $index): array
    {
        $components = [];
        
        switch ($title) {
            case 'welcome_message':
                $components = [
                    [
                        'type' => 'HEADER',
                        'format' => 'TEXT',
                        'text' => 'Welcome to Our Service!'
                    ],
                    [
                        'type' => 'BODY',
                        'text' => 'Hello {{1}}! Welcome to our community. We\'re excited to have you here! Get started by exploring {{2}} and discover amazing features. Thank you for joining us!',
                        'example' => [
                            'body_text' => [
                                ['John', 'our platform']
                            ]
                        ]
                    ],
                    [
                        'type' => 'FOOTER',
                        'text' => 'We\'re here to help!'
                    ]
                ];
                break;
                
            case 'summer_sale_announcement':
                $components = [
                    [
                        'type' => 'HEADER',
                        'format' => 'TEXT',
                        'text' => '🔥 Summer Sale is Here!'
                    ],
                    [
                        'type' => 'BODY',
                        'text' => 'Hi {{1}}! Our biggest summer sale is live! Get up to {{2}} off on all products. Valid until {{3}}. Don\'t miss out! Shop now and save big!',
                        'example' => [
                            'body_text' => [
                                ['Sarah', '50%', 'July 31st']
                            ]
                        ]
                    ],
                    [
                        'type' => 'FOOTER',
                        'text' => 'Limited time offer'
                    ],
                    [
                        'type' => 'BUTTONS',
                        'buttons' => [
                            [
                                'type' => 'QUICK_REPLY',
                                'text' => 'Shop Now'
                            ],
                            [
                                'type' => 'URL',
                                'text' => 'View Deals',
                                'url' => 'https://example.com/sale/{{1}}',
                                'example' => ['summer2024']
                            ]
                        ]
                    ]
                ];
                break;
                
                
            case 'birthday_greeting':
                $components = [
                    [
                        'type' => 'HEADER',
                        'format' => 'TEXT',
                        'text' => '🎂 Happy Birthday!'
                    ],
                    [
                        'type' => 'BODY',
                        'text' => 'Happy Birthday {{1}}! We hope your special day is filled with joy and happiness! As a birthday gift, enjoy {{2}} off on your next purchase. Use code: {{3}} Wishing you a wonderful year ahead!',
                        'example' => [
                            'body_text' => [
                                ['David', '20%', 'BDAY2024']
                            ]
                        ]
                    ],
                    [
                        'type' => 'FOOTER',
                        'text' => 'Celebrate with us!'
                    ],
                    [
                        'type' => 'BUTTONS',
                        'buttons' => [
                            [
                                'type' => 'QUICK_REPLY',
                                'text' => 'Shop Now'
                            ]
                        ]
                    ]
                ];
                break;
                
            case 'discount_code_promo':
                $components = [
                    [
                        'type' => 'HEADER',
                        'format' => 'TEXT',
                        'text' => '🎁 Special Offer for You!'
                    ],
                    [
                        'type' => 'BODY',
                        'text' => 'Hi {{1}}, We have an exclusive offer just for you! Get {{2}} off on your next purchase. Use code: {{3}} Valid until {{4}}. Don\'t miss out!',
                        'example' => [
                            'body_text' => [
                                ['Lisa', '25%', 'SAVE25', 'December 31']
                            ]
                        ]
                    ],
                    [
                        'type' => 'FOOTER',
                        'text' => 'Limited time only'
                    ],
                    [
                        'type' => 'BUTTONS',
                        'buttons' => [
                            [
                                'type' => 'QUICK_REPLY',
                                'text' => 'Redeem Now'
                            ],
                            [
                                'type' => 'URL',
                                'text' => 'Shop',
                                'url' => 'https://example.com/shop?code={{1}}',
                                'example' => ['SAVE25']
                            ]
                        ]
                    ]
                ];
                break;
                
            case 'weekly_newsletter':
                $components = [
                    [
                        'type' => 'HEADER',
                        'format' => 'TEXT',
                        'text' => '📰 Weekly Newsletter'
                    ],
                    [
                        'type' => 'BODY',
                        'text' => 'Hello {{1}}, Here\'s your weekly update! Featured: {{2}} Tip of the week: {{3}} Don\'t miss: {{4}} Stay tuned for more updates next week!',
                        'example' => [
                            'body_text' => [
                                ['Robert', 'New Product Launch', 'Save energy with smart tips', 'Limited edition collection']
                            ]
                        ]
                    ],
                    [
                        'type' => 'FOOTER',
                        'text' => 'Subscribe to stay updated'
                    ],
                    [
                        'type' => 'BUTTONS',
                        'buttons' => [
                            [
                                'type' => 'QUICK_REPLY',
                                'text' => 'Read More'
                            ]
                        ]
                    ]
                ];
                break;
                
                
            case 'referral_program':
                $components = [
                    [
                        'type' => 'HEADER',
                        'format' => 'TEXT',
                        'text' => '🎁 Referral Program'
                    ],
                    [
                        'type' => 'BODY',
                        'text' => 'Hi {{1}}! Invite friends and earn rewards! For every friend you refer, you both get {{2}}. Your referral code: {{3}} Share with friends and start earning today!',
                        'example' => [
                            'body_text' => [
                                ['James', '$10 credit', 'REF-ABC123']
                            ]
                        ]
                    ],
                    [
                        'type' => 'FOOTER',
                        'text' => 'Refer and earn!'
                    ],
                    [
                        'type' => 'BUTTONS',
                        'buttons' => [
                            [
                                'type' => 'QUICK_REPLY',
                                'text' => 'Share Code'
                            ],
                            [
                                'type' => 'URL',
                                'text' => 'Refer Now',
                                'url' => 'https://example.com/refer/{{1}}',
                                'example' => ['REF-ABC123']
                            ]
                        ]
                    ]
                ];
                break;
                
                
            default:
                // Default simple template
                $components = [
                    [
                        'type' => 'BODY',
                        'text' => 'Hello {{1}}, This is a message about {{2}}. Thank you for your attention!',
                        'example' => [
                            'body_text' => [
                                ['Customer', 'our services']
                            ]
                        ]
                    ],
                    [
                        'type' => 'BUTTONS',
                        'buttons' => [
                            [
                                'type' => 'QUICK_REPLY',
                                'text' => 'Yes'
                            ],
                            [
                                'type' => 'QUICK_REPLY',
                                'text' => 'No'
                            ]
                        ]
                    ]
                ];
                break;
        }
        
        return $components;
    }
}

