<?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
    {
        Schema::create('document_number_settings', function (Blueprint $table) {
            $table->id(); $table->foreignId('business_id')->index(); $table->string('type');
            $table->string('prefix', 30); $table->unsignedBigInteger('next_number')->default(1);
            $table->unsignedTinyInteger('padding')->default(5); $table->string('separator', 3)->default('-');
            $table->timestamps(); $table->unique(['business_id', 'type']);
        });
        Schema::create('document_templates', function (Blueprint $table) {
            $table->id(); $table->foreignId('business_id')->index(); $table->string('name');
            $table->string('type')->default('all'); $table->string('accent_color', 10)->default('#3454d1');
            $table->string('logo_path')->nullable(); $table->text('header_text')->nullable();
            $table->text('footer_text')->nullable(); $table->boolean('is_default')->default(false);
            $table->timestamps();
        });
        Schema::table('trade_documents', function (Blueprint $table) {
            $table->foreignId('template_id')->nullable()->index();
            $table->foreignId('requested_by')->nullable()->index();
            $table->dateTime('requested_at')->nullable();
            $table->text('rejection_reason')->nullable();
            $table->unsignedInteger('resubmission_count')->default(0);
            $table->uuid('acceptance_token')->nullable()->unique();
            $table->string('customer_email')->nullable();
            $table->string('customer_decision')->nullable();
            $table->text('customer_comment')->nullable();
            $table->dateTime('customer_decided_at')->nullable();
            $table->dateTime('sent_at')->nullable();
            $table->foreignId('transaction_id')->nullable()->index();
        });
        Schema::table('transactions', function (Blueprint $table) {
            $table->foreignId('trade_document_id')->nullable()->index();
        });
        Schema::create('trade_document_approval_histories', function (Blueprint $table) {
            $table->id(); $table->foreignId('trade_document_id')->index(); $table->foreignId('user_id')->nullable()->index();
            $table->string('action'); $table->string('from_status')->nullable(); $table->string('to_status')->nullable();
            $table->text('comment')->nullable(); $table->timestamps();
        });
        Schema::create('trade_document_payments', function (Blueprint $table) {
            $table->id(); $table->foreignId('trade_document_id')->index(); $table->foreignId('recorded_by')->nullable()->index();
            $table->decimal('amount', 15, 2); $table->string('method')->nullable(); $table->string('reference')->nullable();
            $table->dateTime('paid_at'); $table->text('notes')->nullable(); $table->timestamps(); $table->softDeletes();
        });
        Schema::create('trade_document_deliveries', function (Blueprint $table) {
            $table->id(); $table->foreignId('trade_document_id')->index(); $table->foreignId('sent_by')->nullable()->index();
            $table->string('recipient'); $table->string('status')->default('pending'); $table->text('error')->nullable();
            $table->dateTime('sent_at')->nullable(); $table->timestamps();
        });

        foreach (['approve_trade_documents', 'configure_trade_documents'] as $name) {
            DB::table('permissions')->insertOrIgnore(['name'=>$name,'guard_name'=>'web','created_at'=>now(),'updated_at'=>now()]);
            $permissionId = DB::table('permissions')->where('name',$name)->value('id');
            foreach (DB::table('roles')->whereRaw('LOWER(name) = ?', ['admin'])->pluck('id') as $roleId) {
                DB::table('role_has_permissions')->insertOrIgnore(['permission_id'=>$permissionId,'role_id'=>$roleId]);
            }
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('trade_document_deliveries');
        Schema::dropIfExists('trade_document_payments');
        Schema::dropIfExists('trade_document_approval_histories');
        Schema::table('transactions', fn (Blueprint $table) => $table->dropColumn('trade_document_id'));
        Schema::table('trade_documents', fn (Blueprint $table) => $table->dropColumn([
            'template_id','requested_by','requested_at','rejection_reason','resubmission_count','acceptance_token',
            'customer_email','customer_decision','customer_comment','customer_decided_at','sent_at','transaction_id',
        ]));
        Schema::dropIfExists('document_templates');
        Schema::dropIfExists('document_number_settings');
    }
};
