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

class Migration_ajax extends Admin_Controller {

	function __construct()
	{
        parent::__construct();
		
        $this->load->model('sistema/Configuracoes_model');
        $this->load->model('administrativo/admin_model');
	}
	
	public function insert_sql()
	{
	    $post = $this->input->post();
	    $post['status'] = 1;
	    
	    $id_sql = $this->Configuracoes_model->insere_sql($post);
	    echo json_encode(['valid' => true, 'msg' => 'Sucesso', 'insert' => $id_sql]);
	}
	
	public function atualiza_sql()
	{
	    $post = $this->input->post();
	    $responsavel = $this->session->all_userdata();
	    
	    $post['id_cadastro'] = $responsavel['id_cadastro'];
	    
	    $valid =  $this->Configuracoes_model->update_sql($post['id_sql'], $post);
	    if($valid == TRUE){
	        $sql = $this->Configuracoes_model->get_sql($post['id_sql']);
	        
	        $data = array([
	            'data_hora'=> date("d/m/Y H:i", strtotime($sql->data_hora)), 
	            'responsavel'=> $sql->nome]
	        );
	        
	        echo json_encode(['valid' => $valid, 'msg' => 'Atualizado com sucesso', 'update' => $data]);
	    }
	    else{
	        echo json_encode(['valid' => $valid, 'msg' => 'Erro, não foi possível atualizar.', 'update' => $sql]);
	    }
	}
	
	public function inativa_sql()
	{
	    $post = $this->input->post();
	    $responsavel = $this->session->all_userdata();
	    $post['id_cadastro'] = $responsavel['id_cadastro'];
	    $post['status'] = 0;
	    
	    $valid =  $this->Configuracoes_model->update_sql($post['id_sql'], $post);
	    echo json_encode(['valid' => $valid, 'msg' => 'Excluído com sucesso', 'delete' => $post]);
	    
	}
	
	public function delete_sql()
	{
	    $post = $this->input->post();
	    $valid =  $this->Configuracoes_model->delete_sql($post['id_sql'], $post);
	    
	    echo json_encode(['valid' => $valid, 'msg' => 'Excluído com sucesso', 'delete' => $post]);
	    
	}
	
	private function create_file_version($post_array)
    {
        $path = APPPATH.'migrations/'.$version.'_version.php';  
      
	    $file = fopen($path, "w");
        $txt = "<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');\n\nclass Migration_Version extends CI_Migration\n{\n";
        $txt .= "\tpublic function __construct() \n\t{\n\t\tparent::__construct();\n\t}\n\n";
        $txt .= "\tpublic function {$method}() \n\t{\n\n\t}\n}";
        
        fwrite($file, $txt);
        fclose($file);
    }
}