<?php

namespace Database\Seeders;

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

class UbigeoSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $this->runDataDefault();
        if (env('PROJECT_MODE', 'prod') === 'dev') {
            $this->runDataFake();
        }
    }

    public function runDataDefault() {
        $ubigeo_rute = './app/Resources/UbigeoChile.json';

        if(@file_get_contents($ubigeo_rute) === false){
            $ubigeo_rute = '/var/www/html/app/Resources/UbigeoChile.json';
        }

        $strUbigeo = file_get_contents($ubigeo_rute);
        $ubigeo = json_decode($strUbigeo);

        $this->command->info('UBIGEO CHILE :: INSERTING DATA ...');

        foreach ($ubigeo as $key => $region) {
            $this->command->info('UBIGEO CHILE :: INSERTING IN '. strtoupper($region->value) .' ...');
            $id_region = $this->setDepartment($region->key, $region->value,'1');

            foreach ($region->childrens as $key => $province) {
                $id_department = $this->setProvince($province->key, $province->value,$id_region);
                foreach ($province->childrens as $key => $comuna) {
                    $this->setDistrict($comuna->key, $comuna->value,$id_department);
                }
            }
        }
        
        $this->command->info('UBIGEO CHILE :: DATA INSERTION FINISH');
    }

    public function setDepartment($code,$name,$idpais){
        $department = new Department;
        $department->code = $code;
        $department->name = $name;
        $department->idcountry = $idpais;
        $department->idtimezone = 1;
        $department->save();

        return $department->id;
    }

    public function setProvince($code,$name,$iddepartment){
        $province = new Province;
        $province->code = $code;
        $province->name = $name;
        $province->iddepartment = $iddepartment;
        $province->save();

        return $province->id;
    }

    public function setDistrict($code,$name,$idprovince){
        $district = new District;
        $district->code = $code;
        $district->name = $name;
        $district->idprovince = $idprovince;
        $district->save();

        return $district->id;
    }

    public function runDataFake() {}
}
