<?php

namespace App\Console\Commands;

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

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

    protected $description = 'Import flash sales from mecaprograms.com homepage';

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

    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;
        }

        $sales = $this->parseFlashSales($html);
        $this->info('Found ' . count($sales) . ' flash sale(s) on homepage');

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

        $this->newLine();
        $this->info('Processing flash sales...');

        foreach ($sales as $index => $sale) {
            $this->importFlashSale($sale, $index);
            usleep((int) $this->option('delay') * 1000);
        }

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

        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 parseFlashSales(string $html): array
    {
        $sales = [];

        $patterns = [
            '/announcement-title[^>]*>\s*<p[^>]*>(.*?)<\/p>/is',
            '/class="[^"]*announcement[^"]*"[^>]*>(.*?)<\/div>/is',
            '/promo-banner[^"]*"[^>]*>(.*?)<\/div>/is',
            '/LIMITED TIME/i',
        ];

        $promoText = '';

        foreach ($patterns as $pattern) {
            if (preg_match($pattern, $html, $m)) {
                $text = trim(strip_tags($m[1] ?? $m[0]));
                $text = preg_replace('/\s+/', ' ', $text);
                $text = trim($text);
                if (!empty($text) && strlen($text) > 10) {
                    $promoText = $text;
                    break;
                }
            }
        }

        if (empty($promoText)) {
            if (preg_match('/LIMITED TIME/i', $html)) {
                $promoText = 'Limited Time! Special Discounts Available – Ask Now';
            }
        }

        if (!empty($promoText)) {
            $title = 'Limited Time Offer';
            $description = $promoText;
            $discount = null;
            $btnText = 'Ask Now';
            $btnLink = '/contact';

            if (preg_match('/(\d+)\s*%\s*OFF/i', $promoText, $dm)) {
                $discount = (int) $dm[1];
            }

            $sales[] = [
                'title' => $title,
                'description' => $description,
                'discount_percentage' => $discount,
                'badge_text' => 'FLASH',
                'btn_text' => $btnText,
                'btn_link' => $btnLink,
                'slug' => Str::slug($title),
            ];
        }

        if (empty($sales)) {
            $sales[] = [
                'title' => 'Limited Time Offer',
                'description' => '43% OFF PACKAGES – ASK NOW',
                'discount_percentage' => 43,
                'badge_text' => 'FLASH',
                'btn_text' => 'Ask Now',
                'btn_link' => '/contact',
                'slug' => 'limited-time-offer',
            ];
            $this->line('  Using fallback flash sale data.');
        }

        return $sales;
    }

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

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

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

        try {
            FlashSale::create([
                'title' => $data['title'],
                'description' => $data['description'],
                'discount_percentage' => $data['discount_percentage'],
                'badge_text' => $data['badge_text'],
                'btn_text' => $data['btn_text'],
                'btn_link' => $data['btn_link'],
                'order' => $index,
                'is_active' => true,
            ]);

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

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