<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Migration_Version_615 extends CI_Migration
{
    public function __construct()
    {
        parent::__construct();
    }

    public function up()
    {
        $this->defer_indexes('615');

        if ($this->table_exists('tbl_config')) {
            $this->db->where('config_key', 'version')->update('tbl_config', array('value' => '6.1.5'));
        }
    }

    public function down()
    {
        $indexes = array(
            array('table' => 'tbl_transactions', 'name' => 'idx_tbl_transactions_date'),
            array('table' => 'tbl_transfer', 'name' => 'idx_tbl_transfer_date'),
            array('table' => 'tbl_journals', 'name' => 'idx_tbl_journals_date'),
        );

        foreach ($indexes as $index) {
            if ($this->table_exists($index['table']) && $this->index_exists($index['table'], $index['name'])) {
                $this->db->query("ALTER TABLE `{$index['table']}` DROP INDEX `{$index['name']}`");
            }
        }

        if ($this->table_exists('tbl_config')) {
            $this->db->where('config_key', 'version')->update('tbl_config', array('value' => '6.1.4'));
        }
    }

    private function table_exists($table)
    {
        return $this->db->table_exists($table);
    }

    private function index_exists($table, $indexName)
    {
        $result = $this->db->query("SHOW INDEX FROM `{$table}` WHERE Key_name = " . $this->db->escape($indexName));
        return $result && $result->num_rows() > 0;
    }

    private function defer_indexes($version)
    {
        if (!$this->db->table_exists('tbl_config')) {
            return;
        }

        $key = 'deferred_upgrade_indexes';
        $existing = $this->db->where('config_key', $key)->get('tbl_config')->row_array();
        $versions = !empty($existing['value']) ? array_filter(array_map('trim', explode(',', $existing['value']))) : array();
        if (!in_array($version, $versions, true)) {
            $versions[] = $version;
        }
        $value = implode(',', $versions);

        if (!empty($existing)) {
            $this->db->where('config_key', $key)->update('tbl_config', array('value' => $value));
            return;
        }

        $this->db->insert('tbl_config', array('config_key' => $key, 'value' => $value));
    }
}
