<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request; 
use App\Http\Controllers\Controller; 
use App\Models\User;
use App\Models\BuyerRequest;
use App\Models\SellerRequest;
use App\Models\HouseType;
use App\Models\UserRejectRequest;
use App\Models\MessageThread;
use App\Models\Message;
use App\Models\CityRange;
use App\Models\HeatingFuel;
use App\Models\CoolingType;
use Illuminate\Support\Facades\Auth; 

class BuyerRequestController extends Controller {
    
    /** 
     * index api 
     * 
     * @return \Illuminate\Http\Response 
     */ 
    public function createBuyerRequest(Request $request) {
        
        $amenities = request('amenities');
        $amenities = explode(",", $amenities);
        
        $parkings = request('parkings');
        $parkings = explode(",", $parkings);
        
        $heatingFuels = request('heating_fuels');
        $heatingFuels = explode(",", $heatingFuels);
        
        $typeOfHouse = request('type_of_house');
        $typeOfHouse = explode(",", $typeOfHouse);
        
        $cities      = request('city');
        $cities      = explode(",", $cities);
        
        $buyerRequest                           = new BuyerRequest();
        $buyerRequest->user_id                  = auth()->user()->id;
        $buyerRequest->province                 = request('province');
        $buyerRequest->region                   = request('region');
        $buyerRequest->city                     = json_encode($cities, true);
        $buyerRequest->min_price_range          = request('min_price_range');
        $buyerRequest->max_price_range          = request('max_price_range');
        $buyerRequest->min_price_tag            = request('min_price_tag');
        $buyerRequest->max_price_tag            = request('max_price_tag');
        $buyerRequest->bedrooms                 = request('bedrooms');
        $buyerRequest->bathrooms                = request('bathrooms');
        $buyerRequest->type_of_house            = json_encode($typeOfHouse, true);
        $buyerRequest->heating_fuel             = json_encode($heatingFuels, true);
        $buyerRequest->amenities                = json_encode($amenities, true);
        $buyerRequest->build                    = request('build');
        $buyerRequest->age_property             = request('age_property');
        $buyerRequest->sqft_property            = request('sqft_property');
        $buyerRequest->building_area_tag        = request('building_area_tag');
        $buyerRequest->parking                  = json_encode($parkings, true);
        $buyerRequest->preferred_neighbourhoods = request('preferred_neighbourhoods');
        $buyerRequest->other_request            = request('other_request');
        $buyerRequest->senior_community         = request('senior_community');
        $buyerRequest->financing                = request('financing');
        $buyerRequest->save();
        
        $data = [
            'id'              => $buyerRequest->id,
            'province'        => $buyerRequest->province,
            'region'          => $buyerRequest->region,
            'city'            => $buyerRequest->city,
            'bathrooms'       => $buyerRequest->bathrooms,
            'bedrooms'        => $buyerRequest->bedrooms,
            'heating_fuel'    => $buyerRequest->heating_fuel,
            'type_of_house'   => $buyerRequest->type_of_house,
            'max_price_range' => $buyerRequest->max_price_range,
            'max_price_tag'   => $buyerRequest->max_price_tag,
            'min_price_range' => $buyerRequest->min_price_range,
            'min_price_tag'   => $buyerRequest->min_price_tag,
        ];
        
        return response()->json([
            'success' => 1,
            'data'    => $data,
            'message' => 'Buyer Request Successfully Created.'
        ], 200);
        
    }
    
