<?php

namespace App\Http\Controllers;

use App\Components\AsyncResponse;
use App\Region;
use Illuminate\Support\Facades\Gate;

class RegionController extends Controller
{
    use AsyncResponse;
    public function get()
    {
        $type = request("type");
        $regions = Region::query();
        if ($type)$regions->where("type",$type);
        $this->success($regions->get());
    }

    public function index()
    {
        if(!Gate::allows("地域"))return view("exception.authority");
        $regions = Region::withTrashed()->get();
        return view("maintenance.region.index",compact("regions"));
    }

    public function store()
    {
        $parent = request("parent_id");
        $type = request("type");
        if (!$type)$this->error("非法参数");

        $name = app("RegionService")->formatName(request("name"),$type);
        if (!$name)$this->error("非法参数");

        $region = Region::withTrashed()->where("name",$name)->where("type",$type)->first();
        if ($region)$this->error("已经存在，无需重复录入");
        $this->success(Region::query()->create([
            "name" => $name,
            "type" => $type,
            "parent_id" => $parent
        ]));
    }

    public function getProvinces()
    {
        $this->success(app("RegionService")->getSelection(1));
    }
}
