<?php

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

return new class extends Migration
{

    public function up(): void
    {
        Schema::create('subscriptions', function (Blueprint $table) {
            $table->id();
            $table->string('code'); // SUB-2024-001
            $table->foreignId('customer_id')->constrained()->onDelete('cascade');
            $table->foreignId('plan_id')->constrained()->onDelete('cascade');
            $table->date('start_date');
            $table->date('end_date');

            $table->decimal('amount', 10);
            $table->decimal('discount', 10);
            $table->decimal('net_amount', 10);
            $table->decimal('vat', 10);
            $table->decimal('vat_value', 10);
            $table->decimal('total', 10);
            $table->decimal('amount_paid', 10);
            $table->decimal('remaining_paid', 10);
            $table->boolean('vat_included')->default(true);
            $table->integer('sessions_count')->nullable();
            $table->integer('remaining_sessions')->nullable();
            $table->integer('how_know_us')->nullable();

            $table->foreignId('payment_method_id')->constrained()->onDelete('cascade');
            $table->enum('status', ['active', 'expired', 'canceled'])->default('active');
            $table->text('notes')->nullable();
            $table->foreignId('renewed_to')->nullable()->constrained('subscriptions')->onDelete('set null');
            $table->boolean('is_renewal')->default(false);

            $table->text('cancellation_reason')->nullable();
            $table->timestamp('canceled_at')->nullable();
            $table->foreignId('canceled_by')->nullable()->constrained('users');

            $table->foreignId('transferred_from_customer_id')->nullable()->constrained('customers');
            $table->foreignId('transferred_to_customer_id')->nullable()->constrained('customers');
            $table->foreignId('transferred_by')->nullable()->constrained('users');
            $table->timestamp('transferred_at')->nullable();
            $table->text('transfer_reason')->nullable();
            $table->boolean('is_transferred')->default(false);

            $table->timestamps();
            $table->softDeletes();

            $table->foreignId('created_by')->nullable()->constrained('users');
        });
    }

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