<?php

namespace App\Http\Controllers\Admin;

use App\CaseTopic;
use App\CaseTopicDescription;
use App\Http\Requests\CaseTopicRequest;
use Exception;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;

class CaseTopicController extends Controller
{

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


    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= __('caseTopics.head');
        $request= $request->toArray();
        return view($this->viewDirectory.'index', get_defined_vars());
    }

    /**
     * return data of the courses.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = CaseTopic::orderByDesc('case_topics.id')
            ->join('case_topic_descriptions AS cDesc', 'case_topics.id', 'cDesc.case_topic_id')
            ->where('cDesc.language_id', currentLanguage()->id)
            ->select(['case_topics.*', 'cDesc.name']);;

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

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

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



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

        $caseTopics= $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('caseTopics.store');
        $head = metaFields('caseTopics', 'new', getCurrentLocale()) ?? __('caseTopics.new');
        $title = $head;

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

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


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

        $query = CaseTopicDescription::where('case_topic_id', $caseTopic->id)
            ->join('languages', 'languages.id', 'case_topic_descriptions.language_id')
            ->select(['case_topic_descriptions.*', 'languages.local']);

        $documentation_typeDescription= $query->get();

        foreach ($documentation_typeDescription as $row) {
            $caseTopic[$row->local]= $row;
        }

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

    /**
     * Update the specified resource in storage.
     * @param CaseTopicRequest $request
     * @param CaseTopic $caseTopic
     * @return JsonResponse
     */
    public function update(CaseTopicRequest $request, CaseTopic $caseTopic)
    {
        $caseTopic->touch();
        // Delete old description
        CaseTopicDescription::where('case_topic_id', $caseTopic->id)->delete();
        $this->saveData( $request, $caseTopic->id );
        session()->flash('message', __('dashboard.saveDone'));
        return  response()->json(['url' => route('caseTopics.index')]);
//        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }


    /**
     * Handle Save form data
     *
     * @param CaseTopicRequest $request
     * @param int $case_topic_id
     * @return void
     */

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

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