<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class CleanLogs extends Command
{
	protected $signature = 'app:clean-logs {--days=14 : So ngay giu lai log}';

	protected $description = 'Xoa cac file log cu trong storage/logs';

	public function handle(): int
	{
		$days = (int) $this->option('days');
		if ($days < 1) {
			$this->error('Gia tri --days phai lon hon hoac bang 1');
			return self::INVALID;
		}

		$logDir = storage_path('logs');
		if (!is_dir($logDir)) {
			$this->warn('Khong tim thay thu muc log');
			return self::SUCCESS;
		}

		$threshold = time() - ($days * 86400);
		$deleted = 0;
		$skipped = 0;

		$files = scandir($logDir) ?: [];
		foreach ($files as $file) {
			if ($file === '.' || $file === '..') {
				continue;
			}

			$path = $logDir . DIRECTORY_SEPARATOR . $file;
			if (!is_file($path)) {
				continue;
			}

			if (pathinfo($path, PATHINFO_EXTENSION) !== 'log') {
				continue;
			}

			$mtime = @filemtime($path);
			if ($mtime === false || $mtime >= $threshold) {
				$skipped++;
				continue;
			}

			if (@unlink($path)) {
				$deleted++;
			} else {
				$this->warn('Khong the xoa file: ' . $file);
			}
		}

		$this->info('Da xoa ' . $deleted . ' file log cu.');
		$this->line('Da bo qua ' . $skipped . ' file moi hoac khong hop le.');

		return self::SUCCESS;
	}
}
