<?php

namespace App\Http\Controllers;

use App\Province;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;

class ProvincesController extends Controller
{
    public function index()
    {
        if(!Gate::allows('省份-查询')){ return redirect(url('/'));  }
        $provinces=Province::orderBy('id', 'DESC')->paginate(50);
        return view('maintenance.province.index',['provinces'=>$provinces]);
    }

    public function create()
    {
        if(!Gate::allows('省份-录入')){ return redirect(url('/'));  }
        return view('maintenance.province.create');
    }


    public function store(Request $request)
    {
        if(!Gate::allows('省份-录入')){ return redirect(url('/'));  }
        $id=false;
        $this->validatorProvinces($request,$id)->validate();
        $provinces=$request->input('Province');
        if(Province::create($provinces)){
            app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
            return redirect('maintenance/province')->with('successTip','新省份“'.$request->input('Province.name').'”添加成功');
        };
    }

    public function edit($id)
    {
        if(!Gate::allows('省份-编辑')){ return redirect(url('/'));  }
        $provinces=Province::find($id);
        return view('maintenance.province.edit',['province'=>$provinces]);
    }

    public function update(Request $request, $id)
    {
        if(!Gate::allows('省份-编辑')){ return redirect(url('/'));  }
        $this->validatorProvinces($request,$id)->validate();
        $data=$request->input('Province');
        $province=Province::find($id);
        $province->fill($data);
        if ($province->save()){
            app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
            return redirect('maintenance/province')->with('successTip','省份“'.$request->input('Province.name').'”修改成功');
        }
    }

    public function destroy($id)
    {
        if(!Gate::allows('省份-删除')){ return redirect(url('/'));  }
        $province=Province::find($id);
        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($province),Auth::user()['id']);
        $result=$province->delete();
        return ['success'=>$result];
    }

    protected function validatorProvinces(Request $request,$id){
        if ($id){$name=$id;}
        $validator=Validator::make($request->input(),[
            'Province.name'=>['required','max:50',isset($name)?"unique:provinces,name,$name":'unique:provinces,name'],
        ],[
            'required'=>':attribute 为必填项',
            'unique'=>':attribute 已存在',
        ],[
            'Province.name'=>'省份名称'
        ]);
        return $validator;
    }

    public function get(){
        $provinces = Province::query()->select("id","name")->get();
        return ["success"=>true,"data"=>$provinces];
    }
}
