<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request; 
use App\Http\Controllers\Controller; 
use App\Models\UserRejectRequest;
// use App\Models\Message;
use App\Models\User;
use App\Models\MessageThread;
use App\Models\BuyerRequest;
use App\Models\SellerRequest;

class MessageController extends Controller {
    
    public function realtorRequestOption(Request $request) {
        
        $type        = request('type');
        $userId      = auth()->user()->id;
        $requestId   = request('request_id');
        $requestType = request('request_type');
        if($type == 'reject'){
            
              if($requestType == 'buy'){
                    $requestRow = BuyerRequest::select('user_id', 'selected_realtor')->where('id', $requestId)->first();
                }else{
                    $requestRow = SellerRequest::select('user_id', 'selected_realtor')->where('id', $requestId)->first();
                }
                
            $checkPreviousEntry = UserRejectRequest::where('user_id', $userId)->where('request_id', $requestId)->where('request_type', $requestType)->first();
            if(!$checkPreviousEntry){
                $userRejectRequest               = new UserRejectRequest();
                $userRejectRequest->user_id      = $userId;
                $userRejectRequest->request_id   = $requestId;
                $userRejectRequest->request_type = $requestType;
                $userRejectRequest->request_owner_id = $requestRow->user_id;
                $userRejectRequest->save();
                
              
                
                $messageThread = MessageThread::where('request_id',$requestId)->where('realtor_user_id',$userId)->where('request_type',$requestType)->first();
                
                if($messageThread){
                    
                    $customerId  = $requestRow->user_id;
                    
                    $user        = User::where('id', $customerId)->first();
                    $iosUUID     =  $user->ios_uuid;
                    $androidUUID =  $user->android_uuid;
                    
                    if($requestType == 'buy'){
                        $title = '#B'.$requestId.' closed conversation';
                    }
                    else {
                        $title = '#S'.$requestId.' closed conversation';
                    }
                    
                    $body  = 'A '.auth()->user()->name.' has closed a conversation.';
                                    
                    if($iosUUID){
                        pushNotification($iosUUID, $title, $body, $requestType, $requestId);
                    }
                    if($androidUUID) {
                        pushNotification($androidUUID, $title, $body, $requestType, $requestId);
                    }
                }
                
                return response()->json([
                    'success' => 1,
                    'message' => 'Request successfully rejected.'
                ],200);
            }else{
                return response()->json([
                    'success' => 0,
                    'error'   => 'This request is already rejected.'
                ],200);
            }
        }
        if($type == 'chat'){
            $requestUserId = request('request_user_id');
            $messageThread = MessageThread::where('request_id',$requestId)->where('request_user_id',$requestUserId)->where('realtor_user_id',$userId)->where('request_type',$requestType)->first();
            if(!$messageThread){
                $messageThread                  = new MessageThread();
                $messageThread->request_id      = $requestId;
                $messageThread->request_user_id = $requestUserId;
                $messageThread->realtor_user_id = $userId;
                $messageThread->request_type    = $requestType;
                $messageThread->slug            = '';
                $messageThread->latest_message_by = 'REALTOR';
                
                $messageThread->save();
                MessageThread::where('id',$messageThread->id)->update([
                    'slug' => createSlug().''.$messageThread->id
                ]);
            }
            
            if($messageThread->winner == 0){
                $user = [
                    'winner' => 0,
                ];
            }else{
                $userId = $messageThread->request_user_id;
                $user  = User::select('id', 'name', 'email', 'phone_number', 'profile_pic')->where('id', $userId)->first();
                $customerName = $user->name;
                $customerEmail = $user->email;
                $customerPhone = $user->phone_number;
                $customerProfilePic = url('storage/profile_pictures/customer/'.$user->id.'/'.$user->profile_pic);

                $user = [
                    'customerName'       => $customerName,
                    'customerEamil'      => $customerEmail,
                    'customerPhone'      => $customerPhone,
                    'customerProfilePic' => $customerProfilePic,
                    'winner'             => 1,
                ];
            }
            
            $messageThreadId = $messageThread->id;
            return response()->json([
                'success'           => 1,
                'message'           => 'Message Thread successfully created.',
                'messageThreadId'   => $messageThreadId,
                'messageThreadSlug' => $messageThread->slug,
                'customerData' => $user,
            ],200);
        }
        
    }
    
    // public function conversationBox(Request $request){
    //      $userId   = auth()->user()->id;
    //      $userType = auth()->user()->user_type;
    //      $type     = request('type');
         
    //     if($type == 'primary' && $userType == 2) { //Realtor
    //         $messageThreads    = MessageThread::select('*')->where('realtor_user_id', $userId)->where('winner', 1)->orderBy('id','DESC')->get();
    //         $messageThreadData = [];
            

    //         foreach($messageThreads as $messageThread){

    //              if($messageThread->request_type == 'buy') {
    //                  $property_data = BuyerRequest::where('id', $messageThread->request_id)->first();
    //              }
    //              else {
    //                  $property_data = SellerRequest::where('id', $messageThread->request_id)->first();
    //              }
                 
    //             if($messageThread->winner == 0) {
    //                 $customerData  = User::select('id', 'user_name', 'profile_pic')->where('id',$messageThread->request_user_id)->first();
    //                 $customerName  = $customerData->user_name;
    //                 $profileImageUrl = '';
    //             }
    //             else {
    //                 $customerData  = User::select('id', 'name', 'profile_pic', 'email', 'phone_number')->where('id',$messageThread->request_user_id)->first();
    //                 $customerName  = $customerData->name;
    //                 $profileImage  = $customerData->profile_pic;
    //                 if($profileImage){
    //                     $profileImageUrl = url('storage/profile_pictures/customer/'.$customerData->id.'/'.$customerData->profile_pic);
    //                 }else{
    //                     $profileImageUrl = '';
    //                 }
                    
    //             }
                
