<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class NetgesconSystemCheck extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'netgescon:system-check {--fix : Applica correzioni automatiche}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Controllo completo dell\'integrità del sistema NetGescon';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $fix = $this->option('fix');
        $issues = 0;

        $this->info("🔍 NetGescon System Check - " . now()->format('d/m/Y H:i:s'));
        $this->newLine();

        // 1. Layout Check
        $this->info("📋 1. Controllo Layout...");
        $layoutIssues = $this->checkLayouts($fix);
        $issues += $layoutIssues;

        // 2. Relationship Check
        $this->info("🔗 2. Controllo Relationships...");
        $relationshipIssues = $this->checkRelationships($fix);
        $issues += $relationshipIssues;

        // 3. Database Check
        $this->info("🗄️ 3. Controllo Database...");
        $dbIssues = $this->checkDatabase();
        $issues += $dbIssues;

        // 4. Files Check
        $this->info("📁 4. Controllo File System...");
        $fileIssues = $this->checkFiles();
        $issues += $fileIssues;

        // 5. Route Check
        $this->info("🛣️ 5. Controllo Route...");
        $routeIssues = $this->checkRoutes();
        $issues += $routeIssues;

        $this->newLine();

        if ($issues === 0) {
            $this->info("✅ Sistema NetGescon: TUTTO OK! Nessun problema rilevato.");
        } else {
            $this->warn("⚠️ Sistema NetGescon: {$issues} problema(i) rilevato(i).");
            if (!$fix) {
                $this->info("💡 Usa --fix per applicare correzioni automatiche.");
            }
        }
    }

    private function checkLayouts($fix)
    {
        $issues = 0;
        $deprecatedLayouts = config('netgescon.deprecated_layouts', []);
        $activeLayout = config('netgescon.active_layout', 'admin.layouts.netgescon');

        $files = File::allFiles(resource_path('views'));

        foreach ($files as $file) {
            if ($file->getExtension() === 'php' && str_ends_with($file->getFilename(), '.blade.php')) {
                $content = File::get($file->getPathname());

                foreach ($deprecatedLayouts as $deprecated) {
                    if (preg_match("/@extends\s*\(\s*['\"]" . preg_quote($deprecated, '/') . "['\"]\s*\)/", $content)) {
                        $relativePath = str_replace(base_path() . '/', '', $file->getPathname());
                        $this->line("  ❌ Layout deprecato in: {$relativePath}");
                        $issues++;

                        if ($fix) {
                            $content = preg_replace(
                                "/@extends\s*\(\s*['\"]" . preg_quote($deprecated, '/') . "['\"]\s*\)/",
                                "@extends('{$activeLayout}')",
                                $content
                            );
                            File::put($file->getPathname(), $content);
                            $this->line("    ✅ Corretto automaticamente");
                        }
                    }
                }
            }
        }

        if ($issues === 0) {
            $this->line("  ✅ Tutti i layout sono corretti");
        }

        return $issues;
    }

    private function checkRelationships($fix)
    {
        $issues = 0;

        // Controllo relationship palazzina vs palazzinaObj
        $files = File::allFiles(resource_path('views'));

        foreach ($files as $file) {
            if ($file->getExtension() === 'php' && str_ends_with($file->getFilename(), '.blade.php')) {
                $content = File::get($file->getPathname());

                // Cerca with('palazzina') invece di with('palazzinaObj')
                if (preg_match("/with\s*\(\s*['\"]palazzina['\"]\s*\)/", $content)) {
                    $relativePath = str_replace(base_path() . '/', '', $file->getPathname());
                    $this->line("  ❌ Relationship obsoleto in: {$relativePath}");
                    $issues++;

                    if ($fix) {
                        $content = preg_replace(
                            "/with\s*\(\s*['\"]palazzina['\"]\s*\)/",
                            "with('palazzinaObj')",
                            $content
                        );
                        File::put($file->getPathname(), $content);
                        $this->line("    ✅ Corretto automaticamente");
                    }
                }
            }
        }

        if ($issues === 0) {
            $this->line("  ✅ Tutti i relationship sono corretti");
        }

        return $issues;
    }

    private function checkDatabase()
    {
        $issues = 0;

        try {
            // Controllo connessione database
            DB::connection()->getPdo();
            $this->line("  ✅ Connessione database OK");

            // Controllo tabelle principali
            $tables = ['stabili', 'palazzine', 'unita_immobiliari', 'users'];
            foreach ($tables as $table) {
                if (Schema::hasTable($table)) {
                    $count = DB::table($table)->count();
                    $this->line("  ✅ Tabella {$table}: {$count} record(i)");
                } else {
                    $this->line("  ❌ Tabella mancante: {$table}");
                    $issues++;
                }
            }
        } catch (\Exception $e) {
            $this->line("  ❌ Errore database: " . $e->getMessage());
            $issues++;
        }

        return $issues;
    }

    private function checkFiles()
    {
        $issues = 0;

        // Controllo file essenziali
        $essentialFiles = [
            'resources/views/admin/layouts/netgescon.blade.php',
            'app/Http/Middleware/NetgesconLayoutMiddleware.php',
            'config/netgescon.php',
            'app/Models/UnitaImmobiliare.php',
            'app/Models/Stabile.php',
            'app/Models/Palazzina.php'
        ];

        foreach ($essentialFiles as $file) {
            $fullPath = base_path($file);
            if (File::exists($fullPath)) {
                $this->line("  ✅ {$file}");
            } else {
                $this->line("  ❌ File mancante: {$file}");
                $issues++;
            }
        }

        // Controllo directory inattive
        $inactiveDirs = [
            '_BACKUP_OLD_netgescon-laravel_INACTIVE',
            '_BACKUP_OLD_netgescon_INACTIVE'
        ];

        foreach ($inactiveDirs as $dir) {
            $fullPath = base_path($dir);
            if (File::isDirectory($fullPath)) {
                $this->line("  ✅ Directory backup inattiva: {$dir}");
            } else {
                $this->line("  ⚠️ Directory backup non trovata: {$dir}");
            }
        }

        return $issues;
    }

    private function checkRoutes()
    {
        $issues = 0;

        try {
            // Controllo route principali
            $routes = [
                'admin.dashboard',
                'admin.stabili.index',
                'admin.stabili.create',
                'admin.palazzine.show',
                'admin.unita-immobiliari.show',
                'logout'
            ];

            foreach ($routes as $routeName) {
                if (route($routeName)) {
                    $this->line("  ✅ Route: {$routeName}");
                } else {
                    $this->line("  ❌ Route mancante: {$routeName}");
                    $issues++;
                }
            }
        } catch (\Exception $e) {
            $this->line("  ❌ Errore route: " . $e->getMessage());
            $issues++;
        }

        return $issues;
    }
}
