<?php

namespace Tenant\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * One row per pay period. `status` moves draft -> finalized -> paid:
 * draft is editable (payslips/line items can still change), finalized
 * locks the numbers (mirrors how bookings/complaints use a terminal
 * status once a record is "done"), paid is a separate, later step
 * recording that the manager has actually paid staff through their own
 * existing means — `payment_reference` is a free-text note (e.g. "MoMo
 * batch transfer 14 Aug", "Cash paid at front desk"), not a real
 * disbursement integration. See the plan's payroll section for why
 * disbursement was deliberately out of scope.
 */
class CreatePayrollRunsTable extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => [
                'type'           => 'INT',
                'constraint'     => 11,
                'unsigned'       => true,
                'auto_increment' => true,
            ],
            'period_month' => [
                'type' => 'DATE',
                'comment' => 'First day of the pay period month',
            ],
            'status' => [
                'type'       => 'VARCHAR',
                'constraint' => 20,
                'default'    => 'draft',
                'comment'    => 'draft, finalized, paid',
            ],
            'created_by' => [
                'type'       => 'INT',
                'constraint' => 11,
                'unsigned'   => true,
                'null'       => true,
            ],
            'finalized_at' => ['type' => 'DATETIME', 'null' => true],
            'paid_at'      => ['type' => 'DATETIME', 'null' => true],
            'payment_reference' => [
                'type'       => 'VARCHAR',
                'constraint' => 255,
                'null'       => true,
            ],
            'created_at' => ['type' => 'DATETIME', 'null' => true],
            'updated_at' => ['type' => 'DATETIME', 'null' => true],
        ]);

        $this->forge->addKey('id', true);
        $this->forge->addForeignKey('created_by', 'users', 'id', '', 'SET NULL');
        $this->forge->createTable('payroll_runs');
    }

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