<?php

namespace App\Http\Controllers\Admin;

use App\OtherRequestTopic;
use App\OtherRequestTopicDescription;
use App\Http\Requests\OtherRequestTypeRequest;
use Exception;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;

class OtherRequestTopicController extends Controller
{

    /** Redirect to this path after each operation success*/
    private $redirectSuccessPath = '/admin/otherRequestTopics';
    /** View folder */
    private $viewDirectory = 'admin.other_request_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= __('otherRequestTopics.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 = OtherRequestTopic::orderByDesc('other_request_topics.id')
            ->join('other_request_topic_descriptions AS cDesc', 'other_request_topics.id', 'cDesc.other_request_topic_id')
            ->where('cDesc.language_id', currentLanguage()->id)
            ->select(['other_request_topics.*', 'cDesc.name']);;

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

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

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



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

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

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

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


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

        $query = OtherRequestTopicDescription::where('other_request_topic_id', $otherRequestTopic->id)
            ->join('languages', 'languages.id', 'other_request_topic_descriptions.language_id')
            ->select(['other_request_topic_descriptions.*', 'languages.local']);

        $otherRequestTopicDescription= $query->get();

        foreach ($otherRequestTopicDescription as $row) {
            $otherRequestTopic[$row->local]= $row;
        }

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

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


    /**
     * Handle Save form data
     *
     * @param OtherRequestTypeRequest $request
     * @param int $other_request_topic_id
     * @return void
     */

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

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