<?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('manual_journal_vouchers', function (Blueprint $table): void {
            $table->id(); $table->ulid('public_id')->unique();
            $table->foreignId('company_id')->constrained()->cascadeOnDelete();
            $table->foreignId('branch_id')->constrained()->restrictOnDelete();
            $table->string('voucher_number')->unique();
            $table->date('posting_date'); $table->date('document_date');
            $table->string('reference_number')->nullable(); $table->text('description');
            $table->char('currency_code',3)->default('AED'); $table->decimal('exchange_rate',20,8)->default(1);
            $table->decimal('debit_total',20,4)->default(0); $table->decimal('credit_total',20,4)->default(0);
            $table->string('status',30)->default('draft')->index();
            $table->foreignId('approved_by')->nullable()->constrained('users')->nullOnDelete(); $table->timestamp('approved_at')->nullable();
            $table->timestamp('posted_at')->nullable(); $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();
        });
        Schema::create('manual_journal_lines', function (Blueprint $table): void {
            $table->id(); $table->foreignId('manual_journal_voucher_id')->constrained()->cascadeOnDelete(); $table->unsignedInteger('line_number');
            $table->foreignId('account_id')->constrained()->restrictOnDelete(); $table->foreignId('party_id')->nullable()->constrained()->restrictOnDelete();
            $table->string('party_ledger',20)->nullable(); $table->foreignId('department_id')->nullable()->constrained()->nullOnDelete(); $table->foreignId('cost_center_id')->nullable()->constrained()->nullOnDelete();
            $table->text('description')->nullable(); $table->decimal('debit',20,4)->default(0); $table->decimal('credit',20,4)->default(0); $table->timestamps();
            $table->unique(['manual_journal_voucher_id','line_number'],'manual_journal_line_unique');
        });
    }
    public function down(): void { Schema::dropIfExists('manual_journal_lines'); Schema::dropIfExists('manual_journal_vouchers'); }
};
