<?php

namespace App\Http\Controllers\API;

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

class SellerRequestController extends Controller {
    
    /** 
     * index api 
     * 
     * @return \Illuminate\Http\Response 
     */ 
    public function createSellerRequest(Request $request) {
        
        $amenities = request('amenities');
        
        if($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);
        
        $sellerRequest                           = new SellerRequest();
        $sellerRequest->user_id                  = auth()->user()->id;
        $sellerRequest->province                 = request('province');
        $sellerRequest->region                   = request('region');
        $sellerRequest->city                     = request('city');
        $sellerRequest->sell_price               = request('sell_price');
        $sellerRequest->sell_price_tag           = request('sell_price_tag');
        $sellerRequest->bedrooms                 = request('bedrooms');
        $sellerRequest->bathrooms                = request('bathrooms');
        $sellerRequest->type_of_house            = json_encode($typeOfHouse, true);
        $sellerRequest->heating_fuel             = json_encode($heatingFuels, true);
        $sellerRequest->amenities                = json_encode($amenities, true);
        $sellerRequest->build                    = request('build');
        $sellerRequest->age_property             = request('age_property');
        $sellerRequest->sqft_property            = request('sqft_property');
        $sellerRequest->building_area_tag        = request('building_area_tag');
        $sellerRequest->parking                  = json_encode($parkings, true);
        $sellerRequest->preferred_neighbourhoods = request('preferred_neighbourhoods');
        $sellerRequest->other_request            = request('other_request');
        $sellerRequest->senior_community         = request('senior_community');
        $sellerRequest->suite                    = request('suite');
        $sellerRequest->suite_option             = request('suite_option');
        $sellerRequest->buying_new_home          = request('buying_new_home');
        $sellerRequest->already_buy_request      = request('already_buy_request');
        $sellerRequest->currently_listed_realtor = request('currently_listed_realtor');
        $sellerRequest->save();
        
        $data = [
            'id'             => $sellerRequest->id,
            'province'       => $sellerRequest->province,
            'region'         => $sellerRequest->region,
            'city'           => $sellerRequest->city,
            'bathrooms'      => $sellerRequest->bathrooms,
            'bedrooms'       => $sellerRequest->bedrooms,
            'heating_fuel'   => $sellerRequest->heating_fuel,
            'type_of_house'  => $sellerRequest->type_of_house,
            'sell_price'     => $sellerRequest->max_price_range,
            'sell_price_tag' => $sellerRequest->max_price_tag,
        ];
        
        $userId = auth()->user()->id;
        
        $images = request('images');
        
        if($images){
            $images = json_decode($images,true);
            foreach($images as $key => $image){
                
                $base64          = $image['base64'];
                $actualFilename  = $image['filename']; 
                $customFilename  = time() . "_" . str_replace(" ","_",$actualFilename);
                
                $newDir  = storage_path('request_images/'.$userId.'/'.$sellerRequest->id);
                if (!file_exists($newDir)) {
                    mkdir($newDir, 0777, true);
                }
                $savePath = $newDir.'/'.$customFilename;
                file_put_contents($savePath, base64_decode($base64));
                
                $requestImage                 = new RequestImage();
                $requestImage->request_id     = $sellerRequest->id;
                $requestImage->filename       = $customFilename;
                $requestImage->real_filename  = $actualFilename;
                $requestImage->sorting        = $key;
                $requestImage->type           = 'sell';
                $requestImage->save();
            }
        }
        
        
        return response()->json([
            'success' => 1,
            'data'    => $sellerRequest,
            'message' => 'Seller Request Successfully Created.'
        ], 200);
        
    }
    
