<?php

namespace Database\Seeders;

use App\Models\City;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class CitySeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        City::truncate();

        $chunks = [];
        $time = now();
        if (($handle = fopen(resource_path('files/city.csv'), "r")) !== FALSE) {
            $firstline = true;
            while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
                if (!$firstline) {
                    $d = explode(';', $data[0]);

                    $row = [
                        "id" => $d[0],
                        "province_id" => $d[1],
                        "name" => ucwords(strtolower($d[2])),
                        "created_at" => $time,
                        "updated_at" => $time
                    ];

                    $chunks[] = $row;
                }
                $firstline = false;
                
                if ($chunks && count($chunks) == 100) {
                    City::insert($chunks);
                    $chunks = [];
                }
            }

            if ($chunks && count($chunks) > 0) {
                City::insert($chunks);
                $chunks = [];
            }

            fclose($handle);
        }
    }
}
