<?php

namespace App\Console\Commands;

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

class ImportMecaprogramsPageHome extends Command
{
    protected $signature = 'mecaprograms:import-page-home
        {--replace : Replace existing Home page}
        {--dry-run : Print what would be imported without saving}';

    protected $description = 'Import Home page from mecaprograms.com';

    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();

        $title = 'Home';
        if (preg_match('/<title>(.*?)<\/title>/is', $html, $m)) {
            $title = trim($m[1]);
            $title = str_replace([' - Mecaprograms', ' | Mecaprograms', 'Mecaprograms: '], '', $title);
            $title = trim($title) ?: 'Home';
        }

        $content = '';
        if (preg_match('/<main[^>]*>(.*?)<\/main>/is', $html, $m)) {
            $content = $m[1];
        } elseif (preg_match('/<body[^>]*>(.*?)<\/body>/is', $html, $m)) {
            $content = $m[1];
        }

        $content = preg_replace('/<script[^>]*>.*?<\/script>/is', '', $content);
        $content = preg_replace('/<style[^>]*>.*?<\/style>/is', '', $content);
        $content = preg_replace('/<header[^>]*>.*?<\/header>/is', '', $content);
        $content = preg_replace('/<footer[^>]*>.*?<\/footer>/is', '', $content);
        $content = preg_replace('/<nav[^>]*>.*?<\/nav>/is', '', $content);

        $content = strip_tags($content, '<p><br><ul><ol><li><h1><h2><h3><h4><h5><h6><div><span><strong><em><a><img><section><blockquote>');
        $content = trim(preg_replace('/\s+/', ' ', $content));

        if (empty($content)) {
            $this->warn('No content extracted from homepage.');
            return Command::FAILURE;
        }

        $this->line("  Title: $title");
        $this->line('  Content length: ' . strlen($content) . ' chars');

        $existing = Page::where('title', $title)->first();
        if ($existing) {
            if ($this->option('replace')) {
                if ($this->option('dry-run')) {
                    $this->line("  Would replace: $title");
                } else {
                    $existing->update([
                        'content' => $content,
                        'slug' => 'home',
                    ]);
                    $this->line("  Replaced: $title");
                }
            } else {
                $this->line("  Skipped (already exists, use --replace to update): $title");
            }
            return Command::SUCCESS;
        }

        if ($this->option('dry-run')) {
            $this->line("  Would import page: $title");
            return Command::SUCCESS;
        }

        try {
            Page::create([
                'title' => $title,
                'slug' => 'home',
                'content' => $content,
                'is_active' => true,
                'order' => 0,
            ]);

            $this->info("  Imported page: $title");

        } catch (\Exception $e) {
            $this->error("  Failed: {$e->getMessage()}");
            return Command::FAILURE;
        }

        return Command::SUCCESS;
    }
}
