<?php

namespace App\Http\Controllers\Admin;

use App\Service;
use App\Career;
use Exception;
use App\Language;
use App\CareerDescription;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Requests\CareerRequest;
use App\Http\Controllers\Controller;

class CareerController extends Controller
{

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

    public function __construct()
    {
        $this->redirectSuccessPath = getCurrentLocale().$this->redirectSuccessPath;
    }

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

    /**
     * return data of the careers.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $langId = currentLanguage()->id;
        $query = Career::orderByDesc('careers.id')
            ->join('career_descriptions AS cDesc', 'careers.id', 'cDesc.career_id')
            ->where('cDesc.language_id', $langId)
//            ->join('services', 'careers.service_id', 'services.id')
//            ->join('service_descriptions AS sDesc', 'services.id', 'sDesc.service_id')
//            ->where('sDesc.language_id', $langId)
            ->select(['cDesc.name', 'careers.*']);

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

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

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

//        if ($request->service_id) {
//            $query->where('careers.service_id',$request->service_id);
//        }

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

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

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

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

    /**
     * Store a newly created resource in storage.
     *
     * @param CareerRequest $request
     * @return JsonResponse
     */
    public function store(CareerRequest $request) :JsonResponse
    {
        $career = Career::create($request->all());
        // Insert Description
        $this->saveData( $request, $career->id );
        session()->flash('message', __('dashboard.saveDone'));
        return response()->json(['url' => route('careers.index')]);
//        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }


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

        $query = CareerDescription::where('career_id', $career->id)
            ->join('languages', 'languages.id', 'career_descriptions.language_id')
            ->select(['career_descriptions.*', 'languages.local']);

        $careerDescription= $query->get();

        foreach ($careerDescription as $row) {
            $career[$row->local]= $row;
        }

        $services = Service::withDescription();

        return view( $this->viewDirectory.'form', get_defined_vars());
    }

    /**
     * Update the specified resource in storage.
     *
     * @param CareerRequest $request
     * @param Career $career
     * @return JsonResponse
     */
    public function update(CareerRequest $request, Career $career) : JsonResponse
    {
        // Update image if request has it
        $career->update($request->all());

        // Delete old description
        CareerDescription::where('career_id', $career->id)->delete();

        // Insert new description
        $this->saveData( $request, $career->id );
        session()->flash('message', __('dashboard.saveDone'));
        return response()->json(['url' => route('careers.index')]);
//        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }

    /**
     * Handle Save form data
     *
     * @param CareerRequest $request
     * @param int $career_id
     * @return void
     */

    private function saveData(CareerRequest $request, int $career_id ):void
    {
        $requestData= $request->all();
        $languages= Language::where('status', 1)->cursor();

        foreach ($languages as $lang) {
            $data=[
                'name'=> $requestData['name_'.$lang->local],
                'description'=> $requestData['description_'.$lang->local],
                'type'=> $requestData['type_'.$lang->local],
                'career_id'=> $career_id,
                'language_id'=> $lang->id,
            ];
            CareerDescription::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
    {

        $career = Career::withTrashed()->find($id);
        if ($career) {
            if ($career->deleted_at) {
                $career->forceDelete();
            } else {
                $career->delete();
            }
            return response()->json(['message'=> __('dashboard.deletedDone')]);
        } else{
            return response()->json(['message'=> __('dashboard.noResult')], 400);
        }
    }

    /**
     * Remove several careers by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;
        if ($request->force) {
            Career::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Career::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
    {
        $career = Career::withTrashed()->find($id);

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

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