<?php

namespace App\Console\Commands;

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

class CleanupESP32CamImages extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'esp32cam:cleanup {--days=7 : Number of days to keep images} {--keep=10 : Minimum number of images to keep}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Cleanup old ESP32-CAM images';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        try {
            $uploadDir = 'esp32cam/';
            $files = Storage::disk('public')->files($uploadDir);
            $deletedCount = 0;
            
            $daysToKeep = (int) $this->option('days');
            $minFilesToKeep = (int) $this->option('keep');
            
            $this->info("Membersihkan foto lama dari ESP32-CAM...");
            $this->info("Menyimpan foto dari {$daysToKeep} hari terakhir, minimal {$minFilesToKeep} foto");
            
            // Hapus file yang lebih lama dari N hari, tapi simpan minimal X file terakhir
            if (count($files) > $minFilesToKeep) {
                // Urutkan file berdasarkan waktu modifikasi (terlama lebih dulu)
                usort($files, function($a, $b) {
                    return Storage::disk('public')->lastModified($a) - Storage::disk('public')->lastModified($b);
                });
                
                // Ambil file lama untuk dihapus (tapi sisakan X file terakhir)
                $filesToDelete = array_slice($files, 0, count($files) - $minFilesToKeep);
                
                foreach ($filesToDelete as $file) {
                    $fileTime = Storage::disk('public')->lastModified($file);
                    if (time() - $fileTime > $daysToKeep * 24 * 60 * 60) { // N hari dalam detik
                        Storage::disk('public')->delete($file);
                        $this->line("Menghapus: " . basename($file));
                        Log::info("Deleted old ESP32-CAM image: " . $file);
                        $deletedCount++;
                    }
                }
            }
            
            $this->info("Selesai. {$deletedCount} foto lama telah dihapus.");
            $this->info("Sisa foto: " . (count($files) - $deletedCount));
            
            return 0;
            
        } catch (\Exception $e) {
            $this->error("ESP32-CAM cleanup error: " . $e->getMessage());
            Log::error("ESP32-CAM cleanup error: " . $e->getMessage());
            return 1;
        }
    }
} 