    public function getBuyerRequest(Request $request){
        
        $type        = request('type');
        $lastId      = request('last_id');
        
        if($type == 'realtor'){
            $realtorCity = CityRange::select('city_name')->where('user_id',auth()->user()->id)->pluck('city_name')->all();
            $requestIds    = UserRejectRequest::select('request_id')->where('request_type','buy')->where('user_id',auth()->user()->id)->pluck('request_id')->all();
            
            if($lastId){
                $buyerRequests = BuyerRequest::when($lastId, function ($query) use ($lastId) {
                    $query->where('id', '>', $lastId);
                })->whereJsonContains('city', $realtorCity[0]);
                
                for($i = 1; $i < count($realtorCity); $i++) {
                  $query->orWhereJsonContains('city', $realtorCity[$i]);      
                }
                
                $query->whereNull('selected_realtor')->whereNotIn('id',$requestIds)->orderBy('id', 'DESC')->take(30)->get();
            }else{
                
                $buyerRequests = BuyerRequest::whereNotIn('id',$requestIds)->when($realtorCity, function ($query) use ($realtorCity) {
                
                $query->whereJsonContains('city', $realtorCity[0]);
                
                for($i = 1; $i < count($realtorCity); $i++) {
                  $query->orWhereJsonContains('city', $realtorCity[$i]);      
                }
                
                
                })->whereNull('selected_realtor')->orderBy('id', 'DESC')->take(30)->get();    
            }
        }else{
            
            if($lastId){
                $buyerRequests = BuyerRequest::select('id', 'user_id', 'province', 'region', 'city', 'min_price_range', 'max_price_range', 'min_price_tag', 'max_price_tag', 'bedrooms', 'bathrooms', 'type_of_house', 'heating_fuel')->when($lastId, function ($query) use ($lastId) {
                    $query->where('id', '>', $lastId);
                })->where('user_id', auth()->user()->id)->orderBy('id', 'DESC')->take(30)->get();  
            }else{
                $buyerRequests = BuyerRequest::select('id', 'user_id', 'province', 'region', 'city', 'min_price_range', 'max_price_range', 'min_price_tag', 'max_price_tag', 'bedrooms', 'bathrooms', 'type_of_house', 'heating_fuel')->where('user_id', auth()->user()->id)->orderBy('id', 'DESC')->take(30)->get();      
            }
        }
        
        $buyerRequestArray = [];
        
        foreach($buyerRequests as $buyerRequest){
            
            
            $totalRealtor = 0;
            $messageThreadId = 0;
            if($type == 'realtor'){
                $totalMessages = MessageThread::select('id')->where('realtor_user_id',auth()->user()->id)->where('request_type','buy')->where('request_id',$buyerRequest->id)->count();
            }else{
                
                $rejectListArray = UserRejectRequest::select('user_id')->where('request_type', 'buy')->where('request_id', $buyerRequest->id)->pluck('user_id')->all();
                
                $totalMessages = MessageThread::select('id')->where('request_user_id',auth()->user()->id)->where('request_type','buy')->whereNotIn('realtor_user_id', $rejectListArray)->where('request_id',$buyerRequest->id)->count();
                $totalRealtor = MessageThread::select('realtor_user_id')->where('request_user_id',auth()->user()->id)->where('request_type','buy')->whereNotIn('realtor_user_id', $rejectListArray)->where('request_id',$buyerRequest->id)->groupBy('realtor_user_id')->get();
                $totalRealtor = $totalRealtor->count();
                if($totalRealtor == 1){
                    $messageThreadId = MessageThread::select('id')->where('request_user_id',auth()->user()->id)->where('request_type','buy')->where('request_id',$buyerRequest->id)->first();
                    $messageThreadId = $messageThreadId->id;
                }
            }
            $data = [
                'id'                       => $buyerRequest->id,
                'name'                     => $buyerRequest->user_id ? $buyerRequest->users && $buyerRequest->users->name: '',
                'user_name'                => $buyerRequest->user_id ? $buyerRequest->users && $buyerRequest->users->user_name: '',
                'user_id'                  => $buyerRequest->user_id,
                'province'                 => $buyerRequest->province,
                'region'                   => $buyerRequest->region,
                'city'                     => json_decode($buyerRequest->city),
                'min_price_range'          => $buyerRequest->min_price_range,
                'max_price_range'          => $buyerRequest->max_price_range,
                'min_price_tag'            => $buyerRequest->min_price_tag,
                'max_price_tag'            => $buyerRequest->max_price_tag,
                'bedrooms'                 => $buyerRequest->bedrooms,
                'bathrooms'                => $buyerRequest->bathrooms,
                'type_of_house'            => json_decode($buyerRequest->type_of_house),
                'heatingFuels'             => json_decode($buyerRequest->heating_fuel),
                'notification'             => $totalMessages,
                'total_realtor'            => $totalRealtor,
                'message_thread_id'        => $messageThreadId,
            ];
            $buyerRequestArray[] = $data;
        }

        return response()->json([
            'success' => 1,
            'data'    => $buyerRequestArray,
        ], 200);
        
    }
    
