<?php

namespace App\Http\Controllers\Admin;

use App\City;
use App\SectorDescription;
use App\Http\Requests\CityRequest;
use App\Http\Requests\SectorRequest;
use App\Region;
use App\Sector;
use Exception;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;

class SectorController extends Controller
{

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

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

    /**
     * return data of the courses.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $language_id = currentLanguage()->id;
        $query = Sector::join('sector_descriptions AS sector_desc', 'sectors.id', 'sector_desc.sector_id')
            ->where('sector_desc.language_id', $language_id)
            ->leftJoin('cities', 'cities.id', 'sectors.city_id')
            ->leftJoin('city_descriptions AS city_desc', 'cities.id', 'city_desc.city_id')
            ->where('city_desc.language_id',$language_id)
            ->select(['sector_desc.name', 'city_desc.name as city', 'city_desc.city_id', 'sectors.*']);

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

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

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

        if ($request->city_id) {
            $query->where('city_desc.city_id', $request->city_id);
        }


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

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

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

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

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


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

        $query = SectorDescription::where('sector_id', $sector->id)
            ->join('languages', 'languages.id', 'sector_descriptions.language_id')
            ->select(['sector_descriptions.*', 'languages.local']);

        $sectorDescription= $query->get();

        foreach ($sectorDescription as $row) {
            $sector[$row->local]= $row;
        }
        $cities = City::withDescription();

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

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


    /**
     * Handle Save form data
     *
     * @param CityRequest $request
     * @param int $sector_id
     * @return void
     */

    private function saveData(SectorRequest $request, int $sector_id ):void
    {
        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data=[
                'sector_id'=> $sector_id,
                'language_id'=> $lang->id,
                'name'=> $requestData['name_'.$lang->local],
            ];
            SectorDescription::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
    {
        $sector = Sector::withTrashed()->find($id);
        if ($sector) {
            if ($sector->deleted_at) {
                $sector->forceDelete();
            } else {
                $sector->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) {
            Sector::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Sector::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
    {
        $sector = Sector::withTrashed()->find($id);

        if ($sector){
            $sector->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
    {
        $sectors = Sector::whereIn('id', $request->ids)->onlyTrashed();
        if ($sectors){
            $sectors->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
    }
}
