<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

class RunScheduledTasks extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'tasks:run-scheduled';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Run scheduled tasks for publishing events and releasing seats';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->info('Running scheduled tasks...');
  
        // Run releasSeats
        $this->info('Running releasSeats...');
        $this->releasSeats();
        
        $this->info('All scheduled tasks completed successfully!');
        
        return 0;
    }
    
   
    
    /**
     * Release seats
     *
     * @return void
     */
    public function releasSeats() 
    {
        try {
            $failedCount = 0;
            $seatCount = 0;
            
            DB::table('failed_bookings')->where('seats', '<>', 'null')->where(['success' => 0, 'failed' => 0])->lazyById()->each(function ($booking) use (&$failedCount) {
                
                if(Carbon::now()->format('Y-m-d H:i') > Carbon::parse($booking->created_at)->addMinutes(10)->format('Y-m-d H:i')) {
                    DB::table('failed_bookings')
                    ->where('id', $booking->id)
                    ->update(['failed' => 1 ]);
                    $failedCount++;
                }

            }); 

            DB::table('seat_statuses')->lazyById()->each(function ($seat) use (&$seatCount) {
                
                if(Carbon::now()->format('Y-m-d H:i') > Carbon::parse($seat->updated_at)->addMinutes(10)->format('Y-m-d H:i')) {
                    DB::table('seat_statuses')
                    ->where('id', $seat->id)
                    ->delete();
                    $seatCount++;
                }

            }); 
            
            if ($failedCount > 0) {
                $this->info("✅ Marked {$failedCount} failed bookings");
            }
            
            if ($seatCount > 0) {
                $this->info("✅ Released {$seatCount} seat reservations");
            }
            
            if ($failedCount == 0 && $seatCount == 0) {
                $this->info("ℹ️ No seats or bookings to release");
            }
            
        } catch(\Throwable $th) {
            $this->error("❌ Error in releasSeats: " . $th->getMessage());
        }
    }
} 