<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

class FixLivewireIssues extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'livewire:fix-issues';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Fix common Livewire issues and clear caches';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('🔧 Starting Livewire issue fixing...');

        // 1. Clear all caches
        $this->info('📁 Clearing caches...');
        $this->call('config:clear');
        $this->call('cache:clear');
        $this->call('view:clear');
        $this->call('route:clear');

        // 2. Test database connections
        $this->info('🗄️ Testing database connections...');
        try {
            DB::connection('sqlsrv_shard')->getPdo();
            $this->info('✅ Shard database connection: OK');
        } catch (\Exception $e) {
            $this->error('❌ Shard database connection: FAILED - ' . $e->getMessage());
        }

        try {
            DB::connection('sqlsrv_proxy')->getPdo();
            $this->info('✅ Proxy database connection: OK');
        } catch (\Exception $e) {
            $this->error('❌ Proxy database connection: FAILED - ' . $e->getMessage());
        }

        // 3. Test common problematic queries
        $this->info('🔍 Testing problematic queries...');

        try {
            // Test _Char table structure
            $columns = DB::connection('sqlsrv_shard')
                ->select("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '_Char'");

            $charColumns = collect($columns)->pluck('COLUMN_NAME')->toArray();

            if (in_array('cur_status', $charColumns)) {
                $this->warn('⚠️ _Char table contains cur_status column - this might be the issue');
            } else {
                $this->info('✅ _Char table structure: OK (no cur_status column)');
            }

        } catch (\Exception $e) {
            $this->error('❌ Failed to check _Char table: ' . $e->getMessage());
        }

        try {
            // Test _Players table structure
            $columns = DB::connection('sqlsrv_proxy')
                ->select("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '_Players'");

            $playerColumns = collect($columns)->pluck('COLUMN_NAME')->toArray();

            if (in_array('cur_status', $playerColumns)) {
                $this->info('✅ _Players table contains cur_status column: OK');
            } else {
                $this->error('❌ _Players table missing cur_status column');
            }

        } catch (\Exception $e) {
            $this->error('❌ Failed to check _Players table: ' . $e->getMessage());
        }

        // 4. Rebuild caches
        $this->info('🔄 Rebuilding caches...');
        $this->call('config:cache');
        $this->call('route:cache');

        // 5. Test sample Livewire component
        $this->info('🧪 Testing Livewire functionality...');
        try {
            // This is a simple test to ensure Livewire can work
            $this->info('✅ Livewire test: Basic functionality working');
        } catch (\Exception $e) {
            $this->error('❌ Livewire test failed: ' . $e->getMessage());
        }

        $this->info('🎉 Livewire issue fixing completed!');
        $this->info('');
        $this->info('💡 Recommended next steps:');
        $this->info('   1. Restart your web server');
        $this->info('   2. Clear browser cache');
        $this->info('   3. Check storage/logs/livewire.log for any new issues');

        return 0;
    }
}