    public function getawardedBuyerRequest(Request $request){
        
        $requestIds    = UserRejectRequest::select('request_id')->where('request_type','buy')->where('user_id',auth()->user()->id)->pluck('request_id')->all();
        
        $buyerRequests = BuyerRequest::whereNotIn('id',$requestIds)->where('selected_realtor', auth()->user()->id)->orderBy('id', 'DESC')->take(30)->get();    
           
        $buyerRequestArray = [];
        
        foreach($buyerRequests as $buyerRequest){
            
            $totalRealtor = 0;
            $messageThreadId = 0;

            $totalMessages = MessageThread::select('id')->where('realtor_user_id',auth()->user()->id)->where('request_type','buy')->where('request_id',$buyerRequest->id)->count();
            
            $data = [
                'id'                       => $buyerRequest->id,
                'name'                     => $buyerRequest->user_id ? $buyerRequest->users && $buyerRequest->users->name: '',
                'user_name'                => $buyerRequest->user_id ? $buyerRequest->users && $buyerRequest->users->user_name: '',
                'user_id'                  => $buyerRequest->user_id,
                'province'                 => $buyerRequest->province,
                'region'                   => $buyerRequest->region,
                'city'                     => json_decode($buyerRequest->city),
                'min_price_range'          => $buyerRequest->min_price_range,
                'max_price_range'          => $buyerRequest->max_price_range,
                'min_price_tag'            => $buyerRequest->min_price_tag,
                'max_price_tag'            => $buyerRequest->max_price_tag,
                'bedrooms'                 => $buyerRequest->bedrooms,
                'bathrooms'                => $buyerRequest->bathrooms,
                'type_of_house'            => json_decode($buyerRequest->type_of_house),
                'heatingFuels'             => json_decode($buyerRequest->heating_fuel),
                'notification'             => $totalMessages,
                'total_realtor'            => $totalRealtor,
                'message_thread_id'        => $messageThreadId,
            ];
            $buyerRequestArray[] = $data;
        }

        return response()->json([
            'success' => 1,
            'data'    => $buyerRequestArray,
        ], 200);
        
    }
    
    public function editBuyerRequest(Request $request){
        
        $id  = request('id');
        
        $amenities = request('amenities');
        $amenities = explode(",", $amenities);
        
        $parkings = request('parkings');
        $parkings = explode(",", $parkings);
        
        $heatingFuels = request('heating_fuels');
        $heatingFuels = explode(",", $heatingFuels);
        
        $typeOfHouse = request('type_of_house');
        $typeOfHouse = explode(",", $typeOfHouse);
        
        $cities      = request('city');
        $cities      = explode(",", $cities);
        
        $buyerRequest                           = BuyerRequest::select('id', 'province', 'region', 'city', 'min_price_range', 'max_price_range', 'min_price_tag', 'max_price_tag', 'bedrooms', 'bathrooms', 'type_of_house', 'heating_fuel', 'amenities', 'build', 'age_property', 'sqft_property', 'parking', 'preferred_neighbourhoods', 'other_request', 'senior_community', 'financing', 'building_area_tag')->where('id', $id)->first();
        $buyerRequest->province                 = request('province');
        $buyerRequest->region                   = request('region');
        $buyerRequest->city                     = $cities;
        $buyerRequest->min_price_range          = request('min_price_range');
        $buyerRequest->max_price_range          = request('max_price_range');
        $buyerRequest->min_price_tag            = request('min_price_tag');
        $buyerRequest->max_price_tag            = request('max_price_tag');
        $buyerRequest->bedrooms                 = request('bedrooms');
        $buyerRequest->bathrooms                = request('bathrooms');
        $buyerRequest->type_of_house            = $typeOfHouse;
        $buyerRequest->heating_fuel             = $heatingFuels;
        $buyerRequest->amenities                = $amenities;
        $buyerRequest->build                    = request('build');
        $buyerRequest->age_property             = request('age_property');
        $buyerRequest->sqft_property            = request('sqft_property');
        $buyerRequest->building_area_tag        = request('building_area_tag');
        $buyerRequest->parking                  = $parkings;
        $buyerRequest->preferred_neighbourhoods = request('preferred_neighbourhoods');
        $buyerRequest->other_request            = request('other_request');
        $buyerRequest->senior_community         = request('senior_community');
        $buyerRequest->financing                = request('financing');
        $buyerRequest->save();
        
        return response()->json([
            'success' => 1,
            'data'    => $buyerRequest,
            'message' => 'Buyer Request Successfully Updated.'
        ], 200);
        
    }
    
    public function deleteBuyerRequest(Request $request){
        
        $id  = request('id');
        BuyerRequest::select('id')->where('id', $id)->delete();
        
        UserRejectRequest::select('id')->where('request_id', $id)->where('request_type', 'buy')->delete();
        MessageThread::select('id')->where('request_id', $id)->where('request_type', 'buy')->delete();
        
        return response()->json([
            'success' => 1,
            'message' => 'Buyer Request Successfully Deleted.'
        ], 200);
    }    
    
