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

class Configuracoes extends Admin_Controller
{
	public function __construct() 
	{
		parent::__construct();
	}

	public function index() 
	{
	    $this->ini_method();
	    
	    Assets::add_module_js('sistema',array(
	        'configuracoes',
        ));
	    
	    $data['config'] = new stdClass();
	    $data['config']->public_key = $this->db->where('name','captcha_public_key')->get('sys_config')->row()->value;
	    $data['config']->private_key = $this->db->where('name','captcha_private_key')->get('sys_config')->row()->value;
        
        Template::set($data);	    
        Template::set_view('configuracoes_view');        
        Template::render();
	}
	
	public function update()
	{
        $this->load->library('form_validation');
        
        $this->form_validation->set_rules('captcha_public_key', 'Google Captcha Public Key', 'required|trim');
        $this->form_validation->set_rules('captcha_private_key', 'Google Captcha Private Key', 'required|trim');
        
        if ($this->form_validation->run() === FALSE) 
        {
            echo json_encode(array(
                'valid' => false,
                'retorno' => validation_errors('<p>', '</p>')
            ));
        }
        else
        {
            $campos = array( 'captcha_public_key', 'captcha_private_key');
            $data_update = $this->input->post();
            foreach($data_update as $key=>$item)
            {
                if(!in_array($key, $campos))
                    unset($data_update[$key]);
            }
            
            $error = FALSE;
            foreach($data_update as $key=>$value)
            {
                $result = $this->db->set('value', $value)->where('name',$key)->update('sys_config');
                if(!$result)
                {
                   $error = TRUE;
                }
            }
            
            // UPDATE
            if ($error === FALSE) 
            {
               echo json_encode(array(
                    'valid' => TRUE,
                    'retorno' => 'Configurações atualizadas com sucesso!' 
                ));
            }
            else
            {
                echo json_encode(array(
                    'valid' => FALSE,
                    'retorno' => 'Erro ao atualizar as configurações.'
                )); 
            }
        }	    
	}
}