<?php

namespace App\Http\Controllers\Admin;

use App\Doctor;
use Exception;
use App\Language;
use App\DoctorDescription;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Requests\DoctorRequest;
use App\Http\Controllers\Controller;

class DoctorController extends Controller
{

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

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

    /**
     * return data of the doctors.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Doctor::latest()
            ->join('doctor_descriptions AS dDesc', 'doctors.id', 'dDesc.doctor_id')
            ->where('dDesc.language_id', currentLanguage()->id)
            ->select(['dDesc.name', 'dDesc.specialist', 'doctors.*']);

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

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

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

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

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

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

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

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


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

        $query = DoctorDescription::where('doctor_id', $doctor->id)
            ->join('languages', 'languages.id', 'doctor_descriptions.language_id')
            ->select(['doctor_descriptions.*', 'languages.local']);

        $doctorDescription= $query->get();

        foreach ($doctorDescription as $row) {
            $doctor[$row->local]= $row;
        }

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

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

        // Delete old description
        DoctorDescription::where('doctor_id', $doctor->id)->delete();

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

    /**
     * Handle Save form data
     *
     * @param DoctorRequest $request
     * @param int $doctor_id
     * @return void
     */

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

        foreach ($languages as $lang) {
            $data=[
                'doctor_id'=> $doctor_id,
                'language_id'=> $lang->id,
                'name'=> $requestData['name_'.$lang->local],
                'specialist'=> $requestData['specialist_'.$lang->local],
                'certifications'=> $requestData['certifications_'.$lang->local],
                'trainings'=> $requestData['trainings_'.$lang->local],
                'experiences'=> $requestData['experiences_'.$lang->local],
                'researches'=> $requestData['researches_'.$lang->local],
                'professional_memberships'=> $requestData['professional_memberships_'.$lang->local],
            ];
            DoctorDescription::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);
        }

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

    /**
     * Remove several doctors 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) {
            Doctor::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Doctor::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
    {
        $doctor = Doctor::withTrashed()->find($id);

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

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