<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class MstTown extends Model
{
    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 getData($pref_code=null, $city_code=null, $town_code=null) {
        $arrResult = [];
        if($pref_code !==null && $city_code !== null && $town_code !== null) {
            $towns = MstTown::where('pref_code', '=', $pref_code)
                            ->where('city_code', '=', $city_code)
                            ->where('code', '=', $town_code)
                            ->orderby('name2')->get();
            foreach($towns as $town){
                $arrResult[] = ['code' => $town->code, 'name' => $town->name];
            }
        } elseif($pref_code !==null && $city_code !== null){
            $towns = MstTown::where('pref_code', '=', $pref_code)
                             ->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 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;
    }

    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;
    }
}
