<?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
    {
        // Add subscription + monthly billing fields to bookings
        Schema::table('bookings', function (Blueprint $table) {
            $table->boolean('is_subscription')->default(false);
            $table->unsignedTinyInteger('visits_per_period')->default(1); // visits allowed per month (1 = monthly)
            $table->unsignedTinyInteger('visits_used')->default(0);
            $table->string('subscription_code', 16)->nullable()->unique(); // stable ID across renewals (e.g. SUB-AB12CD)
            $table->string('billing_period', 20)->default('monthly'); // monthly, quarterly
            $table->date('current_period_start')->nullable();
            $table->date('current_period_end')->nullable();
            $table->date('next_billing_date')->nullable();
            $table->boolean('auto_renew')->default(true);
            $table->enum('subscription_status', ['inactive', 'active', 'paused', 'cancelled', 'expired'])->default('inactive');
        });

        Schema::create('subscription_visits', function (Blueprint $table) {
            $table->id();
            $table->foreignId('booking_id')->constrained()->cascadeOnDelete(); // parent subscription
            $table->foreignId('partner_id')->nullable()->constrained('partner_profiles')->nullOnDelete();
            $table->date('scheduled_date');
            $table->string('scheduled_slot', 20)->nullable();
            $table->enum('status', ['scheduled', 'on_the_way', 'arrived', 'in_progress', 'completed', 'cancelled', 'skipped'])->default('scheduled');
            $table->string('start_otp', 6)->nullable();
            $table->timestamp('start_otp_verified_at')->nullable();
            $table->string('completion_otp', 6)->nullable();
            $table->timestamp('completion_otp_verified_at')->nullable();
            $table->timestamp('started_at')->nullable();
            $table->timestamp('completed_at')->nullable();
            $table->timestamp('cancelled_at')->nullable();
            $table->text('notes')->nullable();
            $table->timestamps();

            $table->index(['scheduled_date', 'status']);
            $table->index('booking_id');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('subscription_visits');
        Schema::table('bookings', function (Blueprint $table) {
            $table->dropColumn([
                'is_subscription', 'visits_per_period', 'visits_used',
                'subscription_code', 'billing_period', 'current_period_start',
                'current_period_end', 'next_billing_date', 'auto_renew', 'subscription_status',
            ]);
        });
    }
};