<?php

namespace App\Http\Controllers\Admin;

/** Ajax Request */

use App\City;
use App\Consulting;
use App\ConsultingDetail;
use App\Http\Requests\ConsultingRequest;
use App\Http\Requests\ServiceRequest;
use Exception;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;

/**
 * Class ConsultingController
 * Add Consultation appointments
 * @package App\Http\Controllers\Admin
 */
class ConsultingController extends Controller
{

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

    public function __construct()
    {
        $this->redirectSuccessPath = getCurrentLocale().$this->redirectSuccessPath;
    }

    /**
     * Display a listing of the consultings.
     *
     * @param Request $request
     * @return View
     */
    public function index(Request $request) :View
    {
        $title= __('consultings.head');
        $request= $request->toArray();
        return view($this->viewDirectory.'index',get_defined_vars());
    }

    /**
     * return data of the consultings.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $language_id = currentLanguage()->id;
        $query = Consulting::orderByDesc('consulting_date');

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

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

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

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

        if ($request->consulting_date) {
            $query->whereDate('consultings.consulting_date', '=', $request->consulting_date);
        }
        if ($request->consulting_time) {
            $query->where('consultings.consulting_time', '=', $request->consulting_time);
        }

        if ($request->consulting_status == 'active') {
            $query->whereStatus(1);
        }
        if ($request->consulting_status == 'not_active') {
            $query->whereStatus(0);
        }


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

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

    /**
     * Show the form for creating a new service.
     *
     * @return View
     */
    public function create() :View
    {
        $action= route('consultings.store');
        $head = metaFields('consultings', 'new', getCurrentLocale()) ?? __('consultings.new');
        $title = $head;
        return view( $this->viewDirectory.'form', get_defined_vars() );
    }

    /**
     * Store a newly created service in storage.
     * @param ConsultingRequest $request
     * @return JsonResponse
     */
    public function store(ConsultingRequest $request) :JsonResponse
    {
        $data = $request->all();
        $consulting = Consulting::firstWhere([
            'consulting_date' => $request->consulting_date,
            'consulting_time' => $request->consulting_time
        ]);

        if ($consulting){
            return response()->json(['errors' => __('consultings.consulting_date_time_added_before')]);
        }
        Consulting::create($data);
        session()->flash('message', __('dashboard.saveDone'));
        return response()->json(['url' => route('consultings.index')]);
//        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }

    /**
     * Show the form for editing the specified service.
     *
     * @param  Consulting  $consulting
     * @return View
     */
    public function edit(Consulting $consulting) :View
    {
        $action= route('consultings.update', $consulting->id);
        $head = metaFields('consultings', 'edit', getCurrentLocale()) ?? __('consultings.edit');
        $title = $head;
        return view( $this->viewDirectory.'form', get_defined_vars() );
    }


    public function activeConsulting(Consulting $consulting)
    {
        if ($consulting->status){
            $consulting->update(['status' => 0]);
            return response()->json(['message' => __('consultings.de_active_success')]);
        } else {
            $consulting->update(['status' => 1]);
            return response()->json(['message' => __('consultings.active_success')]);
        }

    }

    /**
     * Update the specified service in storage.
     * @param ConsultingRequest $request
     * @param Consulting $consulting
     * @return JsonResponse
     */
    public function update(ConsultingRequest $request, Consulting $consulting) :JsonResponse
    {
        $data = $request->all();
        $otherConsulting = Consulting::where('id', '!=', $consulting->id)
            ->firstWhere([
            'consulting_date' => $request->consulting_date,
            'consulting_time' => $request->consulting_time
        ]);

        if ($otherConsulting){
            return response()->json(['errors' => __('consultings.consulting_date_time_added_before')]);
        }

        $consulting->update($data);
        session()->flash('message', __('dashboard.saveDone'));
        return response()->json(['url' => route('consultings.index')]);
//        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }


    public function details()
    {
        $head =  __('consultings.page_details');
        $title = $head;
        $detail = ConsultingDetail::first();
//        $descriptions = ServiceDetailDescription::where('service_detail_id', $detail->id)
//            ->join('languages', 'languages.id', 'service_detail_descriptions.language_id')
//            ->select(['service_detail_descriptions.*', 'languages.local'])->get();
//
//        foreach ($descriptions as $description) {
//            $detail[$description->local] = $description;
//        }

        $action= route('consultings.updateDetails', $detail->id);

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

    public function updateDetails(ConsultingRequest $request, ConsultingDetail $consultingDetail)
    {
        $data = $request->all();
        $consultingDetail->update($data);
//        ServiceDetailDescription::where('service_detail_id', $serviceDetail->id)->delete();
//
//        foreach (languages() as $lang) {
//            $detailData=[
//                'service_detail_id'=> $serviceDetail->id,
//                'language_id'=> $lang->id,
//                'vision_title'=> $data['vision_title_'.$lang->local],
//                'mission_title'=> $data['mission_title_'.$lang->local],
//                'vision_description'=> $data['vision_description_'.$lang->local],
//                'mission_description'=> $data['mission_description_'.$lang->local],
//            ];
//            ServiceDetailDescription::create($detailData);
//        }

        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));


    }




    /**
     * Remove the specified service from storage.
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     * @throws Exception
     */
    public function destroy(Request $request, int $id) :JsonResponse
    {
        $consulting= Consulting::withTrashed()->find($id);
        if ($consulting) {

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

    /**
     * Remove several consultings by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;

        if ($request->force) {
            Consulting::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Consulting::whereIn('id', $ids)->delete();
        }

        return response()->json(['message'=> __('dashboard.deletedDone')]);
    }

    /**
     * Restore the specified service from storage.
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function restore(Request $request, int $id) :JsonResponse
    {
        $consulting= Consulting::withTrashed()->find($id);
        if ($consulting) {
            $consulting->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
        return response()->json(['message'=> __('dashboard.noResult')], 400);

    }

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