<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // Fix any existing foreign key issues with hyphenated database name
        // This is a direct fix for MySQL which has issues with hyphens in database names
        
        $currentDb = DB::connection()->getDatabaseName();
        
        // If database name contains hyphens, we might need to fix it
        if (strpos($currentDb, '-') !== false) {
            // For MySQL, try to use backticks to properly escape the database name
            if (DB::connection()->getDriverName() === 'mysql') {
                // Get all tables that might have foreign keys
                $tables = DB::select("SHOW TABLES");
                
                foreach ($tables as $table) {
                    $tableName = array_values((array)$table)[0];
                    
                    // Get all foreign keys in the table
                    $foreignKeys = DB::select("
                        SELECT 
                            CONSTRAINT_NAME 
                        FROM 
                            information_schema.TABLE_CONSTRAINTS 
                        WHERE 
                            TABLE_SCHEMA = '{$currentDb}' 
                            AND TABLE_NAME = '{$tableName}'
                            AND CONSTRAINT_TYPE = 'FOREIGN KEY'
                    ");
                    
                    foreach ($foreignKeys as $foreignKey) {
                        $constraintName = $foreignKey->CONSTRAINT_NAME;
                        
                        // Check if this is causing the specific error in fundings table
                        if ($tableName === 'fundings') {
                            try {
                                // Drop the problematic constraint
                                DB::statement("ALTER TABLE `{$tableName}` DROP FOREIGN KEY `{$constraintName}`");
                                
                                // Get the column and referenced table/column for recreating properly
                                $keyInfo = DB::select("
                                    SELECT 
                                        COLUMN_NAME,
                                        REFERENCED_TABLE_NAME,
                                        REFERENCED_COLUMN_NAME
                                    FROM 
                                        information_schema.KEY_COLUMN_USAGE
                                    WHERE 
                                        TABLE_SCHEMA = '{$currentDb}'
                                        AND TABLE_NAME = '{$tableName}'
                                        AND CONSTRAINT_NAME = '{$constraintName}'
                                ");
                                
                                if (!empty($keyInfo)) {
                                    $columnName = $keyInfo[0]->COLUMN_NAME;
                                    $refTable = $keyInfo[0]->REFERENCED_TABLE_NAME;
                                    $refColumn = $keyInfo[0]->REFERENCED_COLUMN_NAME;
                                    
                                    // Recreate the foreign key properly with backticks
                                    DB::statement("
                                        ALTER TABLE `{$tableName}` 
                                        ADD CONSTRAINT `{$constraintName}` 
                                        FOREIGN KEY (`{$columnName}`) 
                                        REFERENCES `{$refTable}`(`{$refColumn}`)
                                        ON DELETE SET NULL
                                    ");
                                }
                            } catch (\Exception $e) {
                                // Log the error but continue with other fixes
                                \Log::error("Error fixing foreign key {$constraintName} on {$tableName}: " . $e->getMessage());
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        // No reversion needed as this is a fix
    }
}; 