    //              $data  = [
    //               'request_type'          => $messageThread->request_type,
    //               'message_thread_id'     => $messageThread->id,
    //               'last_message_date'     => $messageThread->latest_message_for_realtor_datetime ? date('m/d/Y',strtotime($messageThread->latest_message_for_realtor_datetime)) : '',
    //               'last_message'          => ($messageThread->latest_message_by == 'REALTOR' ? $messageThread->latest_message_for_customer : $messageThread->latest_message_for_realtor),                   
    //               'property_data'         => $property_data,
    //               'is_new'                => $messageThread->new_message_count_for_realtor > 0 ? true : false,
    //               'new_messages'          => $messageThread->new_message_count_for_realtor,
    //               'from_person'           => ($messageThread->latest_message_by == 'REALTOR' ? 1 : 0),
    //               'person_name'           => $customerName,
    //               'customer_email'        => $customerData->email,
    //               'customer_phone_number' => $customerData->phone_number,
    //               'user_id'               => $customerData->id,
    //               'profile_image'         => $profileImageUrl,
    //               'message_thread_slug'   => $messageThread->slug,
    //               'winner'                => $messageThread->winner,
    //              ];
                 
    //              $messageThreadData[] = $data;
    //         }
            
    //         return response()->json([
    //           'success'          => 1,
    //           'messageThreads'   => $messageThreadData
    //         ], 200);
    //     }
        
    //     if($type == 'general' && $userType == 2) { //Realtor
       
    //      $messageThreads = MessageThread::select('*')->where('realtor_user_id', $userId)->where('winner', 0)->orderBy('id','DESC')->get();
    //      $messageThreadData = [];
    //      foreach($messageThreads as $messageThread){
    //          $request_id   = $messageThread->request_id;
    //          $request_type = $messageThread->request_type;
             
    //          if($messageThread->request_type == 'buy') {
    //              $property_data = BuyerRequest::where('id', $messageThread->request_id)->first();
    //          }
    //          else {
    //              $property_data = SellerRequest::where('id', $messageThread->request_id)->first();
    //          }
             
    //              if($messageThread->winner == 0) {
    //                  $customerData  = User::select('id', 'user_name')->where('id',$messageThread->request_user_id)->first();
    //                  $customerName  = $customerData->user_name;
    //              }
    //              else {
    //                 $customerData  = User::select('id', 'name')->where('id',$messageThread->request_user_id)->first();
    //                 $customerName  = $customerData->name;
    //             }
                
                
    //          if($property_data && is_null($property_data->selected_realtor)) {
    //              $data  = [
    //               'request_type'         => $messageThread->request_type,
    //               'message_thread_id'    => $messageThread->id,
    //               'last_message_date'     => $messageThread->latest_message_for_realtor_datetime ? date('m/d/Y',strtotime($messageThread->latest_message_for_realtor_datetime)) : '',
    //               'last_message'          => ($messageThread->latest_message_by == 'REALTOR' ? $messageThread->latest_message_for_customer : $messageThread->latest_message_for_realtor),   
    //               'property_data'         => $property_data,
    //               'is_new'                => $messageThread->new_message_count_for_realtor > 0 ? true : false,
    //               'new_messages'          => $messageThread->new_message_count_for_realtor,
    //               'from_person'           => ($messageThread->latest_message_by == 'REALTOR' ? 1 : 0),
    //               'person_name'          => $customerName,
    //               'person_email'         => '',
    //               'person_phone'         => '',
    //               'user_id'              => $customerData->id,
    //               'profile_image'        => '',
    //              ];
                 
    //              $messageThreadData[] = $data;
    //          }
    //      }
        
    //         return response()->json([
    //           'success'          => 1,
    //           'messageThreads'   => $messageThreadData
    //         ], 200);
    //     }
        
    //     /*******************************************************************************************/
        
    //     if($type == 'primary' && $userType == 3) { //Customer
    //         $messageThreads = MessageThread::select('*')->where('request_user_id', $userId)->where('winner', 1)->orderBy('id','DESC')->get();
    //         $messageThreadData = [];
            

    //         foreach($messageThreads as $messageThread){
                
    //              if($messageThread->request_type == 'buy') {
    //                  $property_data = BuyerRequest::where('id', $messageThread->request_id)->first();
    //              }
    //              else {
    //                  $property_data = SellerRequest::where('id', $messageThread->request_id)->first();
    //              }
                 
    //              $selectedRealtorName = '';
    //              $selectedRealtorEmail = '';
    //              $selectedRealtorPhone = '';
            
    //              if($property_data->selected_realtor > 0 && $property_data->selected_realtor == $messageThread->realtor_user_id) {
    //                  $selectedRealtorRow  = User::select('*')->where('id',$property_data->selected_realtor)->first();
    //                  $selectedRealtorName = $selectedRealtorRow->name;
    //                  $selectedRealtorEmail = $selectedRealtorRow->email;
    //                  $selectedRealtorPhone = $selectedRealtorRow->phone_number;                
    //              }
                 
    //             // if($messageThread->winner == 0) {
    //             //     $realtorData  = User::select('id', 'user_name', 'profile_pic')->where('id',$messageThread->realtor_user_id)->first();
    //             //     $realtorName  = $realtorData->user_name;
    //             //     $profileImage = url('storage/profile_pictures/realtor/'.$realtorData->id.'/'.$realtorData->profile_pic);
    //             // }
    //             // else {
    //                 $realtorData  = User::select('id', 'name', 'profile_pic', 'email', 'phone_number')->where('id',$messageThread->realtor_user_id)->first();
    //                 $realtorName  = $realtorData->name;
    //                 if($realtorData->profile_pic){
    //                     $profileImage = url('storage/profile_pictures/realtor/'.$realtorData->id.'/'.$realtorData->profile_pic);
    //                 }
    //                 else{
    //                     $profileImage = '';
    //                 }
    //             // }
                 
