<?php

namespace App\Http\Controllers\Admin;

use App\Country;
use App\Region;
use App\Http\Requests\RegionRequest;
use Exception;
use App\RegionDescription;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use PHPUnit\Framework\Constraint\Count;

class RegionController extends Controller
{

    /** Redirect to this path after each operation success*/
    private $redirectSuccessPath = '/admin/regions';
    /** View folder */
    private $viewDirectory = 'admin.regions.';

    /**
     * Display a listing of the resource.
     * @param Request $request
     * @return View
     */
    public function index(Request $request) :View
    {
        $title= __('regions.head');
        $request= $request->toArray();
        $countries = Country::withDescription();
        return view($this->viewDirectory.'index',compact('title', 'countries'));
    }

    /**
     * return data of the courses.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $language_id = currentLanguage()->id;
        $query = Region::join('region_descriptions AS region_desc', 'regions.id', 'region_desc.region_id')
            ->where('region_desc.language_id', $language_id)
            ->leftJoin('countries', 'countries.id', 'regions.country_id')
            ->leftJoin('country_descriptions AS country_desc', 'countries.id', 'country_desc.country_id')
            ->where('country_desc.language_id',$language_id)
            ->select(['region_desc.name', 'country_desc.name as country', 'country_desc.country_id', 'regions.*']);

        if ($request->date_from) {
            $query->whereDate('regions.created_at', '>=', $request->date_from);
        }

        if ($request->date_to) {
            $query->whereDate('regions.created_at', '<=', $request->date_to);
        }

        if ($request->name) {
            $query->where('region_desc.name', 'LIKE', '%'.$request->name.'%');
        }

        if ($request->country_id) {
            $query->where('country_desc.country_id', $request->country_id);
        }


        if ( !is_null($request->status) && $request->status == 0) {
            $query->onlyTrashed();
        }

        $regions= $query->paginate(100);

        return view($this->viewDirectory.'grid',compact('regions'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return View
     */
    public function create() :View
    {
        $action= route('regions.store');
        $head = metaFields('regions', 'add_new', getCurrentLocale()) ?? __('regions.new');
        $countries = Country::withDescription();
        return view( $this->viewDirectory.'form', compact('action', 'head', 'countries'));
    }

    /**
     * Store a newly created resource in storage.
     * @param RegionRequest $request
     * @return JsonResponse
     */
    public function store(RegionRequest $request)
    {
        $region = Region::create($request->all());
        $this->saveData( $request, $region->id );
        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }


    /**
     * Show the form for editing the specified resource.
     *
     * @param Region $region
     * @return View
     */
    public function edit(Region $region) :View
    {
        $action= route('regions.update', $region->id);
        $head = metaFields('regions', 'edit', getCurrentLocale()) ?? __('regions.edit');

        $query = RegionDescription::where('region_id', $region->id)
            ->join('languages', 'languages.id', 'region_descriptions.language_id')
            ->select(['region_descriptions.*', 'languages.local']);

        $regionDescription= $query->get();

        foreach ($regionDescription as $row) {
            $region[$row->local]= $row;
        }
        $countries = Country::withDescription();

        return view( $this->viewDirectory.'form', compact('region', 'action', 'head', 'countries'));
    }

    /**
     * Update the specified resource in storage.
     * @param RegionRequest $request
     * @param Region $region
     * @return JsonResponse
     */
    public function update(RegionRequest $request, Region $region)
    {
        $region->update($request->all());
        RegionDescription::where('region_id', $region->id)->delete();
        $this->saveData( $request, $region->id );
        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }


    /**
     * Handle Save form data
     *
     * @param RegionRequest $request
     * @param int $region_id
     * @return void
     */

    private function saveData(RegionRequest $request, int $region_id ):void
    {
        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data=[
                'region_id'=> $region_id,
                'language_id'=> $lang->id,
                'name'=> $requestData['name_'.$lang->local],
            ];
            RegionDescription::create($data);
        }

    }



    /**
     * Remove the specified resource from storage.
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     * @throws Exception
     */
    public function destroy(Request $request, int $id) :JsonResponse
    {
        $region = Region::withTrashed()->find($id);
        if ($region) {
            if ($region->deleted_at) {
                $region->forceDelete();
            } else {
                $region->delete();
            }
            return response()->json(['message'=> __('dashboard.deletedDone')]);
        } else{
            return response()->json(['message'=> __('dashboard.noResult')], 400);
        }
    }

    /**
     * Remove several courses by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;
        if ($request->force) {
            Region::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Region::whereIn('id', $ids)->delete();
        }

        return response()->json(['message'=> __('dashboard.deletedDone')]);
    }

    /**
     * Restore the specified category from storage
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function restore(Request $request, int $id) :JsonResponse
    {
        $region = Region::withTrashed()->find($id);

        if ($region){
            $region->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
        return response()->json(['message'=> __('dashboard.noResult')], 400);
    }

    /**
     * Restore several courses by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function restoreAll(Request $request) :JsonResponse
    {
        $regions = Region::whereIn('id', $request->ids)->onlyTrashed();
        if ($regions){
            $regions->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
    }
}
