<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\User;
use App\Models\Brand;
use App\Models\Proposal;
use App\Models\Campaign;
use App\Models\MessageThread;
use App\Models\Message;
use App\Models\MarketplaceShortlist;

class MarketplaceDemoSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // Get all tenants
        $tenants = \App\Models\Tenant::all();
        
        foreach ($tenants as $tenant) {
            // Get the brand for this tenant
            $brand = Brand::where('tenant_id', $tenant->id)->first();
            
            if (!$brand) {
                continue;
            }
            
            // Get creators for this tenant
            $creators = User::where('tenant_id', $tenant->id)
                ->whereHas('roles', function ($q) {
                    $q->where('name', 'creator');
                })
                ->get();
                
            // Get brand admins for this tenant
            $brandAdmins = User::where('tenant_id', $tenant->id)
                ->whereHas('roles', function ($q) {
                    $q->where('name', 'brand_admin');
                })
                ->get();
                
            if ($creators->isEmpty() || $brandAdmins->isEmpty()) {
                continue;
            }
            
            // Update creators with influencer types
            $influencerTypes = [
                'Lifestyle', 'Tech', 'Gaming', 'Beauty', 'Fitness', 
                'Travel', 'Food', 'Education', 'Business', 
                'Entertainment', 'Sports', 'Other'
            ];
            
            foreach ($creators as $index => $creator) {
                $creator->update([
                    'influencer_type' => $influencerTypes[$index % count($influencerTypes)],
                    'influencer_type_custom' => null
                ]);
            }
            
            // Create sample proposals
            $proposalTypes = ['Collaboration', 'Sponsored Post', 'Affiliate', 'Long-term Partnership'];
            
            foreach ($brandAdmins as $admin) {
                // Create 3 proposals from brand to creators
                for ($i = 0; $i < 3; $i++) {
                    $creator = $creators->random();
                    
                    Proposal::firstOrCreate([
                        'brand_id' => $brand->id,
                        'creator_id' => $creator->id,
                        'title' => $tenant->name . ' Proposal ' . ($i + 1),
                    ], [
                        'message' => 'We would like to propose a collaboration with your brand. This is a sample proposal for demonstration purposes.',
                        'type' => $proposalTypes[array_rand($proposalTypes)],
                        'budget' => rand(100, 10000),
                        'duration' => rand(1, 12) . ' months',
                        'deliverables' => json_encode([
                            rand(1, 5) . ' Instagram posts',
                            rand(1, 3) . ' YouTube videos',
                            rand(2, 10) . ' Stories'
                        ]),
                        'status' => ['sent', 'accepted', 'rejected'][array_rand(['sent', 'accepted', 'rejected'])],
                    ]);
                }
            }
            
            // Create sample campaigns
            $campaignStatuses = ['draft', 'active', 'paused', 'completed', 'cancelled'];
            
            // Get an agency for this tenant
           $agency = User::where('tenant_id', $tenant->id)
               ->whereHas('roles', function ($q) {
                   $q->where('name', 'agency_admin');
               })
               ->first();
           
           foreach ($brandAdmins as $admin) {
               // Create 2 campaigns
               for ($i = 0; $i < 2; $i++) {
                   $campaign = Campaign::firstOrCreate([
                       'brand_id' => $brand->id,
                       'name' => $tenant->name . ' Campaign ' . ($i + 1),
                   ], [
                       'agency_id' => $agency ? $agency->id : $admin->id, // Use agency if available, otherwise use admin
                       'description' => 'This is a sample campaign for demonstration purposes. It showcases how brands can create and manage campaigns.',
                       'objective' => 'Increase brand awareness and engagement',
                       'budget' => rand(5000, 50000),
                       'currency' => 'USD',
                       'start_date' => now()->addDays(rand(1, 30)),
                       'end_date' => now()->addDays(rand(60, 120)),
                       'status' => $campaignStatuses[array_rand($campaignStatuses)],
                       'created_by' => $admin->id,
                   ]);
                    
                    // Attach random creators to the campaign
                    $campaignCreators = $creators->random(rand(2, min(3, $creators->count())));
                    foreach ($campaignCreators as $creator) {
                        $campaign->creators()->syncWithoutDetaching([
                            $creator->id => [
                                'invited_by' => $admin->id,
                                'status' => ['invited', 'accepted', 'declined'][array_rand(['invited', 'accepted', 'declined'])],
                                'invitation_sent_at' => now()->subDays(rand(1, 10)),
                                'responded_at' => now()->subDays(rand(1, 5)),
                            ]
                        ]);
                    }
                }
            }
            
            // Create sample shortlists
            foreach ($brandAdmins as $admin) {
                // Create 2 shortlists
                for ($i = 0; $i < 2; $i++) {
                    $shortlist = MarketplaceShortlist::firstOrCreate([
                        'brand_id' => $brand->id,
                        'name' => $tenant->name . ' Shortlist ' . ($i + 1),
                    ], [
                        'description' => 'This is a sample shortlist for demonstration purposes.',
                        'is_public' => false,
                        'created_by' => $admin->id,
                    ]);
                    
                    // Add random creators to the shortlist
                    $shortlistCreators = $creators->random(rand(2, min(3, $creators->count())));
                    foreach ($shortlistCreators as $creator) {
                        $shortlist->creators()->syncWithoutDetaching([
                            $creator->id => [
                                'added_by' => $admin->id,
                            ]
                        ]);
                    }
                }
            }
            
            // Create sample messages
            foreach ($brandAdmins as $admin) {
                // Create message threads between brand admin and creators
                foreach ($creators as $creator) {
                    // Create a message thread
                    $thread = MessageThread::firstOrCreate([
                        'subject' => $tenant->name . ' Discussion - ' . $creator->name,
                    ]);
                    
                    // Add participants
                    $thread->participants()->firstOrCreate([
                        'user_id' => $admin->id,
                    ], [
                        'is_read' => false,
                        'joined_at' => now(),
                    ]);
                    
                    $thread->participants()->firstOrCreate([
                        'user_id' => $creator->id,
                    ], [
                        'is_read' => false,
                        'joined_at' => now(),
                    ]);
                    
                    // Create sample messages
                    $messages = [
                        'Hi ' . $creator->name . ', I wanted to discuss a potential collaboration opportunity.',
                        'Hello! I\'m interested in learning more about this opportunity. Could you provide more details?',
                        'Sure! We\'re looking for a social media campaign focused on our new product launch.',
                        'That sounds interesting. What are the deliverables and timeline?',
                        'We\'re looking for 5 Instagram posts and 2 YouTube videos over the next 3 months.',
                        'Great! I\'d be happy to work on this. Let me know the next steps.'
                    ];
                    
                    foreach ($messages as $index => $messageText) {
                        $sender = ($index % 2 == 0) ? $admin : $creator;
                        $recipient = ($index % 2 == 0) ? $creator : $admin;
                        
                        Message::create([
                            'sender_id' => $sender->id,
                            'recipient_id' => $recipient->id,
                            'subject' => $thread->subject,
                            'message' => $messageText,
                            'thread_id' => $thread->id,
                            'is_read' => false,
                        ]);
                    }
                    
                    // Update thread timestamp
                    $thread->updated_at = now();
                    $thread->save();
                }
            }
        }
    }
}