    //              $data  = [
    //               'request_type'           => $messageThread->request_type,
    //               'message_thread_id'      => $messageThread->id,
    //               'last_message_date'      => $messageThread->latest_message_for_customer_datetime ? date('m/d/Y',strtotime($messageThread->latest_message_for_customer_datetime)) : '',
    //               'last_message'          => ($messageThread->latest_message_by == 'REALTOR' ? $messageThread->latest_message_for_customer : $messageThread->latest_message_for_realtor),   
    //               'property_data'          => $property_data,
    //               'is_new'                 => $messageThread->new_message_count_for_customer > 0 ? true : false,
    //               'new_messages'           => $messageThread->new_message_count_for_customer,
    //               'winner_selected_id'     => (int)$property_data->selected_realtor,  
    //               'from_person'           => ($messageThread->latest_message_by == 'CUSTOMER' ? 1 : 0),
    //               'selected_realtor_name'  => $selectedRealtorName,
    //               'selected_realtor_email' => $selectedRealtorEmail,
    //               'selected_realtor_phone' => $selectedRealtorPhone,                
    //               'winner'                 => $messageThread->winner,
    //               'person_name'            => $realtorName,
    //               'person_email'           => $realtorData->email,
    //               'person_phone'           => $realtorData->phone_number,
    //               'user_id'                => $realtorData->id,
    //               'profile_image'          => $profileImage
    //              ];
                 
    //              $messageThreadData[] = $data;
    //         }
            
    //         return response()->json([
    //           'success'          => 1,
    //           'messageThreads'   => $messageThreadData
    //         ], 200);
    //     }
        
    //     if($type == 'general' && $userType == 3) { //Customer
       
    //      $messageThreads = MessageThread::select('*')->where('request_user_id', $userId)->where('winner', 0)->orderBy('id','DESC')->get();
    //      $messageThreadData = [];
    //      foreach($messageThreads as $messageThread){
    //          $request_id   = $messageThread->request_id;
    //          $request_type = $messageThread->request_type;
             
    //          if($messageThread->request_type == 'buy') {
    //              $property_data = BuyerRequest::where('id', $messageThread->request_id)->first();
    //          }
    //          else {
    //              $property_data = SellerRequest::where('id', $messageThread->request_id)->first();
    //          }
             
    //         //  if($messageThread->winner == 0) {
    //         //     $realtorData  = User::select('id', 'user_name', 'profile_pic')->where('id',$messageThread->realtor_user_id)->first();
    //         //     $realtorName  = $realtorData->user_name;
    //         //     $profileImage = url('storage/profile_pictures/realtor/'.$realtorData->id.'/'.$realtorData->profile_pic);
    //         // }
    //         // else {
    //             $realtorData  = User::select('id', 'name', 'profile_pic', 'email', 'phone_number')->where('id',$messageThread->realtor_user_id)->first();
    //             $realtorName  = $realtorData->name;
                
    //             if($realtorData->profile_pic){
    //                 $profileImage = url('storage/profile_pictures/realtor/'.$realtorData->id.'/'.$realtorData->profile_pic);
    //             }
    //             else{
    //                 $profileImage = '';
    //             }
    //         // }
             
    //          if($property_data && is_null($property_data->selected_realtor)) {
    //              $data  = [
    //               'request_type'         => $messageThread->request_type,
    //               'message_thread_id'    => $messageThread->id,
    //               'last_message_date'    => $messageThread->latest_message_for_customer_datetime ? date('m/d/Y',strtotime($messageThread->latest_message_for_customer_datetime)) : '',
    //               'last_message'          => ($messageThread->latest_message_by == 'REALTOR' ? $messageThread->latest_message_for_customer : $messageThread->latest_message_for_realtor),   
    //               'from_person'           => ($messageThread->latest_message_by == 'CUSTOMER' ? 1 : 0),
    //               'property_data'        => $property_data,
    //               'is_new'               => $messageThread->new_message_count_for_customer > 0 ? true : false,
    //               'new_messages'         => $messageThread->new_message_count_for_customer,
    //               'person_name'          => $realtorName,
    //               'person_email'         => $realtorData->email,
    //               'person_phone'         => $realtorData->phone_number,
    //               'user_id'              => $realtorData->id,
    //               'profile_image'        => $profileImage
    //              ];
                 
    //              $messageThreadData[] = $data;
    //          }
    //      }
        
