<?php

namespace Database\Seeders;

use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class ParkingSeeder extends Seeder
{
    public function run(): void
    {
        DB::disableQueryLog();
        Model::unsetEventDispatcher();

        $chunkSize = 100;
        $tableName = 'parkings';
        $now = CarbonImmutable::now();
        $startDate = $now->subMonths(12);

        $memberIds = DB::table('members')
            ->where('member_type', 1)
            ->pluck('id')
            ->toArray();

        if (empty($memberIds)) {
            $this->command->warn('No Full Access members found. Run MemberSeeder first.');
            return;
        }

        $makes = ['Toyota', 'Honda', 'Nissan', 'Mercedes', 'BMW', 'Lexus', 'Ford', 'Chevrolet', 'Hyundai', 'Kia'];
        $models = ['Camry', 'Accord', 'Altima', 'C-Class', '3 Series', 'F-150', 'Cruze', 'Sonata', 'Optima', 'Corolla'];
        $colors = ['White', 'Black', 'Silver', 'Gray', 'Red', 'Blue', 'Green'];

        $rows = [];
        $totalCars = 0;
        $qrBase = 1000000;

        foreach ($memberIds as $memberId) {
            $carsPerMember = rand(0, 2);
            if ($carsPerMember === 0 && $totalCars < 300) {
                $carsPerMember = 1;
            }
            for ($c = 0; $c < $carsPerMember; $c++) {
                $createdAt = CarbonImmutable::createFromTimestamp(
                    rand($startDate->timestamp, $now->timestamp)
                )->setTime(12, 0, 0)->format('Y-m-d H:i:s');

                $plateNum = str_pad((($memberId * 100 + $totalCars) % 9000) + 1000, 4, '0', STR_PAD_LEFT);
                $regions = ['1', '2', '3', '4', '6', '10', '11'];
                $carNumber = 'أ ب ج ' . $plateNum . ' ' . $regions[$memberId % count($regions)];

                $make = $makes[array_rand($makes)];
                $model = $models[array_rand($models)];

                $rows[] = [
                    'member_id'   => $memberId,
                    'car_number'  => $carNumber,
                    'make'        => $make,
                    'model'       => $model,
                    'color'       => $colors[array_rand($colors)],
                    'qr_code'     => 'PC-' . ($qrBase + $totalCars),
                    'status'      => 1,
                    'created_at'  => $createdAt,
                    'updated_at'  => $createdAt,
                ];
                $totalCars++;

                if (count($rows) >= $chunkSize) {
                    DB::table($tableName)->insert($rows);
                    $rows = [];
                }
            }
        }

        if (!empty($rows)) {
            DB::table($tableName)->insert($rows);
        }

        $this->command->info("Parkings seeded: {$totalCars} records");
    }
}