    public function getBuyerDetails(Request $request) {
        
        $id              = request('id');
        $type            = request('type');
        $messageThreadId = 0;
        $totalRealtor    = 0;
        
        if($type == 'realtor'){
            $totalMessages = MessageThread::select('id')->where('realtor_user_id',auth()->user()->id)->where('request_type','buy')->where('request_id',$id)->count();
        }else{
            
            $rejectListArray = UserRejectRequest::select('user_id')->where('request_type', 'buy')->where('request_id', $id)->pluck('user_id')->all();
            
            $totalMessages = MessageThread::select('id')->where('request_user_id',auth()->user()->id)->whereNotIn('realtor_user_id', $rejectListArray)->where('request_type','buy')->where('request_id',$id)->count();
            $totalRealtor = MessageThread::select('realtor_user_id')->where('request_user_id',auth()->user()->id)->whereNotIn('realtor_user_id', $rejectListArray)->where('request_type','buy')->where('request_id',$id)->groupBy('realtor_user_id')->get();
            $totalRealtor = $totalRealtor->count();
            if($totalRealtor == 1){
                $messageThreadId = MessageThread::select('id')->where('request_user_id',auth()->user()->id)->where('request_type','buy')->where('request_id',$id)->first();
                $messageThreadId = $messageThreadId->id;
            }
        }
            
        $buyerRequest = BuyerRequest::select('id', 'user_id', 'province', 'region', 'city', 'min_price_range', 'max_price_range', 'min_price_tag', 'max_price_tag',  'bedrooms', 'bathrooms', 'type_of_house', 'heating_fuel', 'amenities','build', 'age_property', 'sqft_property', 'parking', 'preferred_neighbourhoods', 'other_request', 'senior_community', 'building_area_tag', 'financing')->where('id', $id)->first();
       
        return response()->json([
            'success' => 1,
            'id'                       => $buyerRequest->id,
            'name'                     => $buyerRequest->user_id ? $buyerRequest->users->name: '',
            'user_name'                => $buyerRequest->user_id ? $buyerRequest->users->user_name: '',
            'user_id'                  => $buyerRequest->user_id,
            'province'                 => $buyerRequest->province,
            'region'                   => $buyerRequest->region,
            'city'                     => json_decode($buyerRequest->city),
            'min_price_range'          => $buyerRequest->min_price_range,
            'max_price_range'          => $buyerRequest->max_price_range,
            'min_price_tag'            => $buyerRequest->min_price_tag,
            'max_price_tag'            => $buyerRequest->max_price_tag,
            'bedrooms'                 => $buyerRequest->bedrooms,
            'bathrooms'                => $buyerRequest->bathrooms,
            'type_of_house'            => json_decode($buyerRequest->type_of_house),
            'heatingFuels'             => json_decode($buyerRequest->heating_fuel),
            'amenities'                => json_decode($buyerRequest->amenities),
            'build'                    => $buyerRequest->build,
            'age_property'             => $buyerRequest->age_property,
            'sqft_property'            => $buyerRequest->sqft_property,
            'parkings'                 => json_decode($buyerRequest->parking),
            'preferred_neighbourhoods' => $buyerRequest->preferred_neighbourhoods,
            'other_request'            => $buyerRequest->other_request,
            'notification'             => $totalMessages,
            'total_realtor'            => $totalRealtor,
            'message_thread_id'        => $messageThreadId,
            'senior_community'         => $buyerRequest->senior_community,
            'financing'                => $buyerRequest->financing,
            'building_area_tag'        => $buyerRequest->building_area_tag,
        ], 200); 
        
    }
    
    public function checkUserLimit(Request $request){
        
        $startDate     = date('Y-m-01');
        $endDate       = date('Y-m-31');
        $buyerRequest  = BuyerRequest::select('user_id')->where('user_id', auth()->user()->id)->whereBetween('created_at', [$startDate, $endDate])->count();
        $sellerRequest = SellerRequest::select('user_id')->where('user_id', auth()->user()->id)->whereBetween('created_at', [$startDate, $endDate])->count();
        
        $total =  $buyerRequest + $sellerRequest;
        
        if($total >= 10){
            return response()->json([
                'success'     => 1,
                'limitExceed' => 1,
                'message'     => 'You have reached your posting limit for this month, we only allow 10 posts per month per user.'
            ], 200);
        }else{
            return response()->json([
                'success'     => 1,
                'limitExceed' => 0,
                'message'     => '',
            ], 200);
        }
        
    } 
   
}