    //         return response()->json([
    //           'success'          => 1,
    //           'messageThreads'   => $messageThreadData
    //         ], 200);
    //     }
    // }
    
    
    public function conversationBox(Request $request){
        
         $userId   = auth()->user()->id;
         $userType = auth()->user()->user_type;
        // $type     = request('type');

        $messageThreadData = [];
         
        if($userType == 2) { //Realtor
        
            $rejectedBuyRequest    = UserRejectRequest::select('request_id')->where('request_type','buy')->where('user_id',auth()->user()->id)->pluck('request_id')->all();
            $rejectedSellRequest   = UserRejectRequest::select('request_id')->where('request_type','sell')->where('user_id',auth()->user()->id)->pluck('request_id')->all();
            
            $messageThreads    = MessageThread::select('*')->where('realtor_user_id', $userId)->where('active', 1)->orderBy('latest_message_for_realtor_datetime','DESC')->orderBy('latest_message_for_customer_datetime','DESC')->get();
            foreach($messageThreads as $messageThread){
                
                $show = 1;
                if($messageThread->request_type == 'buy' && in_array($messageThread->request_id, $rejectedBuyRequest)) {
                    $show = 0;     
                }
                if($messageThread->request_type == 'sell' && in_array($messageThread->request_id, $rejectedSellRequest)) {
                    $show = 0;     
                }
                
                if($show == 1) {    
    
                     if($messageThread->request_type == 'buy') {
                         $property_data = BuyerRequest::where('id', $messageThread->request_id)->first();
                     }
                     else {
                         $property_data = SellerRequest::where('id', $messageThread->request_id)->first();
                     }
                     
                    if($messageThread->winner == 0) {
                        $customerData  = User::select('id', 'user_name', 'profile_pic')->where('id',$messageThread->request_user_id)->first();
                        $customerName  = $customerData->user_name;
                        $profileImageUrl = '';
                    }
                    else {
                        $customerData  = User::select('id', 'name', 'profile_pic', 'email', 'phone_number')->where('id',$messageThread->request_user_id)->first();
                        $customerName  = $customerData->name;
                        $profileImage  = $customerData->profile_pic;
                        if($profileImage){
                            $profileImageUrl = url('storage/profile_pictures/customer/'.$customerData->id.'/'.$customerData->profile_pic);
                        }else{
                            $profileImageUrl = '';
                        }
                    }
                    
                     $data  = [
                       'request_type'          => $messageThread->request_type,
                       'message_thread_id'     => $messageThread->id,
                       'last_message_date'     => $messageThread->latest_message_for_realtor_datetime ? date('m/d/Y',strtotime($messageThread->latest_message_for_realtor_datetime)) : '',
                       'last_message_datetime' => $messageThread->latest_message_for_realtor_datetime,
                       'last_message'          => ($messageThread->latest_message_by == 'REALTOR' ? $messageThread->latest_message_for_customer : $messageThread->latest_message_for_realtor),                   
                       'property_data'         => $property_data,
                       'is_new'                => $messageThread->new_message_count_for_realtor > 0 ? true : false,
                       'new_messages'          => $messageThread->new_message_count_for_realtor,
                       'from_person'           => ($messageThread->latest_message_by == 'REALTOR' ? 1 : 0),
                       'person_name'           => $customerName,
                       'customer_email'        => $customerData->email,
                       'customer_phone_number' => $customerData->phone_number,
                       'user_id'               => $customerData->id,
                       'profile_image'         => $profileImageUrl,
                       'message_thread_slug'   => $messageThread->slug,
                       'winner'                => $messageThread->winner,
                       'block'                 => $messageThread->block,
                     ];
                     
                     $messageThreadData[] = $data;
                }
            }
          
            return response()->json([
               'success'          => 1,
               'messageThreads'   => $messageThreadData
            ], 200);
        }
        
        /*******************************************************************************************/
        
        if($userType == 3) { //Customer
            
            $rejectedBuyRequest    = UserRejectRequest::select('request_id')->where('request_type','buy')->where('request_owner_id',auth()->user()->id)->pluck('request_id')->all();
            $rejectedSellRequest   = UserRejectRequest::select('request_id')->where('request_type','sell')->where('request_owner_id',auth()->user()->id)->pluck('request_id')->all();
            
            $messageThreads = MessageThread::select('request_id', 'request_type')->where('request_user_id', $userId)->where('active', 1)->orderBy('latest_message_for_realtor_datetime','DESC')->orderBy('latest_message_for_customer_datetime','DESC')->groupBy('request_id', 'request_type')->get();
            
            foreach($messageThreads as $messageThread) {
                
                $show = 1;
                if($messageThread->request_type == 'buy' && in_array($messageThread->request_id, $rejectedBuyRequest)) {
                    $show = 0;     
                }
                if($messageThread->request_type == 'sell' && in_array($messageThread->request_id, $rejectedSellRequest)) {
                    $show = 0;     
                }
                
                if($show == 1) { 
                     if($messageThread->request_type == 'buy') {
                         $propertyData = BuyerRequest::where('id', $messageThread->request_id)->first();
                     }
                     else {
                         $propertyData = SellerRequest::where('id', $messageThread->request_id)->first();
                     }
                     
                     $totalMessages = MessageThread::where('request_user_id',auth()->user()->id)->where('active', 1)->where('request_type', $messageThread->request_type)->where('request_id', $messageThread->request_id)->orderBy('latest_message_for_realtor_datetime','DESC')->orderBy('latest_message_for_customer_datetime','DESC')->get();
                     
                     $messages = [];
                     foreach($totalMessages as $messageThreadRow)  {
                            $realtorData  = User::select('id', 'name', 'profile_pic', 'email', 'phone_number')->where('id',$messageThreadRow->realtor_user_id)->first();
                            $realtorName  = $realtorData->name;
                            
                            if($realtorData->profile_pic){
                                $profileImage = url('storage/profile_pictures/realtor/'.$realtorData->id.'/'.$realtorData->profile_pic);
                            }
                            else{
                                $profileImage = '';
                             }
                             
                             $messages[]  = [
                                      'request_type'         => $messageThreadRow->request_type,
                                      'message_thread_id'    => $messageThreadRow->id,
                                      'last_message_date'    => $messageThreadRow->latest_message_for_customer_datetime ? date('m/d/Y',strtotime($messageThreadRow->latest_message_for_customer_datetime)) : '',
                                      'last_message'          => ($messageThreadRow->latest_message_by == 'REALTOR' ? $messageThreadRow->latest_message_for_customer : $messageThreadRow->latest_message_for_realtor),   
                                      'from_person'           => ($messageThreadRow->latest_message_by == 'CUSTOMER' ? 1 : 0),
                                      'is_new'               => $messageThreadRow->new_message_count_for_customer > 0 ? true : false,
                                      'new_messages'         => $messageThreadRow->new_message_count_for_customer,
                                      'person_name'          => $realtorName,
                                      'person_email'         => $realtorData->email,
                                      'person_phone'         => $realtorData->phone_number,
                                      'user_id'              => $realtorData->id,
                                      'profile_image'        => $profileImage,
                                      'winner'               => $messageThreadRow->winner,
                                     ];
                     }
                     
                     $data = [
                            'request_type'             => $messageThread->request_type,
                            'id'                       => $propertyData->id,
                            'province'                 => $propertyData->province,
                            'region'                   => $propertyData->region,
                            'city'                     => $propertyData->city,
                            'min_price_range'          => @$propertyData->min_price_range,
                            'max_price_range'          => @$propertyData->max_price_range,    
                            'min_price_tag'            => @$propertyData->min_price_tag,
                            'max_price_tag'            => @$propertyData->max_price_tag,    
                            'sell_price'               => $propertyData->sell_price,
                            'sell_price_tag'           => $propertyData->sell_price_tag,
                            'bedrooms'                 => $propertyData->bedrooms,
                            'bathrooms'                => $propertyData->bathrooms,
                            'selected_realtor'         => $propertyData->selected_realtor,
                            'type_of_house'            => json_decode($propertyData->type_of_house),
                            'heatingFuels'             => json_decode($propertyData->heating_fuel),
                            'messages'                 => $messages,
                            'block'                    => $messageThread->block,
                        ];
                     
                    $messageThreadData[] = $data;
                }
            }
            
            return response()->json([
               'success'          => 1,
               'messageThreads'   => $messageThreadData
            ], 200);
        }
    }
    
