<?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
    {
        if (!Schema::hasColumn('products', 'billing_cycle')) {
            Schema::table('products', function (Blueprint $table) {
                $table->string('billing_cycle', 20)->default('one_time')->after('is_essential');
                $table->bigInteger('member_price')->nullable()->after('billing_cycle');
                $table->bigInteger('non_member_price')->nullable()->after('member_price');
            });

            DB::statement("ALTER TABLE products ADD CONSTRAINT products_billing_cycle_check CHECK (billing_cycle IN ('one_time', 'annual'))");
        }

        if (!Schema::hasTable('product_installment_plans')) {
            Schema::create('product_installment_plans', function (Blueprint $table) {
                $table->id();
                $table->uuid('uuid')->unique();
                $table->foreignId('academy_id')->constrained()->cascadeOnDelete();
                $table->foreignId('product_id')->constrained()->cascadeOnDelete();
                $table->string('membership_tier', 20)->default('any');
                $table->string('label_ar');
                $table->unsignedSmallInteger('installments');
                $table->string('frequency', 20)->default('monthly');
                $table->unsignedTinyInteger('down_payment_pct')->default(0);
                $table->boolean('is_active')->default(true);
                $table->unsignedSmallInteger('sort_order')->default(0);
                $table->timestamps();

                $table->index(['product_id', 'membership_tier', 'is_active']);
                $table->index('academy_id');
            });

            DB::statement("ALTER TABLE product_installment_plans ADD CONSTRAINT product_installment_plans_tier_check CHECK (membership_tier IN ('member', 'non_member', 'any'))");
            DB::statement("ALTER TABLE product_installment_plans ADD CONSTRAINT product_installment_plans_frequency_check CHECK (frequency IN ('weekly', 'biweekly', 'monthly', 'quarterly'))");
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('product_installment_plans');

        if (Schema::hasColumn('products', 'billing_cycle')) {
            DB::statement('ALTER TABLE products DROP CONSTRAINT IF EXISTS products_billing_cycle_check');
            Schema::table('products', function (Blueprint $table) {
                $table->dropColumn(['billing_cycle', 'member_price', 'non_member_price']);
            });
        }
    }
};
