<?php

namespace App\Http\Controllers\Admin;

/** Ajax Request */

use App\ConsultingRequest;
use App\Helpers\ZoomHelper;
use App\Http\Requests\ActiveConsultingRequest;
use App\UsersNotification;
use Exception;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use MacsiDigital\Zoom\Facades\Zoom;

class ActiveConsultingController extends Controller
{

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

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

    /**
     * return data of the activeConsultings.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = ConsultingRequest::orderByDesc('id')->whereIn('status', ['active', 'not_active']);

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

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

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

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

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

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

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

        $activeConsultings= $query->paginate(100);

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


    /**
     * Show the form for editing the specified service.
     *
     * @param ConsultingRequest $activeConsulting
     * @return Factory|RedirectResponse|View
     */
    public function edit(ConsultingRequest $activeConsulting)
    {
        if ($activeConsulting->status != 'active'){
            return redirect()->route('activeConsultings.index');
        }
        $action= route('activeConsultings.update', $activeConsulting->id);
        $head = metaFields('activeConsultings', 'edit', getCurrentLocale()) ?? __('activeConsultings.edit');
        $local = getCurrentLocale();
        return view( $this->viewDirectory.'form', get_defined_vars() );
    }


    public function consultationStatus(Request $request, ConsultingRequest $activeConsulting)
    {

        if ($request->ajax()){

            if (!$activeConsulting){
                return response()->json(['message' => __('activeConsultings.consultaongs_not_found')]);
            }

            if (in_array($activeConsulting->consulting_way, ['phone', 'office']) && $activeConsulting->status == 'active'){
                $activeConsulting->update(['status' => 'finished']);
                return response()->json([
                    'message' => __('activeConsultings.consulting_finished_success'),
                    'status' => 'finished',
                ]);
            }

            if ($activeConsulting->consulting_way == 'zoom' && $activeConsulting->status == 'not_active'){
//                $topic = __('activeConsultings.consulting_zoom_meeting').
//                    __('activeConsultings.'.$activeConsulting->consulting_type);
                $topic = $activeConsulting->consulting_subject;
               $meeting = ZoomHelper::createMeeting($topic);
               if(!$meeting->id){
                   return response()->json(['errors' => __('activeConsultings.error_in_zoom')]);
               }

                $activeConsulting->update([
                    'zoom_meeting_id' => $meeting->id,
                    'zoom_user_url' => $meeting->join_url,
                    'zoom_host_url' => $meeting->start_url,
                    'status' => 'active'
                ]);

               UsersNotification::create([
                   'title' => __('activeConsultings.zoom_consulting'),
                   'message' => $topic,
                   'user_id' => $activeConsulting->user_id,
                   'is_read' => [],
               ]);

                return response()->json([
                    'message' => __('activeConsultings.consulting_start_success'),
                    'status' => 'active',
                    'zoom_link' => $activeConsulting->zoom_host_url,
                ]);

            }

            if ($activeConsulting->consulting_way == 'zoom' && $activeConsulting->status == 'active'){
                $meetingDeleted = ZoomHelper::deleteMeeting($activeConsulting->zoom_meeting_id);
                $activeConsulting->update([
                    'zoom_meeting_id' => null,
                    'zoom_user_url' => null,
                    'zoom_host_url' => null,
                    'status' => 'finished',
                ]);

                if (!$meetingDeleted){
                    return response()->json([
                        'message' => __('activeConsultings.consulting_finished_success_zoom_error'),
                        'status' => 'finished',
                    ]);
                }

                return response()->json([
                    'message' => __('activeConsultings.consulting_finished_success'),
                    'status' => 'finished',
                ]);
            }
        }
    }

    /**
     * Update the specified service in storage.
     * @param ConsultingRequest $request
     * @param ConsultingRequest $activeConsulting
     * @return JsonResponse
     */


    public function update(ActiveConsultingRequest $request, ConsultingRequest $activeConsulting) :JsonResponse
    {
        $data = $request->all();
        $activeConsulting->update($data);
        session()->flash('message', __('dashboard.saveDone'));
        return response()->json(['url' => route('activeConsultings.index')]);
//        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= ConsultingRequest::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 activeConsultings by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;

        if ($request->force) {
            ConsultingRequest::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            ConsultingRequest::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= ConsultingRequest::withTrashed()->find($id);
        if ($consulting) {
            $consulting->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
        return response()->json(['message'=> __('dashboard.noResult')], 400);

    }

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