<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('milestones', function (Blueprint $table) {
            // Add project_id if it doesn't exist
            if (!$this->hasColumn('milestones', 'project_id')) {
                $table->unsignedBigInteger('project_id')->nullable()->after('proposal_id');
            }
            
            // Make proposal_id nullable if it's not already
            // Note: We can't change existing NOT NULL columns easily, so we'll add project_id as nullable
            
            // Add completion_criteria and order fields if they don't exist
            if (!$this->hasColumn('milestones', 'completion_criteria')) {
                $table->text('completion_criteria')->nullable()->after('description');
            }
            if (!$this->hasColumn('milestones', 'order')) {
                $table->unsignedInteger('order')->default(0)->after('status');
            }
            if (!$this->hasColumn('milestones', 'completed_at')) {
                $table->timestamp('completed_at')->nullable()->after('status');
            }
            
            // Update status enum to include new values if needed
            // Note: MySQL doesn't support ALTER ENUM easily, so we'll handle this in application logic
            
            // Add foreign key for project_id if it doesn't exist
            if (!$this->hasForeignKey('milestones', 'milestones_project_id_foreign')) {
                $table->foreign('project_id')
                      ->references('id')
                      ->on('projects')
                      ->onDelete('cascade');
            }
            
            // Add index
            if (!$this->hasIndex('milestones', 'milestones_project_id_index')) {
                $table->index('project_id');
            }
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('milestones', function (Blueprint $table) {
            if ($this->hasIndex('milestones', 'milestones_project_id_index')) {
                $table->dropIndex('milestones_project_id_index');
            }
            if ($this->hasForeignKey('milestones', 'milestones_project_id_foreign')) {
                $table->dropForeign(['project_id']);
            }
            if ($this->hasColumn('milestones', 'completed_at')) {
                $table->dropColumn('completed_at');
            }
            if ($this->hasColumn('milestones', 'order')) {
                $table->dropColumn('order');
            }
            if ($this->hasColumn('milestones', 'completion_criteria')) {
                $table->dropColumn('completion_criteria');
            }
            if ($this->hasColumn('milestones', 'project_id')) {
                $table->dropColumn('project_id');
            }
        });
    }
    
    /**
     * Check if a column exists on a table
     */
    private function hasColumn(string $table, string $column): bool
    {
        $databaseName = DB::getDatabaseName();
        
        $result = DB::select(
            "SELECT COUNT(*) as count 
             FROM information_schema.columns 
             WHERE table_schema = ? 
             AND table_name = ? 
             AND column_name = ?",
            [$databaseName, $table, $column]
        );
        
        return $result[0]->count > 0;
    }
    
    /**
     * Check if an index exists on a table
     */
    private function hasIndex(string $table, string $index): bool
    {
        $databaseName = DB::getDatabaseName();
        
        $result = DB::select(
            "SELECT COUNT(*) as count 
             FROM information_schema.statistics 
             WHERE table_schema = ? 
             AND table_name = ? 
             AND index_name = ?",
            [$databaseName, $table, $index]
        );
        
        return $result[0]->count > 0;
    }
    
    /**
     * Check if a foreign key exists
     */
    private function hasForeignKey(string $table, string $foreignKey): bool
    {
        $databaseName = DB::getDatabaseName();
        
        $result = DB::select(
            "SELECT COUNT(*) as count 
             FROM information_schema.key_column_usage 
             WHERE table_schema = ? 
             AND table_name = ? 
             AND constraint_name = ?",
            [$databaseName, $table, $foreignKey]
        );
        
        return $result[0]->count > 0;
    }
};
