<?php

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

require __DIR__.'/vendor/autoload.php';

$app = require_once __DIR__.'/bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$kernel->bootstrap();

echo "--- Starting Visual Demo Seeder ---\n";

// 1. Clear existing Ads
echo "Clearing old ads...\n";
DB::statement('SET FOREIGN_KEY_CHECKS=0;');
AdImage::truncate();
Ad::truncate();
// We won't truncate users to preserve admin, but we will create/update our demo users
DB::statement('SET FOREIGN_KEY_CHECKS=1;');

// 2. Define Users & Plans
$usersData = [
    [
        'name' => 'Demo Standard', 
        'email' => 'standard@demo.com', 
        'plan' => 'Standard', // Will update user_plan logic ideally, or just set a flag if simple
        'tier' => 'Standard' 
    ],
    [
        'name' => 'Demo VIP Buyer', 
        'email' => 'buyer@demo.com', 
        'plan' => 'VIP Buyer',
        'tier' => 'VIP Buyer'
    ],
    [
        'name' => 'Demo VIP Seller', 
        'email' => 'seller@demo.com', 
        'plan' => 'VIP Seller',
        'tier' => 'VIP Seller'
    ],
    [
        'name' => 'Demo VIP Pro', 
        'email' => 'pro@demo.com', 
        'plan' => 'VIP Pro',
        'tier' => 'VIP Pro'
    ],
];

// Helper to get random category
// Removed parent_id check as it caused SQL error
$categories = Category::inRandomOrder()->limit(5)->get();

if ($categories->count() == 0) {
    echo "Error: No categories found. Creating dummy category...\n";
    $cat = new Category();
    $cat->name = 'Demo Category';
    $cat->slug = 'demo-cat';
    $cat->icon = 'fa-tag';
    $cat->save();
    $categories = collect([$cat]);
}

$images = [
    'https://images.unsplash.com/photo-1542282088-fe8426682b8f', // Car
    'https://images.unsplash.com/photo-1581091226825-a6a2a5aee158', // Laptop
    'https://images.unsplash.com/photo-1568605114967-8130f3a36994', // House
    'https://images.unsplash.com/photo-1552519507-da3b142c6e3d', // Car 2
    'https://images.unsplash.com/photo-1593640408182-31c70c8268f5', // PC
    'https://images.unsplash.com/photo-1600607687939-ce8a6c25118c', // Modern House
];

foreach ($usersData as $uData) {
    echo "Processing User: {$uData['name']}...\n";
    
    $user = User::firstOrCreate(
        ['email' => $uData['email']],
        [
            'name' => $uData['name'],
            'password' => Hash::make('password'),
            'role' => 'user',
            // Assuming we might have a field for plan or we rely on the helper method logic 
            // In the app code, 'userTier' on Ad model comes from relationship.
            // For now, let's assume we can mock it or the app logic derives it.
            // If there's a specific column 'current_plan_id', we'd update it.
        ]
    );

    // MOCKING: If the app calculates tier dynamicallly, we need to assign a real plan. 
    // Since we don't know the exact plan IDs, we will update the created_at or verify DB structure later.
    // For now, we will manually force the Ad 'user_tier' if the ad table has it, or rely on the App's joining logic.
    // **CRITICAL**: The Flutter App's Ad model has `userTier`. Check if it comes from API.
    // Assuming API transforms User->plan->name to ad->userTier.
    
    // Create 3 Ads for this user: Normal, Featured, Boosted
    $types = ['Normal', 'Featured', 'Boosted'];
    
    foreach ($types as $type) {
        $cat = $categories->random();
        
        $ad = new Ad();
        $ad->user_id = $user->id;
        $ad->title = "{$uData['tier']} - $type Ad - {$cat->name}";
        $ad->description = "This is a demonstration ad for the {$uData['tier']} plan with $type features. Located in Bangalore.";
        $ad->price = rand(500, 50000);
        $ad->category_id = $cat->id;
        $ad->subcategory_id = null; // Simplify
        $ad->status = 'active';
        
        // Location
        $ad->country = 'India';
        $ad->state = 'Karnataka';
        $ad->city = 'Bangalore';
        $ad->area = 'Indiranagar'; // Popular area
        $ad->latitude = 12.9716;
        $ad->longitude = 77.5946;
        
        // Features
        $ad->is_featured = ($type === 'Featured') ? 1 : 0;
        $ad->is_boosted = ($type === 'Boosted') ? 1 : 0;
        
        // Mocking the tier for the API response if it's stored on Ad (denormalized)
        // If your system logic uses a join, ensure the user has the plan.
        // I will attempt to set a 'user_tier_name' if such column exists, otherwise standard logic applies.
        
        $ad->save();
        
        // Images (5 per ad)
        for ($i = 0; $i < 5; $i++) {
            AdImage::create([
                'ad_id' => $ad->id,
                'image_path' => $images[rand(0, count($images) - 1)],
                'is_primary' => ($i === 0) ? 1 : 0
            ]);
        }
    }
}

// 3. SPECIAL STEP: Force Assign Plans in DB (if Plan table exists)
// This is a guess-attempt to associate the plan if tables exist
try {
    $plans = DB::table('plans')->get();
    foreach ($usersData as $uData) {
        $user = User::where('email', $uData['email'])->first();
        // Find matching plan
        $plan = $plans->filter(function($p) use ($uData) { 
            return stripos($p->name, $uData['tier']) !== false || stripos($p->name, $uData['plan']) !== false; 
        })->first();
        
        if ($plan && $user) {
            // Update User Plan relationship (assuming 'user_plans' table or 'plan_id' column)
            // Trying common patterns:
            // Pattern A: plan_id on user
            // Pattern B: subscription table
            
            // Check if user has plan_id
            // DB::table('users')->where('id', $user->id)->update(['plan_id' => $plan->id]); e.g.
            
            // Create subscription record
            DB::table('user_plans')->updateOrInsert(
                ['user_id' => $user->id],
                [
                    'plan_id' => $plan->id,
                    'status' => 'active',
                    'start_date' => Carbon::now(),
                    'end_date' => Carbon::now()->addYear(),
                    'created_at' => Carbon::now(),
                    'updated_at' => Carbon::now()
                ]
            );
            echo "Assigned Plan {$plan->name} to {$user->name}\n";
        }
    }
} catch (\Exception $e) {
    echo "Note: Could not auto-assign plans via DB table (might not exist): " . $e->getMessage() . "\n";
}

echo "--- Seed Visual Demo Complete ---\n";
?>
