<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

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

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

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

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

        if (in_array('is_beneficiary', $fields, true)) {
            $this->db->table('member_kin')
                ->where('is_beneficiary', 1)
                ->update([
                    'installment_one_selected' => 1,
                    'installment_two_selected' => 1,
                ]);
        }
    }

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

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

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