    public function getSellerRequest(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','sell')->where('user_id',auth()->user()->id)->pluck('request_id')->all();
            
            if($lastId){
                $sellerRequests = SellerRequest::when($lastId, function ($query) use ($lastId) {
                    $query->where('id', '>', $lastId);
                })->whereIn('city', $realtorCity)->whereNull('selected_realtor')->whereNotIn('id',$requestIds)->orderBy('id', 'DESC')->take(30)->get();
            }else{
                $sellerRequests = SellerRequest::whereIn('city', $realtorCity)->whereNull('selected_realtor')->whereNotIn('id',$requestIds)->orderBy('id', 'DESC')->take(30)->get();
            }
        }else{
            if($lastId){
                $sellerRequests = SellerRequest::when($lastId, function ($query) use ($lastId) {
                    $query->where('id', '>', $lastId);
                })->where('user_id', auth()->user()->id)->orderBy('id', 'DESC')->take(30)->get();  
            }else{
                $sellerRequests = SellerRequest::where('user_id', auth()->user()->id)->orderBy('id', 'DESC')->take(30)->get();  
            }
        }
    
        
        $sellerRequestsArray = [];
        
        foreach($sellerRequests as $sellerRequest){
            
            $id = $sellerRequest->id;
            $totalRealtor = 0;
            $messageThreadId = 0;
            
            if($type == 'realtor'){
                $totalMessages = MessageThread::select('id')->where('realtor_user_id',auth()->user()->id)->where('request_type','sell')->where('request_id',$id)->count();
            }else{
                
                // $rejectListArray = UserRejectRequest::select('user_id')->where('request_type', 'sell')->where('request_id', $buyerRequest->id)->pluck('user_id')->all();
                
                // $totalMessages = MessageThread::select('id')->where('request_user_id',auth()->user()->id)->where('request_type','sell')->where('request_id',$id)->count();
                
                $rejectListArray = UserRejectRequest::select('user_id')->where('request_type', 'sell')->where('request_id', $sellerRequest->id)->pluck('user_id')->all();
                
                $totalMessages = MessageThread::select('id')->where('request_user_id',auth()->user()->id)->where('request_type','sell')->whereNotIn('realtor_user_id', $rejectListArray)->where('request_id',$sellerRequest->id)->count();
                $totalRealtor = MessageThread::select('realtor_user_id')->where('request_user_id',auth()->user()->id)->where('request_type','sell')->whereNotIn('realtor_user_id', $rejectListArray)->where('request_id',$sellerRequest->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','sell')->where('request_id',$sellerRequest->id)->first();
                    $messageThreadId = $messageThreadId->id;
                }
            }
            

            $data = [
                'id'                       => $sellerRequest->id,
                'name'                     => $sellerRequest->user_id ? $sellerRequest->users && $sellerRequest->users->name: '',
                'user_name'                => $sellerRequest->user_id ? $sellerRequest->users && $sellerRequest->users->user_name: '',
                'user_id'                  => $sellerRequest->user_id,
                'province'                 => $sellerRequest->province,
                'region'                   => $sellerRequest->region,
                'city'                     => $sellerRequest->city,
                'sell_price'               => $sellerRequest->sell_price,
                'sell_price_tag'           => $sellerRequest->sell_price_tag,
                'bedrooms'                 => $sellerRequest->bedrooms,
                'bathrooms'                => $sellerRequest->bathrooms,
                'type_of_house'            => json_decode($sellerRequest->type_of_house),
                'heatingFuels'             => json_decode($sellerRequest->heating_fuel),
                'notification'             => $totalMessages,
                'total_realtor'            => $totalRealtor,
                'message_thread_id'        => $messageThreadId,
            ];
            $sellerRequestsArray[] = $data;
        }
        
