<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Appointments;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

class CloseExpiredAppointments extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'appointments:close-expired';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Cierra automáticamente todas las citas que ya pasaron de su fecha';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->info('Iniciando cierre de citas expiradas...');
        
        try {
            $today = Carbon::now();
            $this->info('Fecha actual: ' . $today->format('Y-m-d H:i:s'));

            // Buscar citas activas con fecha anterior a hoy
            $expiredAppointments = Appointments::where('active', 1)
                ->where('deleted', 0)
                ->where('date', '<', $today)
                ->get();

            $count = $expiredAppointments->count();
            $this->info("Se encontraron {$count} citas expiradas para cerrar.");

            if ($count > 0) {
                DB::beginTransaction();
                try {
                    // Actualizar todas las citas encontradas
                    foreach ($expiredAppointments as $appointment) {
                        $this->info("Cerrando cita ID: {$appointment->id}, Código: {$appointment->code}, Fecha: " . 
                                    Carbon::parse($appointment->date)->format('d/m/Y H:i'));
                        
                        $appointment->active = 0;
                        $appointment->save();
                    }
                    
                    DB::commit();
                    $this->info("Se cerraron {$count} citas con éxito.");
                    Log::info("Cron de cierre de citas: Se cerraron {$count} citas expiradas.");
                } catch (\Exception $e) {
                    DB::rollBack();
                    $this->error('Error al cerrar citas: ' . $e->getMessage());
                    Log::error('Error en cron de cierre de citas: ' . $e->getMessage());
                    return 1;
                }
            } else {
                $this->info('No hay citas expiradas para cerrar.');
                Log::info('Cron de cierre de citas: No se encontraron citas expiradas.');
            }
            
            return 0;
        } catch (\Exception $e) {
            $this->error('Error general en el comando: ' . $e->getMessage());
            Log::error('Error general en cron de cierre de citas: ' . $e->getMessage());
            return 1;
        }
    }
}
