<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\Booking;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use App\Services\NotificationService;
use App\Services\StripeService;

class CancelUnacceptedRides implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     */
    public function __construct()
    {
        // 
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    { 
        
           $notificationService = app(NotificationService::class);
           
           $stripeService = app(StripeService::class);
           
            Log::info("in unaccepted booking");
        // //get pending bookings not accept over 30 mins 
        // $bookings = Booking::where('status', Booking::STATUS_PENDING)
        // ->where('pickup_date', '=', date('Y-m-d'))
        // ->where('pickup_time', '<', Carbon::now()->subMinutes(30)->format('Y-m-d H:i:s'))
        // ->get();
        
        // // Log::info($bookings);
        
        // if($bookings->isNotEmpty()){
            
        //     foreach($bookings as $booking){
        //         $booking->update(['status' => Booking::STATUS_CANCELED]);
        //         // Log::info("in update status");
        //         //initiate refund 
        //     }
            
        // }
        
         // Get bookings that are still pending and have a pickup date of today
            $bookings = Booking::where('status', Booking::STATUS_PENDING)
                ->where('pickup_date', '=', date('Y-m-d'))
                ->get();
        
            foreach ($bookings as $booking) {
                // Combine pickup_date and pickup_time into a single Carbon instance
                $pickupDateTime = Carbon::parse("{$booking->pickup_date} {$booking->pickup_time}");
                $currentTime = Carbon::now();
        
                // Check if the booking is still pending and the pickup  time is exactly 5 minutes from now
                if ($currentTime->diffInMinutes($pickupDateTime, false) == 5) { // Ensure comparison is forward-looking with `false`
                    // Send a notification to the user before canceling
                    // $user = $booking->user; 
                       
                try {
                    $notification = [
                                    "receiverID"=> $booking->rider_id,
                                    "booking_id" =>$booking->id,
                                    "title" => "Booking Not Accepted Yet",
                                    "message"=>'Your booking "#' . $booking->booking_id . '" has not been accepted yet. We are trying to connect with drivers.',
                                    "type"=>"message"
                                  ];
                                  
                                  
                        Log::info($notification);
                        // $notify= parent::sendNotification($notification);
                        // $response = $this->notificationService->sendNotification($notification);
                        $response = $notificationService->sendNotification($notification,true);
                        
                        
                            // return response()->json($response);
    
                         $booking->update(['unaccepted_notify' => 1]);
                          
                     } catch (\Exception $e) {
                       
                        //  error_log($e->getMessage()); 
                          Log::info("error in notification ",$e->getMessage());
                    }    
                    Log::info("5 min left",$response);
                   
                }
        
                // If current time has passed the pickup time and no one accepted, cancel the booking
                if ($pickupDateTime->isPast() && $booking->status == Booking::STATUS_PENDING) {
                     
                     
                    $cancelHoldPayment =  $stripeService->CancelPaymentIntent($booking->payment_id);
                     
                       if($cancelHoldPayment['success'] == 1){
                             try {
                                    
                                 $cancelNotification = [
                                            "receiverID"=>$booking->rider_id,
                                            "booking_id" =>$booking->id,
                                            "title" => "Booking Cancelled Automatically.",
                                            "message"=>'Your booking "#' . $booking->booking_id . '" has been cancelled. Unable to find driver.',
                                            "type"=>"message"
                                          ];
                                
                                $response = $notificationService->sendNotification($cancelNotification,true);   
                             
                                 
                             } catch (\Exception $e) {
                                error_log($e->getMessage()); 
                            }  
                            
                              $booking->update(['status' => Booking::STATUS_CANCELED]);
                       }
                   
                    
                  
                     Log::info("time over");
                    // Optionally, initiate a refund process here
                }
            }
    }
}
