<?php

namespace App\Console\Commands;

use App\Models\PaymentProcess;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class ImportMecaprogramsPaymentProcess extends Command
{
    protected $signature = 'mecaprograms:import-payment-process
        {--dry-run : Print what would be imported without saving}';

    protected $description = 'Import Payment Process section image from mecaprograms.com homepage';

    protected string $baseUrl = 'https://mecaprograms.com';

    public function handle(): int
    {
        ini_set('memory_limit', '512M');
        $this->info('Fetching mecaprograms.com homepage...');

        $response = Http::withOptions(['verify' => false])
            ->withHeaders(['User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'])
            ->timeout(30)
            ->get($this->baseUrl);

        if (!$response->successful()) {
            $this->error("Failed to fetch homepage (HTTP {$response->status()})");
            return Command::FAILURE;
        }

        $html = $response->body();

        $desktopUrl = null;
        $mobileUrl = null;

        if (preg_match('/PAYMENT PROCESS.*?<picture>.*?<source[^>]*srcset="([^"]+)"[^>]*>.*?<img[^>]*src="([^"]+)"[^>]*>.*?<\/picture>/si', $html, $m)) {
            $mobileUrl = trim($m[1]);
            $desktopUrl = trim($m[2]);
        } elseif (preg_match('/PAYMENT PROCESS.*?<img[^>]*src="([^"]+)"[^>]*>/si', $html, $m2)) {
            $desktopUrl = trim($m2[1]);
        }

        if (!$desktopUrl) {
            $this->warn('Could not locate PAYMENT PROCESS section images in homepage HTML.');
            return Command::SUCCESS;
        }

        $this->info("Found desktop image: $desktopUrl");
        if ($mobileUrl) {
            $this->info("Found mobile image: $mobileUrl");
        }

        $desktopFile = $this->downloadImage($desktopUrl);
        $mobileFile = $mobileUrl ? $this->downloadImage($mobileUrl) : null;

        if ($this->option('dry-run')) {
            $this->line('Would import payment process images.');
            if ($desktopFile) Storage::disk('public')->delete("payment-process/{$desktopFile}");
            if ($mobileFile) Storage::disk('public')->delete("payment-process/{$mobileFile}");
            return Command::SUCCESS;
        }

        PaymentProcess::query()->update(['is_active' => false]);

        PaymentProcess::create([
            'title' => 'Payment Process',
            'image_desktop' => $desktopFile ? "payment-process/{$desktopFile}" : null,
            'image_mobile' => $mobileFile ? "payment-process/{$mobileFile}" : null,
            'is_active' => true,
        ]);

        $this->info('Payment Process imported successfully.');

        return Command::SUCCESS;
    }

    protected function downloadImage(string $url): ?string
    {
        try {
            $response = Http::withOptions(['verify' => false])
                ->withHeaders(['User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'])
                ->timeout(60)
                ->get($url);

            if (!$response->successful()) {
                $this->warn("    Failed to download image (HTTP {$response->status()})");
                return null;
            }

            $extension = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION) ?: 'webp';
            $filename = Str::random(40) . '.' . $extension;

            if (!Storage::disk('public')->exists('payment-process')) {
                Storage::disk('public')->makeDirectory('payment-process');
            }

            Storage::disk('public')->put("payment-process/{$filename}", $response->body());

            return $filename;

        } catch (\Exception $e) {
            $this->warn("    Error downloading image: {$e->getMessage()}");
            return null;
        }
    }
}
