<?php

namespace App\Console\Commands;

use App\Models\Module;
use Illuminate\Console\Command;

class InstallMecaprogramsModules extends Command
{
    protected $signature = 'mecaprograms:install-modules
        {--force : Re-install already installed modules}';

    protected $description = 'Discover and install all modules from mecaprograms.com';

    public function handle(): int
    {
        $this->info('Discovering modules from mecaprograms.com...');

        $fetched = $this->fetchModulesFromMecaprograms();

        if (empty($fetched)) {
            $this->warn('Could not fetch modules from mecaprograms.com. Using local configuration.');
            $fetched = $this->getDefaultModules();
        }

        $installed = 0;
        $skipped = 0;

        foreach ($fetched as $module) {
            $existing = Module::where('code', $module['code'])->first();

            if ($existing && !$this->option('force')) {
                $this->line("  [SKIP] {$module['name']} already installed.");
                $skipped++;
                continue;
            }

            Module::updateOrCreate(
                ['code' => $module['code']],
                [
                    'name' => $module['name'],
                    'group' => $module['group'],
                    'description' => $module['description'] ?? '',
                    'version' => $module['version'] ?? '1.0.0',
                    'is_installed' => true,
                    'is_active' => true,
                    'order' => $module['order'] ?? Module::max('order') + 1,
                ]
            );

            $this->info("  [INSTALL] {$module['name']}");
            $installed++;
        }

        $this->newLine();
        $this->info("Done. {$installed} modules installed, {$skipped} skipped.");

        return Command::SUCCESS;
    }

    protected function fetchModulesFromMecaprograms(): array
    {
        try {
            $ctx = stream_context_create([
                'http' => ['method' => 'GET', 'timeout' => 15, 'header' => "User-Agent: Mozilla/5.0\r\n"],
                'ssl' => ['verify_peer' => false, 'verify_peer_name' => false],
            ]);

            $html = @file_get_contents('https://mecaprograms.com/', false, $ctx);

            // Start with all known modules from config
            $modules = $this->getDefaultModules();

            if ($html) {
                // Detect extra sections on the homepage not in config
                $detected = [];
                $keywords = [
                    'slider' => 'sliders',
                    'feature' => 'features',
                    'product' => 'products',
                    'categor' => 'categories',
                    'brand' => 'brands',
                    'interface' => 'interfaces',
                    'update' => 'updates',
                    'payment' => 'payment-methods',
                    'faq' => 'faqs',
                    'article' => 'articles',
                    'testimonial' => 'testimonials',
                    'service' => 'services',
                    'flash' => 'flash-sales',
                    'contact' => 'contacts',
                    'subscrib' => 'subscribers',
                    'help' => 'help-pages',
                ];

                $existingCodes = array_column($modules, 'code');
                foreach ($keywords as $keyword => $code) {
                    if (!in_array($code, $existingCodes) && stripos($html, $keyword) !== false) {
                        $detected[] = [
                            'code' => $code,
                            'name' => ucwords(str_replace(['-', '_'], ' ', $code)),
                            'group' => $this->getGroupForCode($code),
                            'order' => count($modules),
                        ];
                    }
                }
                $modules = array_merge($modules, $detected);
            }

            return $modules;
        } catch (\Exception $e) {
            $this->error('Error fetching: ' . $e->getMessage());
            return [];
        }
    }

    protected function getGroupForCode(string $code): string
    {
        $shop = ['products', 'categories', 'brands', 'interfaces', 'updates', 'flash-sales', 'orders'];
        $content = ['pages', 'sliders', 'features', 'testimonials', 'services', 'faqs', 'help-pages', 'articles'];
        $payment = ['payment-methods', 'payment-gateways'];
        $comm = ['contacts', 'subscribers'];
        $seo = ['seo-pages', 'settings'];
        $system = ['users', 'dashboard'];

        if (in_array($code, $shop)) return 'shop';
        if (in_array($code, $content)) return 'content';
        if (in_array($code, $payment)) return 'payment';
        if (in_array($code, $comm)) return 'communications';
        if (in_array($code, $seo)) return 'seo';
        if (in_array($code, $system)) return 'system';

        return 'general';
    }

    protected function getDefaultModules(): array
    {
        $modules = [];
        $order = 0;

        foreach (config('modules', []) as $group => $groupConfig) {
            foreach ($groupConfig['modules'] ?? [] as $modCode => $modConfig) {
                $modules[] = [
                    'code' => $modCode,
                    'name' => $modConfig['name'],
                    'group' => $group,
                    'order' => $order++,
                ];
            }
        }

        return $modules;
    }
}
