<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AddPreferredCityIdToUsers extends Migration
{
    public function up()
    {
        if (!$this->db->fieldExists('preferred_city_id', 'users')) {
            $this->forge->addColumn('users', [
                'preferred_city_id' => [
                    'type'       => 'INT',
                    'constraint' => 11,
                    'unsigned'   => true,
                    'null'       => true,
                    'after'      => 'location',
                ],
            ]);
        }
        try {
            $this->db->query('CREATE INDEX users_preferred_city_id_idx ON users (preferred_city_id)');
        } catch (\Throwable $e) {
        }
        try {
            $this->db->query('ALTER TABLE users
                ADD CONSTRAINT users_preferred_city_id_fk
                FOREIGN KEY (preferred_city_id)
                REFERENCES rewarder_cities(id)
                ON UPDATE RESTRICT
                ON DELETE SET NULL');
        } catch (\Throwable $e) {
        }
    }

    public function down()
    {
        try {
            $this->db->query('ALTER TABLE users DROP FOREIGN KEY users_preferred_city_id_fk');
        } catch (\Throwable $e) {
        }
        if ($this->db->fieldExists('preferred_city_id', 'users')) {
            $this->forge->dropColumn('users', 'preferred_city_id');
        }
    }
}