        return response()->json([
            'success' => 1,
            'data'    => $sellerRequestsArray,
        ], 200);
    }
    
    public function getawardedSellerRequest(Request $request){
        $lastId = request('last_id');
        
        $requestIds    = UserRejectRequest::select('request_id')->where('request_type','sell')->where('user_id',auth()->user()->id)->pluck('request_id')->all();

        $sellerRequests = SellerRequest::whereNotIn('id',$requestIds)->where('selected_realtor', auth()->user()->id)->orderBy('id', 'DESC')->take(30)->get();
        
        $sellerRequestsArray = [];
        
        foreach($sellerRequests as $sellerRequest){
            
            $id = $sellerRequest->id;
            
            $totalMessages = MessageThread::select('id')->where('realtor_user_id',auth()->user()->id)->where('request_type','sell')->where('request_id',$id)->count();

            $data = [
                'id'                       => $sellerRequest->id,
                'name'                     => $sellerRequest->user_id ? $sellerRequest->users && $sellerRequest->users->name: '',
                'user_name'                => $sellerRequest->user_id ? $sellerRequest->users && $sellerRequest->users->user_name: '',
                'user_id'                  => $sellerRequest->user_id,
                'province'                 => $sellerRequest->province,
                'region'                   => $sellerRequest->region,
                'city'                     => $sellerRequest->city,
                'sell_price'               => $sellerRequest->sell_price,
                'sell_price_tag'           => $sellerRequest->sell_price_tag,
                'bedrooms'                 => $sellerRequest->bedrooms,
                'bathrooms'                => $sellerRequest->bathrooms,
                'type_of_house'            => json_decode($sellerRequest->type_of_house),
                'heatingFuels'             => json_decode($sellerRequest->heating_fuel),
                'notification'             => $totalMessages,
            ];
            $sellerRequestsArray[] = $data;
        }
        
        return response()->json([
            'success' => 1,
            'data'    => $sellerRequestsArray,
        ], 200);
    }
    
    public function editSellerRequest(Request $request){
        
        $id           = request('id');
        $amenities    = request('amenities');
        $parkings     = request('parkings');
        $heatingFuels = request('heating_fuels');
        $typeOfHouse  = request('type_of_house');
        
        if($amenities) {
            $amenities = explode(",", $amenities);
        }
        
        if($parkings){
            $parkings = explode(",", $parkings);
        }
        
        if($heatingFuels){
            $heatingFuels = explode(",", $heatingFuels);
        }
        
        if($typeOfHouse){
            $typeOfHouse = explode(",", $typeOfHouse);
        }
        
        $sellerRequest                           = SellerRequest::select('id', 'province', 'region', 'city', 'sell_price', 'sell_price_tag', 'bedrooms', 'bathrooms', 'type_of_house', 'heating_fuel', 'amenities', 'build', 'age_property', 'sqft_property', 'parking', 'preferred_neighbourhoods', 'other_request', 'senior_community','suite', 'suite_option', 'buying_new_home', 'already_buy_request', 'currently_listed_realtor')->where('id', $id)->first();
        $sellerRequest->province                 = request('province');
        $sellerRequest->region                   = request('region');
        $sellerRequest->city                     = request('city');
        $sellerRequest->sell_price               = request('sell_price');
        $sellerRequest->sell_price_tag           = request('sell_price_tag');
        $sellerRequest->bedrooms                 = request('bedrooms');
        $sellerRequest->bathrooms                = request('bathrooms');
        $sellerRequest->type_of_house            = $typeOfHouse;
        $sellerRequest->heating_fuel             = $heatingFuels;
        $sellerRequest->amenities                = $amenities;
        $sellerRequest->build                    = request('build');
        $sellerRequest->age_property             = request('age_property');
        $sellerRequest->sqft_property            = request('sqft_property');
        $sellerRequest->building_area_tag        = request('building_area_tag');
        $sellerRequest->parking                  = $parkings;
        $sellerRequest->preferred_neighbourhoods = request('preferred_neighbourhoods');
        $sellerRequest->other_request            = request('other_request');
        $sellerRequest->senior_community         = request('senior_community');
        $sellerRequest->suite                    = request('suite');
        $sellerRequest->suite_option             = request('suite_option');
        $sellerRequest->buying_new_home          = request('buying_new_home');
        $sellerRequest->already_buy_request      = request('already_buy_request');
        $sellerRequest->currently_listed_realtor = request('currently_listed_realtor');
        $sellerRequest->save();
        
        $userId = auth()->user()->id;
        $images = request('images');
        $images = json_decode($images, true);


        if($images){
            foreach($images as $key => $image){
                $base64         = $image['base64'];
                $imageId        = $image['id'];
                $type           = $image['type'];
                $actualFilename = $image['filename'];
                $url            = $image['url'];
                
                if($type == 'old'){
                    
                }else if($type == 'new'){
                    
                    $customFilename = time() . "_" . str_replace(" ","_",$actualFilename);
                    
                    $newDir  = storage_path('request_images/'.$userId.'/'.$sellerRequest->id);
                    if (!file_exists($newDir)) {
                        mkdir($newDir, 0777, true);
                    }
                    
                    $savePath = $newDir.'/'.$customFilename;
                    file_put_contents($savePath, base64_decode($base64));
                    
                    $requestImage                 = new RequestImage();
                    $requestImage->request_id     = $sellerRequest->id;
                    $requestImage->filename       = $customFilename;
                    $requestImage->real_filename  = $actualFilename;
                    $requestImage->sorting        = $key;
                    $requestImage->type           = 'sell';
                    $requestImage->save();
                    
                }else{
                    $requestImage = RequestImage::select('id')->where('id',$imageId)->delete();
                    if($requestImage){
                        $path = storage_path('request_images/'.$userId.'/'.$sellerRequest->id);
                        \File::delete($path);
                    }
                }
            }
        }
        
        
        $imageArray = [];
            $requestImages = RequestImage::where('request_id',$sellerRequest->id)->where('type','sell')->orderBy('sorting','asc')->get();
            foreach($requestImages as $requestImage){
                $data = [
                    'id'     => $requestImage->id,
                    'image'  => url('storage/request_images/'.$sellerRequest->user_id.'/'.$requestImage->request_id.'/'.$requestImage->filename)
                ];
                $imageArray[] = $data;
        }
        
        $data = [
                'id'                       => $sellerRequest->id,
                'province'                 => $sellerRequest->province,
                'region'                   => $sellerRequest->region,
                'city'                     => $sellerRequest->city,
                'sell_price'               => $sellerRequest->sell_price,
                'sell_price_tag'           => $sellerRequest->sell_price_tag,
                'bedrooms'                 => $sellerRequest->bedrooms,
                'bathrooms'                => $sellerRequest->bathrooms,
                'type_of_house'            => $sellerRequest->type_of_house,
                'heatingFuels'             => $sellerRequest->heating_fuel,
                'amenities'                => $sellerRequest->amenities,
                'build'                    => $sellerRequest->build,
                'age_property'             => $sellerRequest->age_property,
                'sqft_property'            => $sellerRequest->sqft_property,
                'parkings'                 => $sellerRequest->parking,
                'preferred_neighbourhoods' => $sellerRequest->preferred_neighbourhoods,
                'other_request'            => $sellerRequest->other_request,
                'senior_community'         => $sellerRequest->senior_community,
                'image_array'              => $imageArray,
                'suite'                    => $sellerRequest->suite,
                'suite_option'             => $sellerRequest->suite_option,
                'buying_new_home'          => $sellerRequest->buying_new_home,
                'already_buy_request'      => $sellerRequest->already_buy_request,
                'currently_listed_realtor' => $sellerRequest->currently_listed_realtor,
                'building_area_tag'        => $sellerRequest->building_area_tag,
            ];
        
        return response()->json([
            'success' => 1,
            'data'    => (object)$data,
            'message' => 'Seller Request Successfully Updated.'
        ], 200);
        
    }
    
    public function deleteSellerRequest(Request $request){
        $id  = request('id');
        SellerRequest::select('id')->where('id', $id)->delete();
        
        UserRejectRequest::select('id')->where('request_id', $id)->where('request_type', 'sell')->delete();
        MessageThread::select('id')->where('request_id', $id)->where('request_type', 'sell')->delete();
        
        return response()->json([
            'success' => 1,
            'message' => 'Seller Request Successfully Deleted.'
        ], 200);
    }  
    
    
    public function getSellerDetails(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','sell')->where('request_id',$id)->count();
        }else{
            
            $rejectListArray = UserRejectRequest::select('user_id')->where('request_type', 'sell')->where('request_id', $id)->pluck('user_id')->all();
            
            $totalMessages = MessageThread::select('id')->where('request_user_id',auth()->user()->id)->where('request_type','sell')->whereNotIn('realtor_user_id', $rejectListArray)->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','sell')->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','sell')->where('request_id',$id)->first();
                $messageThreadId = $messageThreadId->id;
            }
        }
            
        $sellerRequest = SellerRequest::select('id', 'user_id', 'province', 'region', 'city', 'sell_price', 'sell_price_tag', 'bedrooms', 'bathrooms', 'type_of_house', 'heating_fuel', 'amenities','build', 'age_property', 'sqft_property', 'parking', 'preferred_neighbourhoods', 'other_request', 'senior_community', 'suite', 'suite_option', 'buying_new_home', 'already_buy_request', 'currently_listed_realtor', 'building_area_tag')->where('id', $id)->first();
        
        $imageArray = [];
        $requestImages = RequestImage::where('request_id',$sellerRequest->id)->where('type','sell')->orderBy('sorting','asc')->get();
        foreach($requestImages as $requestImage){
            $data = [
                'id'     => $requestImage->id,
                'image'  => url('storage/request_images/'.$sellerRequest->user_id.'/'.$requestImage->request_id.'/'.$requestImage->filename)
            ];
            $imageArray[] = $data;
        }
        
        return response()->json([
            'success' => 1,
            'id'                       => $sellerRequest->id,
            'name'                     => $sellerRequest->user_id ? $sellerRequest->users->name: '',
            'user_name'                => $sellerRequest->user_id ? $sellerRequest->users->user_name: '',
            'user_id'                  => $sellerRequest->user_id,
            'province'                 => $sellerRequest->province,
            'region'                   => $sellerRequest->region,
            'city'                     => $sellerRequest->city,
            'sell_price'               => $sellerRequest->sell_price,
            'sell_price_tag'           => $sellerRequest->sell_price_tag,
            'bedrooms'                 => $sellerRequest->bedrooms,
            'bathrooms'                => $sellerRequest->bathrooms,
            'type_of_house'            => json_decode($sellerRequest->type_of_house),
            'heatingFuels'             => json_decode($sellerRequest->heating_fuel),
            'amenities'                => json_decode($sellerRequest->amenities),
            'build'                    => $sellerRequest->build,
            'age_property'             => $sellerRequest->age_property,
            'sqft_property'            => $sellerRequest->sqft_property,
            'parkings'                 => json_decode($sellerRequest->parking),
            'preferred_neighbourhoods' => $sellerRequest->preferred_neighbourhoods,
            'other_request'            => $sellerRequest->other_request,
            'notification'             => $totalMessages,
            'total_realtor'            => $totalRealtor,
            'message_thread_id'        => $messageThreadId,
            'image_array'              => $imageArray,
            'senior_community'         => $sellerRequest->senior_community,
            'suite'                    => $sellerRequest->suite,
            'suite_option'             => $sellerRequest->suite_option,
            'buying_new_home'          => $sellerRequest->buying_new_home,
            'already_buy_request'      => $sellerRequest->already_buy_request,
            'currently_listed_realtor' => $sellerRequest->currently_listed_realtor,
            'building_area_tag'        => $sellerRequest->building_area_tag
        ], 200); 
    }
}