<?php

namespace App\Models;

use Illuminate\Support\Facades\Auth;
use App\Utils;
use Illuminate\Database\Eloquent\Model;

class ContractAllowableCity extends Model
{
    const CREATED_AT = 'created_at';
    const UPDATED_AT = 'updated_at';
    const PERPAGE = 50;

    protected $table = 'contract_allowable_city';
    protected $primaryKey = 'contract_allowable_city_id';

    protected $fillable = [
        'city_id',
        'contract_allowable_city_name',
        'park_id',
        'same_district_flag',
        'operator_id'
    ];

    /**
     * 一覧検索・ソート処理
     */
    public static function search($inputs)
    {
        $list = self::query()
            ->leftJoin('park', 'contract_allowable_city.park_id', '=', 'park.park_id')
            ->leftJoin('city', 'contract_allowable_city.city_id', '=', 'city.city_id')
            ->select(
                'contract_allowable_city.*',
                'park.park_name',
                'city.city_name'
            );

        if ($inputs['isMethodPost'] ?? false) {
            if (!empty($inputs['contract_allowable_city_id'])) {
                $list->where('contract_allowable_city.contract_allowable_city_id', $inputs['contract_allowable_city_id']);
            }
            if (!empty($inputs['city_id'])) {
                $list->where('contract_allowable_city.city_id', $inputs['city_id']);
            }
            if (!empty($inputs['contract_allowable_city_name'])) {
                $list->where('contract_allowable_city.contract_allowable_city_name', 'like', '%' . $inputs['contract_allowable_city_name'] . '%');
            }
            if (!empty($inputs['park_id'])) {
                $list->where('contract_allowable_city.park_id', $inputs['park_id']);
            }
        }

        // 並び順
        if (!empty($inputs['sort'])) {
            $list->orderBy($inputs['sort'], $inputs['sort_type'] ?? 'asc');
        }

        if ($inputs['isExport'] ?? false) {
            return $list->get();
        } else {
            return $list->paginate(Utils::item_per_page);
        }
    }


    /**
     * 主キーで取得
     */
    public static function getByPk($pk)
    {
        return self::find($pk);
    }

    /**
     * 主キー配列で一括削除
     */
    public static function deleteByPk($arr)
    {
        return self::whereIn('contract_allowable_city_id', $arr)->delete();
    }

    /**
     * 選択リスト取得用（フォーム等）
     */
    public static function getList()
    {
        return self::pluck('contract_allowable_city_name', 'contract_allowable_city_id');
    }
}
