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

class Migration extends CI_Controller//Admin_Controller
{
    function __construct()
    {
        parent::__construct();
        
        $this->load->config('migration');
        $this->load->library('migration');
        
    }
    
    public function index()
    {
        if ($this->config->item('migration_enabled') == true) 
        {
            $cg_version = $this->config->item('migration_version');
            $db_version = $this->db->select('version')->get('migrations')->row()->version ?? 0;
           
            if($cg_version > $db_version)
            {
                $db_version++;
                for ($db_version; $db_version <= $cg_version; $db_version++) {
                   $this->config->set_item('migration_version', $db_version); 
                   $this->migrate_version($db_version);
                }
            }
            else
            {
                $this->migrate_current();
            }
        }
        
    }
    
    private function migrate_current()
    {
        $this->load->library('migration');
        if ($this->migration->current() === FALSE)
        {
            show_error($this->migration->error_string());
        }
        else 
        {
            echo('Versão: '.$this->config->item('migration_version').' atualizada com sucesso!');
        }
    }
    
    private function migrate_version($v)
    {
        $this->load->library('migration');
        if ($this->migration->version($v) === FALSE)
        {
            show_error($this->migration->error_string());
        }
        else 
        {
            echo('Versão: '.$this->config->item('migration_version').' atualizada com sucesso!');
        }
    }

}