<?php

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

/**
 * Vet-specific metadata for an ERP quotation (transactions row with
 * sub_status='quotation'). Keeps the core transactions table untouched while
 * letting the vet module:
 *   - link a quotation to an appointment / pet
 *   - send the owner a tokenised approval link (email / SMS / WhatsApp)
 *   - capture owner approval + signature image + IP
 *   - record rejection with a reason
 *   - back-reference the resulting final invoice (sells.id) on conversion
 *
 * Once approved, the existing core "Convert Quotation -> Invoice" action
 * still drives the actual invoicing — we only stamp converted_sell_id.
 */
class CreateClcQuotationMetaTable extends Migration
{
    public function up()
    {
        if (!Schema::hasTable('clc_quotation_meta')) {
            Schema::create('clc_quotation_meta', function (Blueprint $table) {
                $table->increments('id');
                $table->unsignedInteger('business_id')->index();
                $table->unsignedInteger('transaction_id')->unique();          // FK to core transactions.id
                $table->unsignedInteger('appointment_id')->nullable()->index();
                $table->unsignedInteger('patient_id')->nullable()->index();

                $table->string('approval_token', 64)->nullable()->unique();
                $table->enum('status', ['draft', 'sent', 'viewed', 'approved', 'rejected', 'expired'])
                    ->default('draft')->index();

                $table->timestamp('sent_at')->nullable();
                $table->timestamp('viewed_at')->nullable();
                $table->timestamp('approved_at')->nullable();
                $table->string('approved_by_name', 191)->nullable();
                $table->string('approval_ip', 45)->nullable();
                $table->string('approval_signature_path', 255)->nullable();

                $table->timestamp('rejected_at')->nullable();
                $table->text('rejection_reason')->nullable();

                $table->date('expires_at')->nullable();
                $table->unsignedInteger('converted_sell_id')->nullable()->index();

                $table->unsignedInteger('created_by')->nullable();
                $table->timestamps();
            });
        }

        foreach (['clinic.view_quotations', 'clinic.manage_quotations'] as $perm) {
            Permission::findOrCreate($perm, 'web');
        }
    }

    public function down()
    {
        Schema::dropIfExists('clc_quotation_meta');

        Permission::whereIn('name', ['clinic.view_quotations', 'clinic.manage_quotations'])->delete();
    }
}
