<?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
{
    public function up(): void
    {
        Schema::table('training_programs', function (Blueprint $table) {
            $table->string('billing_cycle', 20)->nullable()->after('renewal_policy');
            $table->unsignedTinyInteger('billing_day')->nullable()->after('billing_cycle');
        });

        DB::statement("ALTER TABLE training_programs ADD CONSTRAINT training_programs_billing_cycle_check CHECK (billing_cycle IN ('monthly', 'quarterly', 'semi_annual', 'annual', 'per_duration'))");

        Schema::table('enrollments', function (Blueprint $table) {
            $table->date('next_billing_date')->nullable()->after('end_date');
            $table->date('last_billed_at')->nullable()->after('next_billing_date');
        });

        $table = 'enrollments';
        if (!Schema::hasIndex($table, 'enrollments_next_billing_date_index')) {
            Schema::table($table, function (Blueprint $table) {
                $table->index('next_billing_date');
            });
        }
    }

    public function down(): void
    {
        DB::statement("ALTER TABLE training_programs DROP CONSTRAINT IF EXISTS training_programs_billing_cycle_check");

        Schema::table('training_programs', function (Blueprint $table) {
            $table->dropColumn(['billing_cycle', 'billing_day']);
        });

        Schema::table('enrollments', function (Blueprint $table) {
            $table->dropIndex(['next_billing_date']);
            $table->dropColumn(['next_billing_date', 'last_billed_at']);
        });
    }
};
