<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Spatie\Permission\Models\Permission;

/**
 * Wellness plans — recurring health-plan subscriptions billed via the
 * existing core recurring-invoice engine (transactions.is_recurring=1 +
 * pos:generateSubscriptionInvoices cron).
 *
 *  vc_wellness_plans          : catalogue
 *  vc_wellness_plan_benefits  : "2 vaccines / year", "10% off services", etc.
 *  vc_wellness_subscriptions  : per-pet active plan
 *  vc_wellness_benefit_usage  : redemption ledger
 */
class CreateVcWellnessTables extends Migration
{
    public function up()
    {
        if (!Schema::hasTable('vc_wellness_plans')) {
            Schema::create('vc_wellness_plans', function (Blueprint $table) {
                $table->increments('id');
                $table->unsignedInteger('business_id')->index();
                $table->string('name', 120);
                $table->text('description')->nullable();
                $table->decimal('price_monthly', 22, 4)->nullable();
                $table->decimal('price_annual',  22, 4)->nullable();
                $table->unsignedInteger('product_id')->nullable();  // ERP product backing the recurring invoice
                $table->enum('status', ['active', 'inactive'])->default('active');
                $table->timestamps();
            });
        }

        if (!Schema::hasTable('vc_wellness_plan_benefits')) {
            Schema::create('vc_wellness_plan_benefits', function (Blueprint $table) {
                $table->increments('id');
                $table->unsignedInteger('plan_id')->index();
                $table->enum('kind', ['visits', 'vaccines', 'products', 'discount_pct']);
                $table->string('label', 120);
                $table->decimal('quantity_per_year', 8, 2)->nullable();
                $table->decimal('value', 22, 4)->nullable();   // discount % or product price cap
                $table->string('notes', 255)->nullable();
                $table->timestamps();
            });
        }

        if (!Schema::hasTable('vc_wellness_subscriptions')) {
            Schema::create('vc_wellness_subscriptions', function (Blueprint $table) {
                $table->increments('id');
                $table->unsignedInteger('business_id')->index();
                $table->unsignedInteger('contact_id');
                $table->unsignedInteger('pet_id');
                $table->unsignedInteger('plan_id');
                $table->enum('status', ['active', 'paused', 'cancelled', 'expired'])->default('active')->index();
                $table->enum('billing_cycle', ['monthly', 'annual'])->default('monthly');
                $table->date('started_at');
                $table->date('renews_at')->nullable();
                $table->date('ended_at')->nullable();
                $table->unsignedInteger('erp_recurring_transaction_id')->nullable();
                $table->unsignedInteger('created_by')->nullable();
                $table->timestamps();

                $table->index(['business_id', 'pet_id']);
            });
        }

        if (!Schema::hasTable('vc_wellness_benefit_usage')) {
            Schema::create('vc_wellness_benefit_usage', function (Blueprint $table) {
                $table->increments('id');
                $table->unsignedInteger('subscription_id')->index();
                $table->unsignedInteger('benefit_id');
                $table->dateTime('used_at');
                $table->decimal('qty', 8, 2)->default(1);
                $table->decimal('discounted_amount', 22, 4)->nullable();
                $table->string('source_type', 30)->nullable();  // 'appointment' | 'prescription' | 'vaccination' | 'sell'
                $table->unsignedInteger('source_id')->nullable();
                $table->string('notes', 255)->nullable();
                $table->timestamps();
            });
        }

        foreach (['vet_clinic.view_wellness', 'vet_clinic.manage_wellness'] as $perm) {
            Permission::findOrCreate($perm, 'web');
        }
    }

    public function down()
    {
        Schema::dropIfExists('vc_wellness_benefit_usage');
        Schema::dropIfExists('vc_wellness_subscriptions');
        Schema::dropIfExists('vc_wellness_plan_benefits');
        Schema::dropIfExists('vc_wellness_plans');
        Permission::whereIn('name', ['vet_clinic.view_wellness', 'vet_clinic.manage_wellness'])->delete();
    }
}
