<?php

namespace Database\Seeders;

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

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

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

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

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

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

            fclose($handle);
        }
    }
}
