<?php

namespace App\Console\Commands;

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

class FetchESP32CamImage extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'esp32cam:fetch {ip? : IP address of ESP32-CAM web server}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Fetch image from ESP32-CAM web server and save it to storage';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        try {
            // Ambil IP dari argumen command atau gunakan default
            $cameraIp = $this->argument('ip');
            
            if (empty($cameraIp)) {
                $this->error('IP address ESP32-CAM diperlukan');
                return 1;
            }
            
            $this->info("Menghubungi ESP32-CAM di {$cameraIp}...");
            
            // URL untuk mengambil gambar dari ESP32-CAM
            $captureUrl = "http://{$cameraIp}/capture";
            
            // Ambil gambar dari ESP32-CAM dengan timeout yang lebih lama
            $response = Http::timeout(30)->get($captureUrl);
            
            if ($response->successful()) {
                // Direktori untuk menyimpan gambar
                $uploadDir = 'esp32cam/';
                
                // Pastikan direktori ada di storage/app/public
                if (!Storage::disk('public')->exists($uploadDir)) {
                    Storage::disk('public')->makeDirectory($uploadDir);
                }
                
                // Buat nama file unik dengan timestamp
                $filename = 'esp32cam_' . Carbon::now()->format('Ymd_His') . '.jpg';
                $fullPath = $uploadDir . $filename;
                
                // Simpan gambar menggunakan Laravel Storage
                Storage::disk('public')->put($fullPath, $response->body());
                
                // Log informasi
                $fileSize = strlen($response->body());
                $this->info("Gambar berhasil diambil dari ESP32-CAM ({$fileSize} bytes)");
                $this->info("Tersimpan sebagai: {$fullPath}");
                
                Log::info("ESP32-CAM image fetched successfully via command", [
                    'camera_ip' => $cameraIp,
                    'filename' => $filename,
                    'path' => $fullPath,
                    'size' => $fileSize . ' bytes',
                    'time' => Carbon::now()->format('Y-m-d H:i:s')
                ]);
                
                return 0;
            }
            
            $this->error("Gagal mengambil gambar dari ESP32-CAM. Status: " . $response->status());
            Log::error("ESP32-CAM fetch error: Failed with status " . $response->status());
            return 1;
            
        } catch (\Exception $e) {
            $this->error("ESP32-CAM fetch error: " . $e->getMessage());
            Log::error("ESP32-CAM fetch error: " . $e->getMessage());
            return 1;
        }
    }
} 