<?php

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Artisan;

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

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

// 1. Force Create Favorites Table if not exists
echo "Checking Favorites Table...\n";
if (!Schema::hasTable('favorites')) {
    echo "Creating favorites table via Schema builder...\n";
    Schema::create('favorites', function (Illuminate\Database\Schema\Blueprint $table) {
        $table->id();
        $table->foreignId('user_id')->constrained()->cascadeOnDelete();
        $table->foreignId('ad_id')->constrained()->cascadeOnDelete();
        $table->timestamps();
        $table->unique(['user_id', 'ad_id']);
    });
    echo "Favorites table created.\n";
} else {
    echo "Favorites table already exists.\n";
}

// 2. Mark Migration as Run
$favMigration = '2026_01_09_081152_create_favorites_table';
if (!DB::table('migrations')->where('migration', $favMigration)->exists()) {
    echo "Marking migration as run: $favMigration\n";
    DB::table('migrations')->insert([
        'migration' => $favMigration,
        'batch' => 99 // High batch number to indicate manual fix
    ]);
}

// 3. Mark User Plans fields migration as run if needed (avoiding that conflict too)
$plansMigration = '2026_01_09_074230_add_plan_fields_to_users_table';
if (!DB::table('migrations')->where('migration', $plansMigration)->exists()) {
     // Check if column exists first
    if (Schema::hasColumn('users', 'membership_type')) {
         echo "Marking plans migration as run (column exists): $plansMigration\n";
         DB::table('migrations')->insert(['migration' => $plansMigration, 'batch' => 99]);
    } else {
        // Here we might want to run it, but let's stick to favorites for now.
        // Actually, if this is missing, the code might break elsewhere.
        // Let's safe-add columns if missing.
        Schema::table('users', function ($table) {
            if (!Schema::hasColumn('users', 'membership_type')) {
                $table->string('membership_type')->nullable()->after('current_plan_id');
            }
            if (!Schema::hasColumn('users', 'plan_expires_at')) {
                 $table->dateTime('plan_expires_at')->nullable()->after('membership_type');
            }
        });
         DB::table('migrations')->insert(['migration' => $plansMigration, 'batch' => 99]);
    }
}


// 4. Create Test User Logic
echo "Creating Test User & Ads...\n";
$email = 'test@clxpro.com';
$password = 'password123';
$u = \App\Models\User::where('email', $email)->first();

if (!$u) {
    $u = \App\Models\User::create([
        'name' => 'Test User',
        'email' => $email,
        'password' => \Illuminate\Support\Facades\Hash::make($password),
        'role' => 'user',
        'email_verified_at' => now(),
    ]);
}

// Create Ads
$category = \App\Models\Category::first();
if (!$category) {
    $category = \App\Models\Category::create(['name' => 'Electronics', 'slug' => 'electronics', 'icon' => 'fa-laptop']);
}

// Delete existing to start fresh
\App\Models\Ad::where('user_id', $u->id)->delete();

$adsData = [
    ['title' => 'iPhone 15 Pro Max', 'price' => 1199, 'status' => 'Active', 'views' => 1200, 'favs' => 45],
    ['title' => 'Honda Civic 2022', 'price' => 22000, 'status' => 'Active', 'views' => 3400, 'favs' => 120],
    ['title' => 'Gaming PC RTX 4080', 'price' => 1800, 'status' => 'Pending', 'views' => 50, 'favs' => 12],
    ['title' => 'Sony A7III Camera', 'price' => 1400, 'status' => 'Inactive', 'views' => 890, 'favs' => 34],
    ['title' => 'MacBook Air M2', 'price' => 950, 'status' => 'Inactive', 'views' => 2100, 'favs' => 88],
];

foreach ($adsData as $idx => $d) {
    $ad = \App\Models\Ad::create([
        'user_id' => $u->id,
        'category_id' => $category->id,
        'title' => $d['title'],
        'description' => 'Great condition.',
        'price' => $d['price'],
        'currency' => 'USD',
        'status' => $d['status'],
        'view_count' => $d['views'],
        'location_city' => 'New York',
        'location_country' => 'USA',
        'slug' => 'test-ad-' . uniqid(),
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    // Image
    \App\Models\AdImage::create([
        'ad_id' => $ad->id,
        'image_url' => 'https://picsum.photos/400/300?random=' . ($idx + 1),
        'is_primary' => true,
        'order' => 0
    ]);
    
    // Favorites
    // Just inject valid favorites
    $dummyUsers = \App\Models\User::where('id', '!=', $u->id)->take($d['favs'])->pluck('id');
    foreach($dummyUsers as $uid) {
         DB::table('favorites')->insertOrIgnore([
            'user_id' => $uid,
            'ad_id' => $ad->id,
            'created_at' => now(),
            'updated_at' => now()
        ]);
    }
    
    echo "Created {$d['title']} ({$d['status']}) with {$d['favs']} favs.\n";
}

