<?php

namespace App\Console\Commands;

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

class ImportMecaprogramsCmsPages extends Command
{
    protected $signature = 'mecaprograms:import-cms-pages
        {--replace : Replace existing pages}
        {--dry-run : Print what would be imported without saving}';

    protected $description = 'Import CMS pages (About, Terms, Privacy) from mecaprograms.com';

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

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

    protected array $pages = [
        [
            'url' => '/about',
            'slug' => 'about',
            'title' => 'About Us',
        ],
        [
            'url' => '/about/terms-and-conditions',
            'slug' => 'terms-and-conditions',
            'title' => 'Terms and Conditions',
        ],
        [
            'url' => '/about/privacy-policy',
            'slug' => 'privacy-policy',
            'title' => 'Privacy Policy',
        ],
        [
            'url' => '/about/contact',
            'slug' => 'contact',
            'title' => 'Contact Us',
        ],
        [
            'url' => '/about/frequent-questions',
            'slug' => 'frequent-questions',
            'title' => 'Frequently Asked Questions',
        ],
    ];

    public function handle(): int
    {
        ini_set('memory_limit', '512M');
        $this->info('Importing CMS pages from mecaprograms.com...');
        $this->newLine();

        foreach ($this->pages as $page) {
            $this->importPage($page);
        }

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

        return Command::SUCCESS;
    }

    protected function importPage(array $page): void
    {
        $url = "{$this->baseUrl}{$page['url']}";
        $this->line("  Fetching: <fg=yellow>{$url}</>");

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

        if (!$response->successful()) {
            $this->warn("  Skipped (HTTP {$response->status()}): {$page['title']}");
            $this->skipped++;
            return;
        }

        $html = $response->body();

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

        $content = $this->extractContent($html, $page['slug']);

        if (empty($content)) {
            $this->warn("  No content found for: {$page['title']}");
            $this->skipped++;
            return;
        }

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

        $existing = Page::where('slug', $page['slug'])->first();

        if ($existing) {
            if (!$this->option('replace')) {
                $this->line("  Skipped (already exists, use --replace to update): {$title}");
                $this->skipped++;
                return;
            }
        }

        if ($this->option('dry-run')) {
            $this->line("  Would " . ($existing ? 'replace' : 'import') . ": {$title}");
            $this->imported++;
            return;
        }

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

            $action = $existing ? 'Replaced' : 'Imported';
            $this->line("  {$action}: {$title}");
            $this->imported++;

        } catch (\Exception $e) {
            $this->error("  Failed: {$title} - {$e->getMessage()}");
            $this->failed++;
        }
    }

    protected function extractContent(string $html, string $slug): string
    {
        // Remove scripts and styles
        $html = preg_replace('/<script[^>]*>.*?<\/script>/is', '', $html);
        $html = preg_replace('/<style[^>]*>.*?<\/style>/is', '', $html);

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

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

        if (empty($content)) {
            return '';
        }

        // For Terms and Privacy pages, extract the content div
        if (in_array($slug, ['terms-and-conditions', 'privacy-policy'])) {
            if (preg_match('/<div class="max-w-\[90%\][^>]*>(.*?)<\/div>\s*<\/div>\s*<\/div>/is', $content, $divContent)) {
                $content = $divContent[1];
            }
        }

        // For About page, extract the inner content from the Livewire wrapper
        if ($slug === 'about') {
            if (preg_match('/<div class="absolute inset-0[^"]*"[^>]*>(.*?)<\/div>\s*<\/div>\s*<\/div>/is', $content, $aboutContent)) {
                $content = $aboutContent[1];
            }
        }

        // For Contact page, extract the Livewire component content
        if ($slug === 'contact') {
            if (preg_match('/<div wire:id="[^"]*"[^>]*>(.*?)<\/div>\s*<\/div>\s*<\/div>/is', $content, $contactContent)) {
                $content = $contactContent[1];
            }
        }

        // For FAQ page
        if ($slug === 'frequent-questions') {
            if (preg_match('/<div wire:id="[^"]*"[^>]*>(.*?)<\/div>\s*<\/div>\s*<\/div>/is', $content, $faqContent)) {
                $content = $faqContent[1];
            }
        }

        // Strip wire: attributes from Livewire
        $content = preg_replace('/wire:[a-z]+="[^"]*"/i', '', $content);
        $content = preg_replace('/wire:[a-z]+/i', '', $content);

        // Clean excessive whitespace
        $content = trim(preg_replace('/\s+/', ' ', $content));

        return $content;
    }
}
