<?php

namespace App\Http\Controllers;

use App\Events\ChatMessage;
use App\Http\Helpers\FileUploader;
use App\Models\Chat;
use App\Models\Engineer;
use App\Models\Firm;
use App\Models\Message;
use App\Models\Project;
use App\Models\Service;
use App\Models\User;
use App\Traits\ZoomJWT;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;

class ChatController extends Controller
{
    use ZoomJWT;

    const MEETING_TYPE_INSTANT = 1;
    const MEETING_TYPE_SCHEDULE = 2;
    const MEETING_TYPE_RECURRING = 3;
    const MEETING_TYPE_FIXED_RECURRING_FIXED = 8;
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function startChat(Request $request)
    {

        $request->validate([
            'message' => 'required',
            'project' =>'bool|required',
        ]);

        $chatable = null;
        $worker_type = null;
        $worker_id = null;

        if ($request->project) {
            $chatable = Project::find($request->chatable_id);
            $worker_type = $request->worker_type;
            $worker_id = $request->worker_id;
        } else {
            $chatable = Service::find($request->chatable_id);
            $worker_type = $chatable->serviceable_type;
            $worker_id = $chatable->serviceable_id;
        }

        $chatable_type = get_class($chatable);


        $chat = [
            'user_id' => Auth::user()->id,
            'chatable_id' => $chatable->id,
            'chatable_type' => $chatable_type,
            'worker_id' => $worker_id,
            "worker_type" => $worker_type,
            'last_message_at'=>now(),
        ];
        $chatModel= Chat::where('user_id',$chat['user_id'])
            ->where('chatable_id',$chat['chatable_id'])
            ->where('chatable_type',$chat['chatable_type'])
            ->where('worker_id',$chat['worker_id'],)
            ->where('worker_type',$chat['worker_type'])->get()?->first()
        ;
        if($chatModel==null){
            $chatModel = Chat::create($chat);
        }

        if($chatModel->messages()->count() == 0){

            $message = [
                'message' => $request->message['text'],
                'chat_id' => $chatModel->id,
                'sender' => $request->project ?'user':'worker',
                'sender_uid' => Auth::user()->id,
            ];
            // if($request->message->hasFile('attachment')){
            //     $message['attachment']= FileUploader::store('chats/'.$chatModel->id .'/',$request->message->attachment);
            // }
            $messageModel = Message::create($message);

            event(new ChatMessage($messageModel));

        }
        return Redirect::route('client.chat', ['chat' => $chatModel->id]);
    }
    public function startChatFromWorker(Request $request)
    {

        $request->validate([
            'message' => 'required',
            'project' =>'bool|required',
            'user_id' => 'required|exists:users,id',
        ]);

        $chatable = null;
        $worker_type = null;
        $worker_id = null;



        if ($request->project) {
            $chatable = Project::find($request->chatable_id);

            $worker_type = $request->worker_type??Auth::user()->is_engineer?'App\\Models\\Engineer':'App\\Models\\Firm';
            $worker_id = $request->worker_id??Auth::user()->is_engineer?Auth::user()->engineer?->id:Auth::user()->firm?->id;
        } else {
            $chatable = Service::find($request->chatable_id);
            $worker_type = $chatable->serviceable_type;
            $worker_id = $chatable->serviceable_id;
        }

        $chatable_type = get_class($chatable);


        $chat = [
            'user_id' => $request->user_id,
            'chatable_id' => $chatable->id,
            'chatable_type' => $chatable_type,
            'worker_id' => $worker_id,
            "worker_type" => $worker_type,
            'last_message_at'=>now(),
        ];
        $chatModel= Chat::where('user_id',$chat['user_id'])
            ->where('chatable_id',$chat['chatable_id'])
            ->where('chatable_type',$chat['chatable_type'])
            ->where('worker_id',$chat['worker_id'],)
            ->where('worker_type',$chat['worker_type'])->get()?->first()
        ;
        if($chatModel==null){
            $chatModel = Chat::create($chat);
        }

        if($chatModel->messages()->count() == 0){

            $message = [
                'message' => $request->message['text'],
                'chat_id' => $chatModel->id,
                'sender' => $request->project ?'user':'worker',
                'sender_uid' => Auth::user()->id,
            ];
            // if($request->message->hasFile('attachment')){
            //     $message['attachment']= FileUploader::store('chats/'.$chatModel->id .'/',$request->message->attachment);
            // }
            $messageModel = Message::create($message);

            event(new ChatMessage($messageModel));

        }
        return Redirect::route($worker_type == 'App\\Models\\Engineer' ? 'engineer.chat' : 'firm.chat', ['chat' => $chatModel->id]);
    }

