<?php

namespace App\Console\Commands;

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

class ClearOldLogs extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'log:clear {--keep=14 : Days of logs to keep}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Clear old log files, keeping only the specified number of days';

    /**
     * Execute the console command.
     */
    public function handle(): int
    {
        $daysToKeep = (int) $this->option('keep');
        $logPath = storage_path('logs');
        $deletedCount = 0;

        if (!File::isDirectory($logPath)) {
            $this->info('Log directory does not exist.');
            return Command::SUCCESS;
        }

        $files = File::files($logPath);
        $cutoffDate = Carbon::now()->subDays($daysToKeep);

        foreach ($files as $file) {
            // Skip non-log files
            if ($file->getExtension() !== 'log') {
                continue;
            }

            // Keep the main laravel.log file if it's recent
            $lastModified = Carbon::createFromTimestamp($file->getMTime());
            
            if ($lastModified->lt($cutoffDate)) {
                File::delete($file->getPathname());
                $this->line("Deleted: {$file->getFilename()}");
                $deletedCount++;
            }
        }

        $this->info("Cleaned up {$deletedCount} old log files (keeping last {$daysToKeep} days).");

        return Command::SUCCESS;
    }
}
