<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\Vehicle;
use App\Models\PrepaidCard;

class VehicleSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $file = file_get_contents('database/seeders/data/vehicles-imported-2.json');
        $json = json_decode($file);


        Vehicle::create([
            'plate' => 'KBK87h',
            'profile_id' => 1, // Super User ID
            'vehicle_type_id' => 1,
            'vehicle_brand_id' => 46, // Mazda
            'year' => 2006,
            'color' => 'Negro',
        ]);

        $index = 0;
        $total = count($json);

        foreach ($json as $item) {
            $card = PrepaidCard::with('profile')->where('code', $item->prepaidCardCode)->first();
            if (!$card) {
                print(PHP_EOL.$item->prepaidCardCode . ' NOT FOUND, PLATE: '.$item->plate. PHP_EOL) ;
                continue;
            }

            $vehicle = Vehicle::create([
                'plate' => $item->plate,
                'profile_id' => $card->profile->id, // Temporal
                'vehicle_type_id' => intval($item->vehicleTypeId),
                'vehicle_brand_id' => 80, // Undefinde by default
                'year' => 1900, //Undefinde by default
                'color' => 'Por Definir'
            ]);

            $card->vehicles()->attach($vehicle);

            $this->printProgress($total, $index);
            $index++;
        }
    }

    private function printProgress($total, $index): void
    {
        // Print progress every $steps%
        $steps = 50;
        $ratio = 50;
        $progress = round($index * 100 * $ratio / $total);
        if ( $progress % $steps == 0 ) {
            print('....'. ($progress / $ratio) .'%');
        }
        if($total == ($index + 1)) {
            print(PHP_EOL. PHP_EOL. '      FINISHED!!' . PHP_EOL. PHP_EOL);

        }
    }
}
