<?php

namespace App\Console\Commands;

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

class CleanupLedgerPDFs extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'pdf:cleanup-ledgers {--days=1 : Number of days to keep files} {--force : Force cleanup without confirmation}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Clean up old ledger statement PDF files';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $daysToKeep = $this->option('days');
        $force = $this->option('force');
        
        $this->info("Starting PDF cleanup process...");
        $this->info("Files older than {$daysToKeep} day(s) will be deleted.");
        
        $path = 'exports/ledger-statements';
        
        // Check if directory exists
        if (!Storage::exists($path)) {
            $this->warn("Directory '{$path}' does not exist.");
            return Command::SUCCESS;
        }
        
        // Get all PDF files
        $files = Storage::files($path);
        
        if (empty($files)) {
            $this->info("No files found in '{$path}'.");
            return Command::SUCCESS;
        }
        
        $cutoffTime = Carbon::now()->subDays($daysToKeep);
        $filesToDelete = [];
        $totalSize = 0;
        
        // Filter files older than cutoff time
        foreach ($files as $file) {
            $lastModified = Carbon::createFromTimestamp(Storage::lastModified($file));
            
            if ($lastModified->lt($cutoffTime)) {
                $fileSize = Storage::size($file);
                $filesToDelete[] = [
                    'path' => $file,
                    'name' => basename($file),
                    'size' => $fileSize,
                    'modified' => $lastModified->format('Y-m-d H:i:s')
                ];
                $totalSize += $fileSize;
            }
        }
        
        if (empty($filesToDelete)) {
            $this->info("No files to delete. All files are within the retention period.");
            return Command::SUCCESS;
        }
        
        // Display files to be deleted
        $this->newLine();
        $this->warn("Found " . count($filesToDelete) . " file(s) to delete:");
        $this->newLine();
        
        $headers = ['Filename', 'Size', 'Last Modified'];
        $rows = [];
        
        foreach ($filesToDelete as $file) {
            $rows[] = [
                $file['name'],
                $this->formatBytes($file['size']),
                $file['modified']
            ];
        }
        
        $this->table($headers, $rows);
        $this->info("Total size to be freed: " . $this->formatBytes($totalSize));
        $this->newLine();
        
        // Confirm deletion unless --force is used
        if (!$force) {
            if (!$this->confirm('Do you want to proceed with deletion?', false)) {
                $this->info('Cleanup cancelled.');
                return Command::SUCCESS;
            }
        }
        
        // Delete files
        $deletedCount = 0;
        $deletedSize = 0;
        $errors = [];
        
        $this->info('Deleting files...');
        $progressBar = $this->output->createProgressBar(count($filesToDelete));
        $progressBar->start();
        
        foreach ($filesToDelete as $file) {
            try {
                if (Storage::delete($file['path'])) {
                    $deletedCount++;
                    $deletedSize += $file['size'];
                } else {
                    $errors[] = "Failed to delete: " . $file['name'];
                }
            } catch (\Exception $e) {
                $errors[] = "Error deleting " . $file['name'] . ": " . $e->getMessage();
            }
            $progressBar->advance();
        }
        
        $progressBar->finish();
        $this->newLine(2);
        
        // Summary
        $this->info("✓ Cleanup completed!");
        $this->info("Files deleted: {$deletedCount} / " . count($filesToDelete));
        $this->info("Space freed: " . $this->formatBytes($deletedSize));
        
        if (!empty($errors)) {
            $this->newLine();
            $this->error("Errors encountered:");
            foreach ($errors as $error) {
                $this->error("  - " . $error);
            }
        }
        
        // Log the cleanup
        \Log::info("PDF Cleanup completed", [
            'files_deleted' => $deletedCount,
            'space_freed' => $deletedSize,
            'retention_days' => $daysToKeep,
            'errors' => count($errors)
        ]);
        
        return Command::SUCCESS;
    }
    
    /**
     * Format bytes to human readable format
     */
    private function formatBytes($bytes, $precision = 2)
    {
        $units = ['B', 'KB', 'MB', 'GB', 'TB'];
        
        for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) {
            $bytes /= 1024;
        }
        
        return round($bytes, $precision) . ' ' . $units[$i];
    }
}