<?php

namespace App\Console\Commands;

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

class ImportMecaprogramsPaymentMethods extends Command
{
    protected $signature = 'mecaprograms:import-payment-methods
        {--delay=300 : Milliseconds between requests}
        {--dry-run : Print what would be imported without saving}';

    protected $description = 'Import payment methods from mecaprograms.com homepage footer';

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

    protected array $filenameToName = [
        'paypal' => 'PayPal',
        'tether' => 'Tether (USDT)',
        'bitcoin' => 'Bitcoin',
        'ethereum' => 'Ethereum',
        'zelle' => 'Zelle',
        'western-union' => 'Western Union',
        'money-gram' => 'MoneyGram',
        'visa' => 'Visa',
        'remitly' => 'Remitly',
    ];

    protected int $imported = 0;
    protected int $skipped = 0;

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

        $html = $this->fetchHomepage();
        if (!$html) {
            return Command::FAILURE;
        }

        $methods = $this->parsePaymentMethods($html);
        $this->info('Found ' . count($methods) . ' payment method(s) on homepage');

        if (empty($methods)) {
            $this->warn('No payment methods found to import.');
            return Command::SUCCESS;
        }

        $this->newLine();
        $this->info('Processing payment methods...');

        foreach ($methods as $index => $method) {
            $this->importPaymentMethod($method, $index);
            usleep((int) $this->option('delay') * 1000);
        }

        $this->newLine();
        $this->table(
            ['Imported', 'Skipped'],
            [[$this->imported, $this->skipped]]
        );

        return Command::SUCCESS;
    }

    protected function fetchHomepage(): ?string
    {
        $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 null;
        }

        return $response->body();
    }

    protected function parsePaymentMethods(string $html): array
    {
        $methods = [];

        if (!preg_match('/<h2[^>]*>PAYMENT PROCESS\s*<\/h2>/i', $html, $sectionMatch)) {
            $this->warn('Could not locate PAYMENT PROCESS section in homepage HTML.');
            return [];
        }

        preg_match_all(
            '/<img[^>]*src="[^"]*\/storage\/images\/([a-z-]+)\.png[^"]*"[^>]*>/i',
            $html,
            $matches
        );

        $seen = [];

        foreach ($matches[1] as $filename) {
            if (isset($seen[$filename])) {
                continue;
            }
            $seen[$filename] = true;

            $name = $this->filenameToName[$filename] ?? Str::of($filename)->replace('-', ' ')->title();
            $slug = $filename;

            $methods[] = [
                'name' => $name,
                'slug' => $slug,
            ];
        }

        return $methods;
    }

    protected function importPaymentMethod(array $data, int $index): void
    {
        $this->line("  Processing: {$data['name']}");

        $existing = PaymentMethod::where('slug', $data['slug'])->first();
        if ($existing) {
            $this->line("  Skipped (already exists): {$data['name']}");
            $this->skipped++;
            return;
        }

        if ($this->option('dry-run')) {
            $this->line("  Would import: {$data['name']}");
            $this->imported++;
            return;
        }

        try {
            PaymentMethod::create([
                'name' => $data['name'],
                'slug' => $data['slug'],
                'description' => "Pay via {$data['name']}",
                'order' => $index,
                'is_active' => true,
            ]);

            $this->line("  Imported: {$data['name']}");
            $this->imported++;

        } catch (\Exception $e) {
            $this->error("  Failed to import {$data['name']}: {$e->getMessage()}");
            $this->skipped++;
        }
    }
}
