<?php

namespace Tenant\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * Split billing: a folio can be divided across multiple payers, each
 * responsible for an amount (e.g. guest pays room, company pays extras).
 * Allocations are folio-level totals per payer, not tied to individual
 * line items — flagged as an assumption in the Phase 1 summary since the
 * spec didn't specify line-item-level split granularity.
 *
 * `payer_guest_id` is nullable because a payer can be a known guest OR a
 * free-text payer (e.g. "Acme Ltd — company account") with no guest record;
 * Phase 3's corporate_account table can attach to this later.
 */
class CreateFolioPayerAllocationsTable extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => [
                'type'           => 'INT',
                'constraint'     => 11,
                'unsigned'       => true,
                'auto_increment' => true,
            ],
            'folio_id' => [
                'type'     => 'INT',
                'constraint' => 11,
                'unsigned' => true,
            ],
            'payer_name' => [
                'type'       => 'VARCHAR',
                'constraint' => 150,
            ],
            'payer_guest_id' => [
                'type'     => 'INT',
                'constraint' => 11,
                'unsigned' => true,
                'null'     => true,
            ],
            'amount' => [
                'type'       => 'DECIMAL',
                'constraint' => '10,2',
            ],
            'notes' => [
                'type' => 'TEXT',
                'null' => true,
            ],
            'created_at' => ['type' => 'DATETIME', 'null' => true],
            'updated_at' => ['type' => 'DATETIME', 'null' => true],
        ]);

        $this->forge->addKey('id', true);
        $this->forge->addKey('folio_id');
        $this->forge->addForeignKey('folio_id', 'folios', 'id', '', 'CASCADE');
        $this->forge->addForeignKey('payer_guest_id', 'guests', 'id', '', 'SET NULL');
        $this->forge->createTable('folio_payer_allocations');
    }

    public function down()
    {
        $this->forge->dropTable('folio_payer_allocations', true);
    }
}
