<?php

namespace Database\Seeders;

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


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

        $index = 0;
        $total = count($json);
        foreach ($json as $item) {
            $card = PrepaidCard::where('code', $item->cardCode)->first();
            if (!$card){
                print(PHP_EOL . "Card ".$item->cardCode . ' NOT REGISTERED'. PHP_EOL);
                continue;
            }
            $vehicle = Vehicle::where('plate', $item->plate)->first();
            if (!$vehicle){
                print(PHP_EOL . "Plate ". $item->plate . ' NOT REGISTERED'. PHP_EOL);
                continue;
            }

            Ansapass::create([
                'code' => $item->stickerCode,
                'vehicle_id' => $vehicle->id,
                'prepaid_card_id' => $card->id,
            ]);

            $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);

        }
    }
}