    /**
     * Send chat message
     * @param $request
     * @return void
     */
    public function sendMessage(Request $request)
    {
        $message = [
            'message' => $request->message['text'],
            'chat_id' => $request->chat_id,
            'sender_uid' => Auth::user()->id,
            'sender' => $request->is,
        ];

        if($request->message['attachment']){
            // dd($request->all());

            try {
                $message['attachment']= FileUploader::store('chats/'.$request->chat_id .'/',$request->message['attachment']);
            } catch (\Throwable $th) {
                return back(303)->with('error', 'Error uploading file');
            }
        }

        $message = Message::create($message);

        $message->chat->update(['last_message_at' => now()]);

        //TODO:: send mail if user not active
        event(new ChatMessage($message));

        return back(303);
    }


    public function createZoomLink(Request $request){
        $chat = Chat::find($request->chat_id);
        // check if the chat has a zoom meeting created in the past 30 minutes
        $lastMeeting = $chat->messages()->where('attachment', 'like', '%zoom.us%')->where('created_at', '>', now()->subMinutes(0))->orderBy('created_at', 'desc')->first();

        if(!$lastMeeting)
        {
//           dd( $this->zoomPatch(
//                '/users/'.$chat->worker->email,[
//                    'type'=>2
//                ]
//            )->body());
            if($this->zoomGet('/users/'.$chat->worker->email)->status()==404){
                $this->zoomPost('users',[
                    'action'=>'custCreate',
                    'user_info'=>[
                        'email'=>$chat->worker->email,
                        'display_name'=>$chat->worker->name,
                        'type'=>1,
                    ]
                ]);
            }
            if($this->zoomGet('/users/'.$chat->user->email)->status()==404){
                $this->zoomPost('users',[
                    'action'=>'custCreate',
                    'user_info'=>[
                        'email'=>$chat->user->email,
                        'display_name'=>$chat->user->name,
                        'type'=>1,
                    ]
                ]);
            }
            $path = 'users/'. Auth::user()->email .'/meetings';
            $response = $this->zoomPost($path, [
                'type' => self::MEETING_TYPE_INSTANT,
                'settings' => [
                    'allow_multiple_devices' => true,
//                    'alternative_hosts'=> $chat->user->email,
                    'host_video' => true,
                    'participant_video' => true,
                    'waiting_room' => true,
                    'join_before_host' => true,
                    'authentication_exception'=> [
                        [
                            'email'=>$chat->user->email,
                            'name'=>$chat->user->name,
                        ],
                        [
                            'email'=>$chat->worker->email,
                            'name'=>$chat->worker->name,
                        ],
                    ],
                ]
            ]);
//            dd($response,$response->body(),$response->json());
        }

        // compose a message to send, if the meeting was created in the past 30 minutes, send the link to the meeting
        // else send a message that the meeting was not created
        if($lastMeeting)
        {
            $message = [
                'message' => 'We already had a zoom meeting recently, click the link to join' ,
                'chat_id' => $request->chat_id,
                'sender_uid' => Auth::user()->id,
                'sender' => $request->is,
                'attachment' => $lastMeeting->attachment,
            ];
        }
        else
        {
            $message = [
                'message' => 'I created us a zoom new meeting, click the link to join and here is the password => '. $response->json()['password'],
                'chat_id' => $request->chat_id,
                'sender_uid' => Auth::user()->id,
                'sender' => $request->is,
                'attachment' => $response->json()['start_url'],
            ];
        }


        $message = Message::create($message);

        $message->chat->update(['last_message_at' => now()]);

        //TODO:: send mail if user not active
        event(new ChatMessage($message));
        return back(303);
    }


}
