<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // 1. Modify products table
        Schema::table('products', function (Blueprint $table) {
            $table->decimal('cost_price', 12, 2)->default(0.00)->nullable()->after('price');
            $table->longText('service_form')->nullable()->after('type');
            $table->string('subscription_period')->nullable()->after('service_form'); // month, year
        });

        // 2. Modify users table
        Schema::table('users', function (Blueprint $table) {
            $table->string('bank_name')->nullable()->after('avatar');
            $table->string('bank_account_number')->nullable()->after('bank_name');
            $table->string('bank_account_name')->nullable()->after('bank_account_number');
        });

        // 3. Modify orders table
        Schema::table('orders', function (Blueprint $table) {
            $table->decimal('tax_amount', 12, 2)->default(0.00)->after('shipping_cost');
        });

        // 4. Modify order_items table
        Schema::table('order_items', function (Blueprint $table) {
            $table->longText('custom_form_data')->nullable()->after('price');
        });

        // 5. Create subscriptions table
        Schema::create('subscriptions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users')->cascadeOnDelete();
            $table->foreignId('order_id')->constrained('orders')->cascadeOnDelete();
            $table->foreignId('product_id')->constrained('products')->cascadeOnDelete();
            $table->string('status')->default('active'); // active, expired, cancelled
            $table->string('billing_cycle')->default('month'); // month, year
            $table->dateTime('starts_at');
            $table->dateTime('ends_at');
            $table->dateTime('last_notified_at')->nullable();
            $table->longText('custom_form_data')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('subscriptions');

        Schema::table('order_items', function (Blueprint $table) {
            $table->dropColumn('custom_form_data');
        });

        Schema::table('orders', function (Blueprint $table) {
            $table->dropColumn('tax_amount');
        });

        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn(['bank_name', 'bank_account_number', 'bank_account_name']);
        });

        Schema::table('products', function (Blueprint $table) {
            $table->dropColumn(['cost_price', 'service_form', 'subscription_period']);
        });
    }
};
