<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use \App\Models\traits\SetConnection;

class MstTown extends Model
{
    const CREATED_AT = null;
    const UPDATED_AT = null;

    use SetConnection;

    protected $guarded = [];

    public static function getName($prefCode=null, $cityCode=null, $townCode=null)
    {
        $city_name = "";
        if($prefCode != null && $cityCode != null){
            $city_name = MstTown::select('name')->where('pref_code', '=', $prefCode)->where('city_code', '=', $cityCode)->where('code', '=', $townCode)->first();
        }
        return $city_name;
    }

    public static function getByCityCode($city_code){
        $towns = MstTown::where('city_code', '=', $city_code)
            ->orderby('name2')
            ->orderby('code')
            ->get();
        foreach($towns as $town){
            $arrResult[] = ['code' => $town->code, 'name' => $town->name];
        }
        return $arrResult ?? [];
    }

    public static function getData($pref_code=null, $city_code=null, $town_code=null) {
        $arrResult = [];
        if($pref_code !==null && $city_code !== null && $town_code !== null) {
            $query = MstTown::where('pref_code', '=', $pref_code)
                            ->where('city_code', '=', $city_code)
                            ->where('code', '=', $town_code);
        } elseif($pref_code !==null && $city_code !== null){
            $query = MstTown::where('pref_code', '=', $pref_code)
                             ->where('city_code', '=', $city_code);
        }
        $towns = [];
        if (isset($query)){
            if (auth()->user() && auth()->user()->company_id == 1) {
                $query->orderBy('name2')->orderBy('id');
            } else {
                $query->orderBy('code');
            }
            $towns = $query->get();
        }
        foreach($towns as $town){
            $arrResult[] = ['code' => $town->code, 'name' => $town->name.$town->chome_name.$town->koaza_name];
        }
        return $arrResult;
    }

    public static function getDataByAddress($address) {
        if($address != "") {
            $address = mb_convert_kana($address, 'n');
            $pattern = array("/1/", "/2/", "/3/", "/4/", "/5/", "/6/", "/7/", "/8/", "/9/", "/0/");
            $replace = array('一', '二', '三', '四', '五', '六', '七', '八', '九', '０');
            $address_kann = preg_replace($pattern, $replace, $address);

            $town = MstTown::where('name', '=', $address)
            ->orwhere('name', '=', $address_kann)
            ->get();
            return $town;
        }

        return [];
    }

    function toKansuuji($string) {
        $pattern = array("/1/", "/2/", "/3/", "/4/", "/5/", "/6/", "/7/", "/8/", "/9/", "/0/");
        $replace=array('一', '二', '三', '四', '五', '六', '七', '八', '九', '０');
        $result=preg_replace($pattern, $replace, $string);
        return $result;
    }
}
