<?php

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

/**
 * Loyalty / prepaid maintenance plans (R3.4): a plan template and a customer's
 * enrollment that draws down visits over time. A redeemed visit adds the
 * covered service to a repair order at no charge.
 */
return new class extends Migration {
    public function up(): void
    {
        if (! Schema::hasTable('vrc_service_plans')) {
            Schema::create('vrc_service_plans', function (Blueprint $t) {
                $t->bigIncrements('id');
                $t->unsignedInteger('business_id');
                $t->string('name', 191);
                $t->string('name_ar', 191)->nullable();
                $t->decimal('price', 15, 2)->default(0);
                $t->unsignedInteger('validity_months')->default(12);
                $t->unsignedInteger('visit_count')->default(1);
                $t->json('included_services')->nullable(); // vrc_service ids covered
                $t->boolean('is_active')->default(true);
                $t->timestamps();
                $t->index(['business_id', 'is_active']);
            });
        }

        if (! Schema::hasTable('vrc_customer_plans')) {
            Schema::create('vrc_customer_plans', function (Blueprint $t) {
                $t->bigIncrements('id');
                $t->unsignedInteger('business_id');
                $t->unsignedInteger('erp_customer_id');
                $t->unsignedBigInteger('plan_id');
                $t->unsignedBigInteger('vehicle_id')->nullable();
                $t->date('purchased_at');
                $t->date('expires_at')->nullable();
                $t->unsignedInteger('visits_remaining')->default(0);
                $t->string('status', 20)->default('active'); // active|expired|used_up|cancelled
                $t->timestamps();
                $t->index(['business_id', 'erp_customer_id'], 'vrc_cust_plan_biz_cust_idx');
                $t->index(['business_id', 'status']);
            });
        }
    }

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