<?php

namespace Tenant\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * A folio can have multiple payment rows (e.g. two partial cash payments).
 * `method` is cash/mobile_money/card/bank_transfer in Phase 1 (plain
 * VARCHAR, no gateway); `reference` stays null until Phase 3 populates it
 * with a Hubtel transaction ID for method=hubtel_momo — no restructuring
 * needed, just new values. Deliberately no `updated_at`: payment rows are
 * immutable once recorded (corrections are a new row / void flow, not an
 * edit-in-place), matching the spec's exact field list for this table.
 */
class CreateFolioPaymentsTable 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,
            ],
            'amount' => [
                'type'       => 'DECIMAL',
                'constraint' => '10,2',
            ],
            'method' => [
                'type'       => 'VARCHAR',
                'constraint' => 30,
                'comment'    => 'cash, mobile_money, card, bank_transfer in Phase 1',
            ],
            'reference' => [
                'type'       => 'VARCHAR',
                'constraint' => 100,
                'null'       => true,
            ],
            'recorded_by' => [
                'type'     => 'INT',
                'constraint' => 11,
                'unsigned' => true,
            ],
            'paid_at' => [
                'type' => 'DATETIME',
            ],
            'created_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('recorded_by', 'users', 'id', '', 'RESTRICT');
        $this->forge->createTable('folio_payments');
    }

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