    public function sendMessage(Request $request){
        
        $messageThreadId = request('message_thread_id');
        $messageThread   = MessageThread::where('id',$messageThreadId)->first();
        $doc_id          = request('doc_id');
        $requestType     = request('request_type');
        
        if(auth()->user()->user_type == 3) { // Customer
            $messageThread->latest_message_for_realtor          = request('message_text'); 
            $messageThread->latest_message_for_realtor_datetime = date('Y-m-d H:i:s');
            $messageThread->latest_message_by = 'CUSTOMER';
            
            $counter = $messageThread->new_message_count_for_realtor + 1;
            
            $messageThread->new_message_count_for_realtor = $counter;
        }
        else {
            $messageThread->latest_message_for_customer          = request('message_text'); 
            $messageThread->latest_message_for_customer_datetime = date('Y-m-d H:i:s');
            $messageThread->latest_message_by = 'REALTOR';
            
            $counter = $messageThread->new_message_count_for_customer + 1;
            
            $messageThread->new_message_count_for_customer = $counter;
        }
        
        
        $messageThread->doc_id = $doc_id;
        $messageThread->save();
        
        $notificationReceiver = 0;
        $senderName = '';
        
        
        if(auth()->user()->user_type == 3) { // Customer
            $notificationReceiver = $messageThread->realtor_user_id;
            $propertyId           = $messageThread->request_id;
            $senderName           = auth()->user()->user_name;
            $senderEmail          = auth()->user()->email;
            $senderPhone          = auth()->user()->phone_number;
            $senderProfile        = auth()->user()->profile_pic;
            $docId                = $doc_id;
            $requestType          = $requestType;
            $winnerName           = '';
            $winnerEmail          = '';
            $winnerPhone          = '';
            $winner = 0;
            
            
            
            $senderProfile = '';
            
            if($messageThread->winner == 1) {
                $senderProfile = url('storage/profile_pictures/customer/'.auth()->user()->id.'/'.auth()->user()->profile_pic);

                $senderName      = auth()->user()->name;
                $request_user_id = $messageThread->request_user_id;
                // $userInfo        = User::select('name','email','phone_number')->where('id', $request_user_id)->first(); 
                $winnerName      = auth()->user()->name;
                $winnerEmail     = auth()->user()->email;
                $winnerPhone     = auth()->user()->phone_number;
                $winner          = 1;
            }
        }
        if(auth()->user()->user_type == 2) { // Realtor
            $notificationReceiver = $messageThread->request_user_id;
            $propertyId           = $messageThread->request_id;
            $senderName           = auth()->user()->user_name;
            $senderEmail          = auth()->user()->email;
            $senderPhone          = auth()->user()->phone_number;
            $docId                = $doc_id; 
            $requestType          = $requestType;
            $winnerName           = '';
            $winnerEmail          = '';
            $winnerPhone          = '';
            $winner               = 0;
            
            if($messageThread->winner == 1) {
                $senderName    = auth()->user()->name;
                $senderProfile = auth()->user()->profile_pic;
                $winner        = 1;
                
                if($senderProfile){
                    $senderProfile = url('storage/profile_pictures/realtor/'.auth()->user()->id.'/'.auth()->user()->profile_pic);
                }
            }
            
        }
       
        if(strlen(request('message_text')) > 100) {
            $message_text = substr(request('message_text'), 0, 100) . '...';
        }
        else {
            $message_text = request('message_text');
        }
        
        if($notificationReceiver > 0) {
            
            $senderDetails = [];
            $senderDetails['thread_id']      = $messageThread->id;
            $senderDetails['sender_name']    = $senderName;
            $senderDetails['sender_email']   = $senderEmail;
            $senderDetails['sender_phone']   = $senderPhone;
            $senderDetails['winner_name']    = $winnerName;
            $senderDetails['winner_email']   = $winnerEmail;
            $senderDetails['winner_phone']   = $winnerPhone;
            $senderDetails['winner']         = $winner;
            $senderDetails['doc_id']         = $docId;
            $senderDetails['request_type']   = $requestType;
            $senderDetails['request_id']     = $propertyId;
            $senderDetails['sender_profile'] = @$senderProfile;
            
            $userInfo = User::select('ios_uuid', 'android_uuid')->where('id', $notificationReceiver)->first(); 
            if($userInfo->android_uuid) {
                pushNotification($userInfo->android_uuid, auth()->user()->user_name, $message_text, 'CHAT', $senderDetails);
            }
            if($userInfo->ios_uuid) {
                pushNotification($userInfo->ios_uuid, auth()->user()->user_name, $message_text, 'CHAT', $senderDetails);
            }
        }
        
        return response()->json([
            'success'    => 1,
        ], 200);
        
    }
    
    public function chatMessages(Request $request) {
        $messageThreadId = request('message_thread_id');
        
        $userType = auth()->user()->user_type;

        if($userType == 2) { //Realtor
            MessageThread::where('id',$messageThreadId)->update([
                'new_message_count_for_realtor' => 0
            ]);
        }
        
        if($userType == 3) { //Customer
            MessageThread::where('id',$messageThreadId)->update([
                'new_message_count_for_customer' => 0
            ]);
        }

        return response()->json([
            'success'           => 1,
        ], 200);
    }

    
    public function awardToRealtor(Request $request) {
        $messageThreadId = request('message_thread_id');
        $docId           = request('doc_id');

        
        $messageThread = MessageThread::select('request_type', 'realtor_user_id', 'request_id', 'request_user_id')->where('id', $messageThreadId)->first();
        $requestType   = $messageThread->request_type;
        $realtorUserId = $messageThread->realtor_user_id;
        $requestId     = $messageThread->request_id;
        $requestUserId = $messageThread->request_user_id;

        MessageThread::where('request_type', $requestType)->where('request_id', $requestId)->update([
            'active' => 0,
        ]);
        
        MessageThread::where('id', $messageThreadId)->update([
            'active' => 1,
            'winner' => 1,
        ]);
        
        
        if($requestType == 'sell') {
            SellerRequest::where('id', $requestId)->update(['selected_realtor' => $realtorUserId]);
        }
        else {
            BuyerRequest::where('id', $requestId)->update(['selected_realtor' => $realtorUserId]);
        }
        
        $realtorRow     = User::select('id', 'name', 'email', 'phone_number', 'profile_pic')->where('id', $realtorUserId)->first();
        
        $customerRow    = User::select('id', 'name', 'email', 'phone_number', 'profile_pic')->where('id', $requestUserId)->first();
        
        $profileImage = url('storage/profile_pictures/realtor/'.$realtorRow->id.'/'.$realtorRow->profile_pic);
        
        $message      = "You have choosen ". $realtorRow->name . " as your Realtor. You can now view each others information.";
        

        return response()->json([
            'name'                  => $realtorRow->name,
            'email'                 => $realtorRow->email,
            'phone_number'          => $realtorRow->phone_number,    
            'profileImage'          => $profileImage,    
            'customer_name'         => $customerRow->name,    
            'customer_email'        => $customerRow->email,    
            'customer_phone_number' => $customerRow->phone_number,    
            'message'               => $message,
            'success'               => 1,
        ], 200);
        
    }
    
