<?php

namespace App\Jobs;

use App\Models\{Trip};
use App\Notifications\Api\App\AutoCancelTripNotification;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

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

    public $trip_id;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($trip_id)
    {
        $this->trip_id = $trip_id;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $trip = Trip::where('status', 'pending')
            ->where('created_at', '<=', now()->subMinutes(setting('waiting_time_to_Start') ?? 10))
            ->find($this->trip_id);

        if ($trip) {
            $trip->update([
                'status'       => 'auto_canceled',
                'status_times' => ['auto_canceled' => now()]
            ]);

            $trip->scooter->update(['in_order' => false]);
            $trip->coupon()->decrement('users_used_count');

            $trip->user->notify(new AutoCancelTripNotification($trip->id, ['database', 'fcm']));
        }
    }
}
