<?php

namespace App\Console\Commands;

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

class CleanTempQrImages extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cleanup:temp-qr';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Delete old temporary QR images (older than 1 hour)';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $path = storage_path('app/temp');

        if (!File::exists($path)) {
            $this->info('Temp directory does not exist.');
            return Command::SUCCESS;
        }

        $files = File::files($path);
        $now = Carbon::now();
        $deletedCount = 0;

        foreach ($files as $file) {
            try {
                $fileAgeMinutes = $now->diffInMinutes(Carbon::createFromTimestamp($file->getMTime()));

                if ($fileAgeMinutes > 120) {
                    File::delete($file->getRealPath());
                    $deletedCount++;
                }
            } catch (\Exception $e) {
                $this->error("❌ Failed to delete {$file->getFilename()}: " . $e->getMessage());
            }
        }

        if ($deletedCount > 0) {
            $this->info("✅ Deleted {$deletedCount} old QR image(s).");
        } else {
            $this->info("ℹ️ No old QR images found to delete.");
        }

        return Command::SUCCESS;
    }
}