     public function buyerAwardNotification(Request $request) {
        $requestType = 'buy'; 
        $buyerRequestResult = BuyerRequest::select('id')->where('award_notification', 0)->where('selected_realtor', '>', 0)->get();
     
        foreach($buyerRequestResult as $buyerRequestRow) {
            echo $buyerRequestId = $buyerRequestRow->id;
            echo '<br>';
            $messageThreads = MessageThread::select('id', 'realtor_user_id', 'request_user_id', 'winner', 'doc_id')->where('request_id', $buyerRequestId)->where('request_type', $requestType)->get();
            
            foreach($messageThreads as $messageThread) {
                
                $docId       = $messageThread->doc_id;
                $userRow     = User::select('id', 'ios_uuid', 'android_uuid')->where('id', $messageThread->realtor_user_id)->first();
               
                $iosUUID     =  $userRow->ios_uuid;
                $androidUUID =  $userRow->android_uuid;
                $type        = '';
                
                if($messageThread->winner == 1) {
                    
                    $senderRow     = User::select('name', 'user_name', 'email', 'phone_number', 'profile_pic')->where('id', $messageThread->request_user_id)->first();
                    
                    $body = "You have been chosen as the Realtor for property #B$buyerRequestId You can now view each others information.";
                    $title = "#B$buyerRequestId You were selected";
                    
                    $senderName           = $senderRow->name;
                    $senderEmail          = $senderRow->email;
                    $senderPhone          = $senderRow->phone_number;
                    $senderProfile        = $senderRow->profile_pic;
                    
                    $winnerName           = '';
                    $winnerEmail          = '';
                    $winnerPhone          = '';
                    $winner               = 1;
                    
                    if($senderProfile){
                        $senderProfile = url('storage/profile_pictures/customer/'.$messageThread->request_user_id.'/'.$senderProfile);
                    }else{
                        $senderProfile = '';
                    }
                    
                    $senderDetails = [];
                    $senderDetails['thread_id']      = $messageThread->id;
                    $senderDetails['sender_name']    = $senderName;
                    $senderDetails['sender_email']   = $senderEmail;
                    $senderDetails['sender_phone']   = $senderPhone;
                    $senderDetails['winner_name']    = $senderName;
                    $senderDetails['winner_email']   = $senderEmail;
                    $senderDetails['winner_phone']   = $senderPhone;
                    $senderDetails['winner']         = $winner;
                    $senderDetails['doc_id']         = $docId;
                    $senderDetails['request_type']   = $requestType;
                    $senderDetails['request_id']     = $buyerRequestId;
                    $senderDetails['sender_profile'] = $senderProfile;
                    
                    if($iosUUID) {
                        pushNotification($iosUUID, $title, $body, 'CHAT', $senderDetails);
                    }
                    
                    if($androidUUID) {
                        pushNotification($androidUUID, $title, $body, 'CHAT', $senderDetails);
                    }    
                    
                }
                else {
                     $body = "The property #B$buyerRequestId has been given to a different Realtor. Your connection is now closed.";
                    $title = "#B$buyerRequestId You were not selected";
                    
                    if($iosUUID) {
                        pushNotification($iosUUID, $title, $body, 'LOST', $buyerRequestId);
                    }
                    
                    if($androidUUID) {
                        pushNotification($androidUUID, $title, $body, 'LOST', $buyerRequestId);
                    }    
                    
                }

                           
                
            }
            
            
             BuyerRequest::where('id', $buyerRequestId)->update([
                  'award_notification'    => 1
                 ]);
            
        }
    }
    
