<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;

class CleanupOldExcelFiles extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'excel:cleanup {--days=30 : Number of days to keep files}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Cleanup uploaded Excel files older than specified days (default: 30 days)';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $days = (int) $this->option('days');
        $this->info("Starting cleanup of Excel files older than {$days} days...");
        
        $disk = Storage::disk('public');
        $basePath = 'uploads/excel';
        
        if (!$disk->exists($basePath)) {
            $this->warn("Upload directory does not exist: {$basePath}");
            return 0;
        }
        
        $cutoffDate = Carbon::now()->subDays($days);
        $deletedCount = 0;
        $deletedSize = 0;
        $errors = [];
        
        // Get all year directories
        $years = $disk->directories($basePath);
        
        foreach ($years as $yearPath) {
            // Get all month directories in this year
            $months = $disk->directories($yearPath);
            
            foreach ($months as $monthPath) {
                // Get all files in this month directory
                $files = $disk->files($monthPath);
                
                foreach ($files as $file) {
                    try {
                        $lastModified = $disk->lastModified($file);
                        $fileDate = Carbon::createFromTimestamp($lastModified);
                        
                        if ($fileDate->lt($cutoffDate)) {
                            $fileSize = $disk->size($file);
                            
                            if ($disk->delete($file)) {
                                $deletedCount++;
                                $deletedSize += $fileSize;
                                
                                $this->line("Deleted: {$file} (Modified: {$fileDate->format('Y-m-d H:i:s')})");
                            }
                        }
                    } catch (\Exception $e) {
                        $errors[] = [
                            'file' => $file,
                            'error' => $e->getMessage()
                        ];
                        $this->error("Error deleting {$file}: " . $e->getMessage());
                    }
                }
                
                // Delete empty month directories
                if (empty($disk->files($monthPath)) && empty($disk->directories($monthPath))) {
                    $disk->deleteDirectory($monthPath);
                    $this->line("Deleted empty directory: {$monthPath}");
                }
            }
            
            // Delete empty year directories
            if (empty($disk->files($yearPath)) && empty($disk->directories($yearPath))) {
                $disk->deleteDirectory($yearPath);
                $this->line("Deleted empty directory: {$yearPath}");
            }
        }
        
        // Log results
        $deletedSizeMB = round($deletedSize / 1024 / 1024, 2);
        
        Log::info('Excel files cleanup completed', [
            'deleted_count' => $deletedCount,
            'deleted_size_mb' => $deletedSizeMB,
            'cutoff_date' => $cutoffDate->format('Y-m-d H:i:s'),
            'retention_days' => $days,
            'errors_count' => count($errors)
        ]);
        
        if (count($errors) > 0) {
            Log::warning('Excel cleanup errors', ['errors' => $errors]);
        }
        
        $this->info("\nCleanup completed!");
        $this->info("Files deleted: {$deletedCount}");
        $this->info("Space freed: {$deletedSizeMB} MB");
        
        if (count($errors) > 0) {
            $this->warn("Errors encountered: " . count($errors));
        }
        
        return 0;
    }
}
