<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class MstSchool extends Model
{
    const CREATED_AT = null;
    const UPDATED_AT = null;
    
    //
    public static function getData() {
        $result = MstSchool::get();
        return $result;
    }

    public static function getAllId($type) {
        $res = MstSchool::select('code')->where('type', '=', $type)->get();
        return $res; 
    }

    public static function getSchoolName($idList) 
    {
        $q = MstSchool::query();
        $num = 0;
        $idList = $idList->toArray();
        foreach($idList as $id) {
            if($id != null) {
                if($num == 0) {
                    $q->where('code', '=', $id);
                    $num++;
                } else {
                    $q->orWhere('code', '=', $id);
                }
            }
        }
        $response = $q->select(['code', 'name'])->get();
        return $response;
    }

    public static function getSchoolByCode($code) 
    {
        $result = [];
        if(isset($code)) {
            $result = MstSchool::where('code', '=', $code)->first();
        }
        return $result;
    }

    public static function getSchoolByType($type, $companyId = null) 
    {
        $shools = MstSchool::where('type', '=', $type);

	if(!is_null($companyId)) {
            $shools->where('company_id', $companyId);
        }

        $shools = $shools->get();

        $arrResult = array();
        foreach($shools as $shool){
                $arrResult[] = ['code' => $shool->code, 'name' => $shool->name];
        }
        return $arrResult;    
    }

    public static function getPrimarySchoolByAddress($pref_id, $city_id) 
    {
        $shools = MstSchool::where('pref_id', '=', $pref_id)->where('city_id', '=', $city_id)->where('type', '=', 1)->get();

        $arrResult = array();
        foreach($shools as $shool){
                $arrResult[] = ['code' => $shool->code, 'name' => $shool->name];
        }
        return $arrResult;    
    }

    public static function getSecondarySchoolByAddress($pref_id, $city_id) 
    {
        $shools = MstSchool::where('pref_id', '=', $pref_id)->where('city_id', '=', $city_id)->where('type', '=', 2)->get();

        $arrResult = array();
        foreach($shools as $shool){
                $arrResult[] = ['code' => $shool->code, 'name' => $shool->name];
        }
        return $arrResult;    
    }

    public static function getCodeByName($name) 
    {
        $shools = MstSchool::where('name', 'like', '%'.$name.'%')->first();
        return $shools;    
    }

    public function scopeWithCompany($query)
    {
        $ownerCompany = auth()->user()->company_id;
        return $query->where("company_id", $ownerCompany);
    }

    public function scopeESchool($query)
    {
        return $query->where("type", 1);
    }

    public function scopeJSchool($query)
    {
        return $query->where("type", 2);
    }
}