    public function sellerAwardNotification(Request $request) {
        $requestType = 'sell'; 
        $buyerRequestResult = SellerRequest::select('id')->where('award_notification', 0)->where('selected_realtor', '>', 0)->get();
     
        foreach($buyerRequestResult as $buyerRequestRow) {
            echo $buyerRequestId = $buyerRequestRow->id;
            echo '<br>';
            $messageThreads = MessageThread::select('id', 'realtor_user_id', 'request_user_id', 'winner', 'doc_id')->where('request_id', $buyerRequestId)->where('request_type', $requestType)->get();
            
            foreach($messageThreads as $messageThread) {
                
                $docId       = $messageThread->doc_id;
                $userRow     = User::select('id', 'ios_uuid', 'android_uuid')->where('id', $messageThread->realtor_user_id)->first();
               
                $iosUUID     =  $userRow->ios_uuid;
                $androidUUID =  $userRow->android_uuid;
                $type        = '';
                
                if($messageThread->winner == 1) {
                    
                    $senderRow     = User::select('name', 'user_name', 'email', 'phone_number', 'profile_pic')->where('id', $messageThread->request_user_id)->first();
                    
                    $body = "You have been chosen as the Realtor for property #S$buyerRequestId You can now view each others information.";
                    $title = "#S$buyerRequestId You were selected";
                    
                    $senderName           = $senderRow->name;
                    $senderEmail          = $senderRow->email;
                    $senderPhone          = $senderRow->phone_number;
                    $senderProfile        = $senderRow->profile_pic;
                    
                    $winnerName           = '';
                    $winnerEmail          = '';
                    $winnerPhone          = '';
                    $winner               = 1;
                    
                    if($senderProfile){
                        $senderProfile = url('storage/profile_pictures/customer/'.$messageThread->request_user_id.'/'.$senderProfile);
                    }else{
                        $senderProfile = '';
                    }
                    
                    $senderDetails = [];
                    $senderDetails['thread_id']      = $messageThread->id;
                    $senderDetails['sender_name']    = $senderName;
                    $senderDetails['sender_email']   = $senderEmail;
                    $senderDetails['sender_phone']   = $senderPhone;
                    $senderDetails['winner_name']    = $senderName;
                    $senderDetails['winner_email']   = $senderEmail;
                    $senderDetails['winner_phone']   = $senderPhone;
                    $senderDetails['winner']         = $winner;
                    $senderDetails['doc_id']         = $docId;
                    $senderDetails['request_type']   = $requestType;
                    $senderDetails['request_id']     = $buyerRequestId;
                    $senderDetails['sender_profile'] = $senderProfile;
                    
                    if($iosUUID) {
                        pushNotification($iosUUID, $title, $body, 'CHAT', $senderDetails);
                    }
                    
                    if($androidUUID) {
                        pushNotification($androidUUID, $title, $body, 'CHAT', $senderDetails);
                    }    
                    
                }
                else {
                    echo $body = "The property #S$buyerRequestId has been given to a different Realtor. Your connection is now closed.";
                    $title = "#S$buyerRequestId You were not selected";
                    
                    if($iosUUID) {
                        pushNotification($iosUUID, $title, $body, 'LOST', $buyerRequestId);
                    }
                    
                    if($androidUUID) {
                        pushNotification($androidUUID, $title, $body, 'LOST', $buyerRequestId);
                    }    
                    
                }

                           
                
            }
            
            
             SellerRequest::where('id', $buyerRequestId)->update([
                  'award_notification'    => 1
                 ]);
            
        }
    }
    
    
    public function getConversationPerRequest(Request $request) {
        $requestType =  request('request_type');
        $id          =  request('id');
        
       
        if($requestType == 'buy') {
            
            $rejectListArray = UserRejectRequest::select('user_id')->where('request_type', 'buy')->where('request_id', $id)->pluck('user_id')->all();
            
            $propertyData = BuyerRequest::select('selected_realtor')->where('id', $id)->first();
        }
        else {
            
            $rejectListArray = UserRejectRequest::select('user_id')->where('request_type', 'sell')->where('request_id', $id)->pluck('user_id')->all();
            
            $propertyData = SellerRequest::select('selected_realtor')->where('id', $id)->first();
        }
      
        if(@$propertyData->selected_realtor > 0) {
            $messageThreads = MessageThread::where('request_user_id', auth()->user()->id)->where('request_type', $requestType)->where('request_id', $id)->whereNotIn('realtor_user_id', $rejectListArray)->orderBy('winner','DESC')->get();
        }
        else {
            $messageThreads = MessageThread::where('request_user_id', auth()->user()->id)->where('request_type', $requestType)->where('request_id', $id)->whereNotIn('realtor_user_id', $rejectListArray)->orderBy('id','DESC')->get();
        }  
        
        $messageThreadData = [];    
        foreach($messageThreads as $messageThread){
                
            //     $selectedRealtorName = '';
            //     $selectedRealtorEmail = '';
            //     $selectedRealtorPhone = '';
                
            //   if($propertyData->selected_realtor > 0 && $propertyData->selected_realtor == $messageThread->realtor_user_id) {
            //         $selectedRealtorRow  = User::select('name', 'email', 'phone_number')->where('id',$propertyData->selected_realtor)->first();
            //         $selectedRealtorName  = $selectedRealtorRow->name;
            //         $selectedRealtorEmail = $selectedRealtorRow->email;
            //         $selectedRealtorPhone = $selectedRealtorRow->phone_number;                
            //   }
            
            $disabled = 0;
            $disabledMessage = '';
            if($propertyData->selected_realtor > 0 && $propertyData->selected_realtor != $messageThread->realtor_user_id) {
                $disabled = 1;
                $disabledMessage = 'Sorry you have chosen another realtor.';
            }
        
            //$message      = Message::select('id','created_at','message_text','sender_id','is_new')->where('message_thread_id',$messageThread->id)->orderBy('id','desc')->first();
            $realtorName  = '';
            
            // if($messageThread->winner == 0) {
            //     $realtorData  = User::select('user_name')->where('id',$messageThread->realtor_user_id)->first();
            //     $realtorName  = $realtorData->user_name;
            //     $profileImage = '';
            // }
            // else {
                $realtorData  = User::select('id', 'name', 'profile_pic', 'email', 'phone_number')->where('id',$messageThread->realtor_user_id)->first();
                $realtorName  = $realtorData->name;
                if($realtorData->profile_pic){
                    $profileImage = url('storage/profile_pictures/realtor/'.$realtorData->id.'/'.$realtorData->profile_pic);
                }
                else{
                    $profileImage = '';
                }
                
            //}
            
            
            
            // $totalNewMessages = Message::select('id')->where('message_thread_id',$messageThread->id)->where('sender_id','<>',auth()->user()->id)->where('is_new',1)->count();
        
            $data  = [
                'request_type'          => $messageThread->request_type,
                'message_thread_id'     => $messageThread->id,
                'person_name'           => $realtorName,
                'last_message_date'      => $messageThread->latest_message_for_customer_datetime ? date('m/d/Y',strtotime($messageThread->latest_message_for_customer_datetime)) : '',
                'last_message'           => $messageThread->latest_message_for_customer ? $messageThread->latest_message_for_customer : '',
                //'property_data'          => $property_data,
                'is_new'                 => $messageThread->new_message_count_for_customer > 0 ? true : false,
                'new_messages'           => $messageThread->new_message_count_for_customer,
                'from_person'           => ($messageThread->latest_message_by != 'REALTOR' ? 1 : 0),
                'winner_selected_id'    => (int)$propertyData->selected_realtor,  
                // 'selected_realtor_name' => $selectedRealtorName,
                // 'selected_realtor_email'=> $selectedRealtorEmail,
                // 'selected_realtor_phone'=> $selectedRealtorPhone,                
                'winner'                => $messageThread->winner,
                'disabled'              => $disabled,
                'disabled_message'      => $disabledMessage,
                'profile_image'         => $profileImage,  
                'user_id'               => $realtorData->id,  
                'person_name'           => $realtorData->name,  
                'person_email'          => $realtorData->email,  
                'person_phone_number'   => $realtorData->phone_number,  
            ];
            
            $messageThreadData[] = $data;
        }
        return response()->json([
            'success'          => 1,
            'messageThreads'   => $messageThreadData
        ], 200);
        
    }
    
