<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\User;
use App\Models\Ad;
use App\Models\Category;
use App\Models\AdImage;
use Illuminate\Support\Facades\Hash;
use Carbon\Carbon;

class BangaloreDemoSeeder extends Seeder
{
    public function run(): void
    {
        $this->command->info('🚀 Starting Bangalore Demo Data Seeding...');

        // 1. Create Bangalore Users
        $users = [
            ['name' => 'Aarav Sharma', 'email' => 'aarav.sharma@demo.com', 'mobile' => '+919876500001'],
            ['name' => 'Diya Menon', 'email' => 'diya.menon@demo.com', 'mobile' => '+919876500002'],
            ['name' => 'Rohan Patil', 'email' => 'rohan.patil@demo.com', 'mobile' => '+919876500003'],
            ['name' => 'Ananya Gupta', 'email' => 'ananya.gupta@demo.com', 'mobile' => '+919876500004'],
            ['name' => 'Karthik Reddy', 'email' => 'karthik.reddy@demo.com', 'mobile' => '+919876500005'],
            ['name' => 'Sanya Verma', 'email' => 'sanya.verma@demo.com', 'mobile' => '+919876500006'],
            ['name' => 'Vikram Malhotra', 'email' => 'vikram.m@demo.com', 'mobile' => '+919876500007'],
            ['name' => 'Isha Kapoor', 'email' => 'isha.k@demo.com', 'mobile' => '+919876500008'],
        ];

        $createdUsers = [];
        foreach ($users as $userData) {
            $createdUsers[] = User::firstOrCreate(
                ['email' => $userData['email']],
                [
                    'name' => $userData['name'],
                    'password' => Hash::make('password123'),
                    'mobile_number' => $userData['mobile'],
                    'city' => 'Bangalore',
                    'state' => 'Karnataka',
                    'country' => 'India',
                    'email_verified_at' => now(),
                    'is_verified' => true, // Make them verified for trust
                ]
            );
        }

        $this->command->info('✅ Created/Found ' . count($createdUsers) . ' Bangalore Users.');

        // 2. Fetch Categories
        $cats = Category::pluck('id', 'name')->toArray();
        // Fallbacks if names match approximately
        $electronicsId = $cats['Electronics'] ?? Category::where('name', 'LIKE', '%Electronic%')->value('id');
        $vehiclesId = $cats['Vehicles'] ?? Category::where('name', 'LIKE', '%Vehicle%')->value('id');
        $propertiesId = $cats['Real Estate'] ?? $cats['Properties'] ?? Category::where('name', 'LIKE', '%Estate%')->value('id');
        $furnitureId = $cats['Furniture'] ?? Category::where('name', 'LIKE', '%Furniture%')->value('id');
        $fashionId = $cats['Fashion'] ?? Category::where('name', 'LIKE', '%Fashion%')->value('id');

        // 3. Define Ads Data (Bangalore specific areas)
        $areas = ['Koramangala', 'Indiranagar', 'Whitefield', 'HSR Layout', 'Jayanagar', 'Marathahalli', 'Electronic City'];
        
        $adsData = [
            [
                'title' => 'iPhone 15 Pro Max - 256GB Natural Titanium',
                'price' => 135000,
                'cat_id' => $electronicsId,
                'desc' => 'Brand new sealed pack Indian unit with bill and warranty.',
                'images' => [
                    'https://images.unsplash.com/photo-1695048133142-1a20484d2569?auto=format&fit=crop&q=80&w=800',
                    'https://images.unsplash.com/photo-1696446701796-da61225697cc?auto=format&fit=crop&q=80&w=800',
                    'https://images.unsplash.com/photo-1678685888221-cda773a3dcdb?auto=format&fit=crop&q=80&w=800'
                ]
            ],
            [
                'title' => 'MacBook Air M2 Midnight',
                'price' => 85000,
                'cat_id' => $electronicsId,
                'desc' => 'Barely used, 2 months old. 8GB/256GB configuration with box.',
                'images' => [
                    'https://images.unsplash.com/photo-1660833638050-41f95d8b94e6?auto=format&fit=crop&q=80&w=800',
                    'https://images.unsplash.com/photo-1611186871348-b1ce696e52c9?auto=format&fit=crop&q=80&w=800',
                    'https://images.unsplash.com/photo-1541807084-5c52b6b3bd99?auto=format&fit=crop&q=80&w=800'
                ]
            ],
            [
                'title' => 'Sony PlayStation 5 User',
                'price' => 45000,
                'cat_id' => $electronicsId,
                'desc' => 'PS5 Disc edition with 2 controllers and God of War Ragnarok.',
                'images' => [
                    'https://images.unsplash.com/photo-1606144042614-b2417e99c4e3?auto=format&fit=crop&q=80&w=800',
                    'https://images.unsplash.com/photo-1607853202273-797f1c22a38e?auto=format&fit=crop&q=80&w=800'
                ]
            ],
            [
                'title' => 'Royal Enfield Meteor 350 Fireball',
                'price' => 190000,
                'cat_id' => $vehiclesId,
                'desc' => '2022 Model, 5000km driven. Showroom condition. Single owner.',
                'images' => [
                    'https://images.unsplash.com/photo-1625043484555-47841a754388?auto=format&fit=crop&q=80&w=800',
                    'https://images.unsplash.com/photo-1558981403-c5f9899a28bc?auto=format&fit=crop&q=80&w=800'
                ]
            ],
            [
                'title' => 'Honda City ZX CVT 2021',
                'price' => 1250000,
                'cat_id' => $vehiclesId,
                'desc' => 'Top model automatic. Sunroof, leather seats, 25k driven. Service records available.',
                'images' => [
                    'https://images.unsplash.com/photo-1590362891991-f776e747a588?auto=format&fit=crop&q=80&w=800',
                    'https://images.unsplash.com/photo-1549317661-bd32c8ce0db2?auto=format&fit=crop&q=80&w=800',
                    'https://images.unsplash.com/photo-1533473359331-0135ef1b58bf?auto=format&fit=crop&q=80&w=800'
                ]
            ],
            [
                'title' => 'Modern 3BHK Flat in Whitefield',
                'price' => 12500000,
                'cat_id' => $propertiesId,
                'desc' => '1800 sqft apartment in gated society with pool, gym, and club house.',
                'images' => [
                    'https://images.unsplash.com/photo-1560448204-e02f11c3d0e2?auto=format&fit=crop&q=80&w=800',
                    'https://images.unsplash.com/photo-1512917774080-9991f1c4c750?auto=format&fit=crop&q=80&w=800',
                    'https://images.unsplash.com/photo-1560185127-6a6a45b89245?auto=format&fit=crop&q=80&w=800'
                ]
            ],
            [
                'title' => 'Office Space for Rent in Indiranagar',
                'price' => 85000,
                'cat_id' => $propertiesId,
                'desc' => 'Fully furnished plug and play office, 15 seats capacity.',
                'images' => [
                    'https://images.unsplash.com/photo-1497366216548-37526070297c?auto=format&fit=crop&q=80&w=800',
                    'https://images.unsplash.com/photo-1524758631624-e2822e304c36?auto=format&fit=crop&q=80&w=800'
                ]
            ],
            [
                'title' => 'L-Shape Fabric Sofa Set',
                'price' => 28000,
                'cat_id' => $furnitureId,
                'desc' => 'Grey color, very comfortable. 2 years old but clean.',
                'images' => [
                    'https://images.unsplash.com/photo-1555041469-a586c61ea9bc?auto=format&fit=crop&q=80&w=800',
                    'https://images.unsplash.com/photo-1556228453-efd6c1ff04f6?auto=format&fit=crop&q=80&w=800'
                ]
            ],
            [
                'title' => 'Solid Wood Dining Table (6 Seater)',
                'price' => 35000,
                'cat_id' => $furnitureId,
                'desc' => 'Sheesham wood table with 6 cushioned chairs. Excellent condition.',
                'images' => [
                    'https://images.unsplash.com/photo-1617806118233-18e1de247200?auto=format&fit=crop&q=80&w=800',
                    'https://images.unsplash.com/photo-1615873968403-89e068629265?auto=format&fit=crop&q=80&w=800'
                ]
            ],
            [
                'title' => 'Nike Air Jordan 1 High',
                'price' => 12000,
                'cat_id' => $fashionId,
                'desc' => 'Size UK 9. Worn twice. Original box available.',
                'images' => [
                    'https://images.unsplash.com/photo-1549298916-b41d501d3772?auto=format&fit=crop&q=80&w=800',
                    'https://images.unsplash.com/photo-1560769629-975ec94e6a86?auto=format&fit=crop&q=80&w=800'
                ]
            ]
        ];

        $this->command->info('📸 Adding Ads with multiple images...');

        foreach ($adsData as $index => $data) {
            // Find category
            if (!$data['cat_id']) continue;

            $user = $createdUsers[$index % count($createdUsers)];
            $area = $areas[$index % count($areas)];
            
            // Random Coordinates around Bangalore (12.9716 N, 77.5946 E)
            // Variation approx 0.05 degrees for diverse map locations
            $lat = 12.9716 + (mt_rand(-500, 500) / 10000); 
            $lng = 77.5946 + (mt_rand(-500, 500) / 10000);

            $ad = Ad::create([
                'user_id' => $user->id,
                'category_id' => $data['cat_id'],
                'title' => $data['title'],
                'description' => $data['desc'],
                'price' => $data['price'],
                'currency' => 'INR',
                'city' => 'Bangalore', // Legacy
                'state' => 'Karnataka', // Legacy
                'location_city' => 'Bangalore',
                'location_state' => 'Karnataka',
                'location_country' => 'India',
                'location_address' => $area . ', Bangalore',
                'location_latitude' => $lat,
                'location_longitude' => $lng,
                'latitude' => $lat,
                'longitude' => $lng,
                'status' => 'Active',
                'is_featured' => ($index % 3 == 0), // Every 3rd ad is featured
                'created_at' => Carbon::now()->subDays(rand(1, 15)),
            ]);

            // Add Images
            foreach ($data['images'] as $key => $imgUrl) {
                AdImage::create([
                    'ad_id' => $ad->id,
                    'image_url' => $imgUrl,
                    'is_primary' => ($key === 0),
                ]);
            }
        }
        
        $this->command->info('🎉 Seeding Complete! Added ' . count($adsData) . ' ads with multiple images to Bangalore users.');
    }
}
