<?php

namespace App\Http\Controllers\AdminPanel;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Area\AreaRequest;
use App\Http\Traits\ToasterTrait;
use App\Models\Area;
use App\Models\Country;
use App\Repositries\MainRepository;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;

class AreaController extends Controller implements HasMiddleware
{
    use ToasterTrait;
    public  $areaRepository, $area, $countries, $country;
    public function __construct(MainRepository $areaRepository, Area $area, Country $country)
    {
        $this->areaRepository = $areaRepository;
        $this->area           = $area->with(['country', 'city']);
        $this->country        = $country;
        $this->countries      = $this->areaRepository->index($this->country);
    }

    public static function middleware()
    {
        return [
            new Middleware('permission:view areas', only: ['index']),
            new Middleware('permission:create areas', only: ['create', 'store']),
            new Middleware('permission:update areas', only: ['edit', 'update']),
            new Middleware('permission:delete areas', only: ['destroy']),
        ];
    }
    public function index()
    {
        $areas = $this->areaRepository->index($this->area);
        return view('AdminPanel.areas.index', get_defined_vars());
    }

    public function create()
    {
        $countries = $this->countries;
        return view('AdminPanel.areas.create', get_defined_vars());
    }

    public function store(AreaRequest $request)
    {
        $this->areaRepository->create($this->area, $request->validated());
        $this->success(__('lang.created'));
        return redirect()->route('areas.index');
    }

    public function edit(string $id)
    {
        $area           = $this->areaRepository->show($this->area, $id);
        $countries      = $this->countries;
        return view('AdminPanel.areas.edit', get_defined_vars());
    }

    public function update(AreaRequest $request, string $id)
    {
        $this->areaRepository->update($this->area, $id, $request->validated());
        $this->success(__('lang.updated'));
        return redirect()->route('areas.index');
    }

    public function destroy(string $id)
    {
        $this->areaRepository->destroy($this->area, $id);
        $this->success(__('lang.deleted'));
        return redirect()->route('areas.index');
    }
}
