<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class UpdateMemberKinForBeneficiarySelection extends Migration
{
    public function up()
    {
        if (!$this->db->tableExists('member_kin')) {
            return;
        }

        $fields = $this->db->getFieldNames('member_kin');

        if (!in_array('is_beneficiary', $fields, true)) {
            $this->forge->addColumn('member_kin', [
                'is_beneficiary' => [
                    'type' => 'TINYINT',
                    'constraint' => 1,
                    'default' => 0,
                    'after' => 'benefits',
                ],
            ]);
        }

        if (!in_array('installment_one_amount', $fields, true)) {
            $this->forge->addColumn('member_kin', [
                'installment_one_amount' => [
                    'type' => 'INT',
                    'constraint' => 11,
                    'default' => 3000000,
                    'after' => 'is_beneficiary',
                ],
            ]);
        }

        if (!in_array('installment_two_amount', $fields, true)) {
            $this->forge->addColumn('member_kin', [
                'installment_two_amount' => [
                    'type' => 'INT',
                    'constraint' => 11,
                    'default' => 3000000,
                    'after' => 'installment_one_amount',
                ],
            ]);
        }
    }

    public function down()
    {
        if (!$this->db->tableExists('member_kin')) {
            return;
        }

        $fields = $this->db->getFieldNames('member_kin');

        foreach (['installment_two_amount', 'installment_one_amount', 'is_beneficiary'] as $field) {
            if (in_array($field, $fields, true)) {
                $this->forge->dropColumn('member_kin', $field);
            }
        }
    }
}
