<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AddCompetitionLockFields extends Migration
{
    public function up()
    {
        $db = \Config\Database::connect();

        if (!$db->tableExists('competitions')) {
            return;
        }

        $fields = [];
        if (!$db->fieldExists('is_locked', 'competitions')) {
            $fields['is_locked'] = ['type' => 'TINYINT', 'constraint' => 1, 'default' => 0];
        }
        if (!$db->fieldExists('locked_at', 'competitions')) {
            $fields['locked_at'] = ['type' => 'DATETIME', 'null' => true];
        }
        if (!$db->fieldExists('locked_by', 'competitions')) {
            $fields['locked_by'] = ['type' => 'INT', 'constraint' => 11, 'null' => true];
        }

        if (!empty($fields)) {
            $this->forge->addColumn('competitions', $fields);
        }
    }

    public function down()
    {
        $db = \Config\Database::connect();

        if (!$db->tableExists('competitions')) {
            return;
        }

        $columns = [];
        foreach (['is_locked', 'locked_at', 'locked_by'] as $column) {
            if ($db->fieldExists($column, 'competitions')) {
                $columns[] = $column;
            }
        }

        if (!empty($columns)) {
            $this->forge->dropColumn('competitions', $columns);
        }
    }
}
