<?php
/**
 * Description of Ajax
 *
 * @author carlos
 */
class ExpenseConfigAjax extends ExpenseConfigRepository {
    
    public $flashmessenger = null;
    
    public function __construct() {
        if(!$this->flashmessenger instanceof FlashMessenger){
            $this->flashmessenger = new FlashMessenger();
        }
    }
    
    public function getResponse($request, $options) {
        return $this->$request($options);
    }
    
    public function _getTranslation($text){
        $translator = new Translator();
        return $translator->_getTranslation($text);
    }
    
    public function getTranslation($options){
        $msj = $options['msj'];
        
        return array(
            'response'=>true,
            'translation'=>$this->_getTranslation($msj)
                );
    }    
    
    public function saveConfig($options){       
        $data = array();
        foreach($options['options'] as $key => $option){  //var_dump($option);    
           
            if(strpos($option['name'], 'cost_')!== false){
                $name = str_replace('cost_', '', $option['name']);
                $data[$name]['cost'] = $option['value'];
            }

            if(strpos($option['name'], 'duedate_')!== false){
                $name = str_replace('duedate_', '', $option['name']);
                $data[$name]['duedate'] = $option['value'];
            }                    
        }     
        
        set_error_handler(function ($err_severity, $err_msg, $err_file, $err_line, array $err_context){
            throw new ErrorException( $err_msg, 0, $err_severity, $err_file, $err_line );
        }, E_WARNING);
        
        try{
            $this->_saveConfig($data);
            $this->flashmessenger->addMessage(array('success'=>'Configuracion de gastos guardada correctamente.'));
            
             return array(
                'response' => true,
                'msj'=>$this->flashmessenger->getRawMessage(),
            );
        } catch (Exception $ex) {
            $this->flashmessenger->addMessage(array('success'=>'Error al guardar configuracion de gastos.'));
            restore_error_handler();            
            
             return array(
                'response' => null,
                'msj'=>$this->flashmessenger->getRawMessage(),
            );
        }    
    }
}