<?php

namespace Database\Seeders;

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

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

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

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

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

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

            fclose($handle);
        }
    }
}
