<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class SystemClearJunks extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'system:clear-junks';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Clears all system junks including cache, logs, and views to free up space.';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info("Starting system cleanup...");

        // Clear view cache
        \Illuminate\Support\Facades\Artisan::call('view:clear');
        $this->info("View cache cleared.");

        // Clear log files older than 30 days
        $logPath = storage_path('logs');
        $files = glob($logPath . '/*.log');
        $deletedLogs = 0;
        foreach ($files as $file) {
            if (is_file($file)) {
                // Delete if older than 30 days
                if (time() - filemtime($file) >= 60 * 60 * 24 * 30) {
                    unlink($file);
                    $deletedLogs++;
                }
            }
        }
        $this->info("Deleted {$deletedLogs} old log files.");

        // Clear temporary uploads / cache if needed
        // ...

        $this->info("System junk cleared successfully.");
        return Command::SUCCESS;
    }
}
