<?php

namespace App\Http\Controllers\Admin;

use App\CompanyRequestTopic;
use App\CompanyRequestTopicDescription;
use App\Http\Requests\CompanyRequestTopicRequest;
use Exception;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;

class CompanyRequestTopicController extends Controller
{

    /** Redirect to this path after each operation success*/
    private $redirectSuccessPath = '/admin/companyRequestTopics';
    /** View folder */
    private $viewDirectory = 'admin.company_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= __('companyRequestTopics.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 = CompanyRequestTopic::orderByDesc('company_request_topics.id')
            ->join('company_request_topic_descriptions AS cDesc', 'company_request_topics.id', 'cDesc.company_request_topic_id')
            ->where('cDesc.language_id', currentLanguage()->id)
            ->select(['company_request_topics.*', 'cDesc.name']);;

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

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

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



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

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

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

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


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

        $query = CompanyRequestTopicDescription::where('company_request_topic_id', $companyRequestTopic->id)
            ->join('languages', 'languages.id', 'company_request_topic_descriptions.language_id')
            ->select(['company_request_topic_descriptions.*', 'languages.local']);

        $companyRequestTopicDescription= $query->get();

        foreach ($companyRequestTopicDescription as $row) {
            $companyRequestTopic[$row->local]= $row;
        }

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

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


    /**
     * Handle Save form data
     *
     * @param CompanyRequestTopicRequest $request
     * @param int $company_request_topic_id
     * @return void
     */

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

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