<?php

namespace Database\Seeders;

use App\Models\Province;
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

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

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

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

                    if ($row['name'] == 'Dki Jakarta') {
                        $row['name'] = 'DKI Jakarta';
                    }

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

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

            fclose($handle);
        }
    }
}