    public function newBuyerNotification(Request $request) {
        $buyerRequestResult = BuyerRequest::select('id', 'city')->where('notification', 0)->whereNull('selected_realtor')->get();
        foreach($buyerRequestResult as $buyerRequestRow) {
            
           
            
            
            $buyerRequestId = $buyerRequestRow->id;
            $city           = $buyerRequestRow->city;
            $city           = json_decode($city, true);
            
            $users = User::select('id', 'ios_uuid', 'android_uuid')->when($city, function ($query) use ($city) {
                
                $query->whereJsonContains('city', $city[0]);
                
                for($i = 1; $i < count($city); $i++) {
                  $query->orWhereJsonContains('city', $city[$i]);      
                }
                
                
                })->where('user_type', 2)->get();    
                
           
                
            
            
            $title          = "#$buyerRequestId New Buying Request";
            //$body           = "New Buying Request in your city $city. Please check.";
            $body           = "New Buying Request submitted. Click to View.";
            
            foreach($users as $userRow) {
                $iosUUID     =  $userRow->ios_uuid;
                $androidUUID =  $userRow->android_uuid;
                
                if($iosUUID) {
                    pushNotification($iosUUID, $title, $body, 'BUYING_REQUEST', $buyerRequestId);
                }
                
                if($androidUUID) {
                    pushNotification($androidUUID, $title, $body, 'BUYING_REQUEST', $buyerRequestId);
                }
                
            }
            
             BuyerRequest::where('id', $buyerRequestId)->update([
                  'notification'    => 1
                 ]);
            
        }
    }
    
    public function newSellerNotification(Request $request) {
        
        $sellerRequestResult = SellerRequest::select('id', 'city')->where('notification', 0)->whereNull('selected_realtor')->get();
        foreach($sellerRequestResult as $sellerRequestRow) {
            $sellingRequestId = $sellerRequestRow->id;
            $city         = $sellerRequestRow->city;
            $users            = User::select('id', 'ios_uuid', 'android_uuid')->where('city', 'LIKE', '%"' . $city . '"%')->where('user_type', 2)->get();
            
            $title            = "#$sellingRequestId New Selling Request";
            $body             = "New Selling Request in your city $city. Click to View.";
            
            foreach($users as $userRow) {
                $iosUUID     =  $userRow->ios_uuid;
                $androidUUID =  $userRow->android_uuid;
                
                if($iosUUID) {
                    pushNotification($iosUUID, $title, $body, 'SELLING_REQUEST', $sellingRequestId);
                }
                
                if($androidUUID) {
                    pushNotification($androidUUID, $title, $body, 'SELLING_REQUEST', $sellingRequestId);
                }
                
            }
            
             SellerRequest::where('id', $sellingRequestId)->update([
                   'notification'    => 1
             ]);
            
        }
        
    }
    
    public function getRealtorDetails(Request $request)
    {
        $reatorUserId = request('realtor_user_id');
        
        $realtorDetail = User::select('name', 'email', 'user_name', 'brokerage', 'realtor', 'realtor_year', 'real_estate_association', 'address', 'awards', 'service_area', 'region', 'city', 'language', 'website', 'bio', 'sports_played', 'interest_and_hobby', 'years_with_brokerage', 'phone_number', 'other_language')->where('id', $reatorUserId)->first();
        
        $realtorDetail = [
            'id'                      => $realtorDetail->id,
            'name'                    => $realtorDetail->name,
            'user_name'               => $realtorDetail->user_name,
            'email'                   => $realtorDetail->email,
            'phone_number'            => $realtorDetail->phone_number,
            'brokerage'               => $realtorDetail->brokerage,        
            'realtor'                 => $realtorDetail->realtor,                 
            'real_estate_association' => $realtorDetail->real_estate_association, 
            'language'                => $realtorDetail->language,                
            'awards'                  => $realtorDetail->awards,                 
            'website'                 => $realtorDetail->website,                 
            'bio'                     => $realtorDetail->bio,                    
            'address'                 => $realtorDetail->address,                
            'service_area'            => $realtorDetail->service_area,           
            'region'                  => $realtorDetail->region,               
            'city'                    => $realtorDetail->city,               
            'realtor_year'            => $realtorDetail->realtor_year,               
            'sports_played'           => $realtorDetail->sports_played,               
            'interest_and_hobby'      => $realtorDetail->interest_and_hobby,               
            'years_with_brokerage'    => $realtorDetail->years_with_brokerage,               
            'other_language'          => $realtorDetail->other_language,               
        ];
        
        return response()->json([
            'success'        => 1,
            'realtor_deails' => $realtorDetail
        ], 200);
    }
    
    public function checkAwardStatus(Request $request)
    {
        $messageThreadId = request('message_thread_id');
        
        $messageThread   = MessageThread::where('id', $messageThreadId)->first();
        
        if($messageThread->winner == 1){
            $user = User::where('id', $messageThread->request_user_id)->first();
            
            if($user->profile_pic){
                $profile_pic = url('storage/profile_pictures/customer/'.$user->id.'/'.$user->profile_pic);
            }else{
                $profile_pic = '';
            }

            $user = [
                'name'         => $user->name,
                'email'        => $user->email,
                'phone_number' => $user->phone_number,
                'profile_pic'  => $profile_pic,
            ];
            
            $requestId = $messageThread->request_id;
            
            if($messageThread->request_type == 'buy') {
                $message = "You have been chosen as the Realtor for property #B$requestId You can now view each others information.";
            }
            else {
                $message = "You have been chosen as the Realtor for property #S$requestId You can now view each others information.";
            }
            
            return response()->json([
                'success'    => 1,
                'userDtails' => $user,
                'winner'     => 1,
                'message'    => $message
            ], 200);
        
        }else{
            return response()->json([
                'success'    => 1,
                'winner'     => 0
            ], 200);
        }
    }
    
}