<?php

namespace App\Http\Controllers\Admin;

use App\Doctor;
use App\Conference;
use Exception;
use App\Language;
use App\ConferenceDescription;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Requests\ConferenceRequest;
use App\Http\Controllers\Controller;

class ConferenceController extends Controller
{

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

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

    /**
     * return data of the conferences.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Conference::latest()
            ->join('conference_descriptions AS sDesc', 'conferences.id', 'sDesc.conference_id')
            ->where('sDesc.language_id', currentLanguage()->id)
            ->select(['sDesc.title', 'conferences.*']);

        if ($request->start_date) {
            $query->whereDate('conferences.start_date', '=', $request->start_date);
        }

        if ($request->end_date) {
            $query->whereDate('conferences.end_date', '=', $request->end_date);
        }

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

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

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

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

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

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

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


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

        $query = ConferenceDescription::where('conference_id', $conference->id)
            ->join('languages', 'languages.id', 'conference_descriptions.language_id')
            ->select(['conference_descriptions.*', 'languages.local']);

        $conferenceDescription= $query->get();

        foreach ($conferenceDescription as $row) {
            $conference[$row->local]= $row;
        }

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

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

        // Delete old description
        ConferenceDescription::where('conference_id', $conference->id)->delete();

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

    /**
     * Handle Save form data
     *
     * @param ConferenceRequest $request
     * @param int $conference_id
     * @return void
     */

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

        foreach ($languages as $lang) {
            $data=[
                'conference_id'=> $conference_id,
                'language_id'=> $lang->id,
                'title'=> $requestData['title_'.$lang->local],
                'description'=> $requestData['description_'.$lang->local],
            ];
            ConferenceDescription::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
    {
        if (1 == $id) {
            return response()->json(['message'=> __('dashboard.noResult')], 400);
        }

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

    /**
     * Remove several conferences by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;
        if ( in_array( 1, $ids) ) {
            return response()->json(['message'=> __('dashboard.noResult')], 400);
        }

        if ($request->force) {
            Conference::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Conference::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
    {
        $conference = Conference::withTrashed()->find($id);

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

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