<?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('form_templates', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->string('name');
            $table->string('code')->unique();
            $table->string('target_model'); // App\Models\Contract, App\Models\Product...
            $table->text('html_template');
            $table->string('paper_size')->default('A4');
            $table->boolean('is_active')->default(true);
            $table->timestamps();
        });

        Schema::create('form_fields', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->foreignUuid('template_id')->constrained('form_templates')->cascadeOnDelete();
            $table->string('code'); // ten_bien trong {{ten_bien}}
            $table->string('label');
            $table->string('source_type'); // db_column, db_relation, formula, input, static
            $table->jsonb('source_config');
            $table->string('format')->default('text'); // text, number, currency, date, percent
            $table->integer('decimal_places')->default(0);
            $table->integer('display_order')->default(0);
            $table->timestamps();
        });

        Schema::create('form_print_logs', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->foreignUuid('template_id')->constrained('form_templates');
            $table->string('target_model');
            $table->uuid('target_id');
            $table->string('target_number')->nullable(); // contract_number, product_code...
            $table->jsonb('snapshot_data'); // snapshot tat ca field values
            $table->text('rendered_html');
            $table->foreignId('printed_by')->constrained('users');
            $table->timestamp('printed_at');
            $table->timestamps();
        });
    }

    public function down(): void {
        Schema::dropIfExists('form_print_logs');
        Schema::dropIfExists('form_fields');
        Schema::dropIfExists('form_templates');
    }
};
