<?php

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

return new class extends Migration
{
    public function up(): void
    {
        // Branch-level settings (overrides academy settings per branch)
        Schema::create('branch_settings', function (Blueprint $table) {
            $table->id();
            $table->foreignId('academy_id')->constrained('academies');
            $table->foreignId('branch_id')->constrained('branches');
            $table->string('key', 100);
            $table->text('value')->nullable();
            $table->string('group', 50)->default('general');
            $table->timestamps();

            $table->unique(['branch_id', 'key']);
            $table->index(['academy_id', 'branch_id', 'group']);
        });

        // Receipt templates — configurable per branch
        Schema::create('receipt_templates', function (Blueprint $table) {
            $table->id();
            $table->foreignId('academy_id')->constrained('academies');
            $table->foreignId('branch_id')->nullable()->constrained('branches');
            $table->string('name', 100);
            $table->string('name_ar', 100);
            $table->string('type', 30)->default('pos');
            $table->jsonb('sections')->default('[]');
            $table->jsonb('visible_fields')->default('[]');
            $table->jsonb('settings')->default('{}');
            $table->boolean('is_default')->default(false);
            $table->boolean('is_active')->default(true);
            $table->foreignId('created_by')->nullable()->constrained('users');
            $table->timestamps();

            $table->index(['academy_id', 'branch_id', 'type']);
        });

        DB::statement("ALTER TABLE receipt_templates ADD CONSTRAINT receipt_templates_type_check CHECK (type IN ('pos', 'invoice', 'enrollment', 'refund', 'payment'))");
    }

    public function down(): void
    {
        Schema::dropIfExists('receipt_templates');
        Schema::dropIfExists('branch_settings');
    }
};
