<?php
/**
 * Description of Ajax
 *
 * @author carlos
 */
class Ajax extends EntityRepository {
    
    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 confirmAction($options){
        $query = "SELECT * FROM users WHERE master_key = '{$options['masterKey']}' LIMIT 1";
        $result = $this->query($query);
        
        $data = null;
        if($result->num_rows > 0){
            $result = $this->resultToArray($result);
            $data = $result[0];            
        }
        
        if($data){
            $operacion = $options['operation'];
            $permisos = array(
                'edit_salesRecord'=>array('1'), #admin, supervisor
                'special_decorated'=>array('1'), #admin, supervisor
                'edit_special_order'=>array('1'),
                'delete_special_order_detail'=>array('1'),
                'delete_special_order'=>array('1')
            );
            
            $permiso = $permisos[$operacion];
            if(in_array($data['role'], $permiso)){
                return array(
                    'response'=>true
                );
            }else{
                $this->flashmessenger->addMessage(array('danger'=>'No tienes provilegios para confirmar esta operacion.'));
                return array(
                    'response'=>false,
                    'msg'=>$this->flashmessenger->getMessageString());
            } 
            
        }else{
            $this->flashmessenger->addMessage(array('danger'=>'Clave incorrecta.'));
            return array(
                    'response'=>false,
                    'msg'=>$this->flashmessenger->getMessageString());
        }         
    }
    
    public function deleteFile(array $file){
        $fileDelete = $file['fileDelete'];
        if (unlink(ROOT.$fileDelete)) {
            $response = true;
            $this->flashmessenger->addMessage(array('success'=>'Documento eliminado correctamente.'));
        }
        else{
            $response = null;
            $this->flashmessenger->addMessage(array('danger'=>'Eror al tratat de eliminar documento.'));
        }

        return array(
            'response' => true,
            'msj'=>$this->flashmessenger->getMessageString(),
        );
    }
    
    public function setLanguage($options){
        $translator = new Translator();
        $translator->setLenguage($options['language']);
        
        $login = new Login();
        $entityRepo = new EntityRepository();
        $entityRepo->update($login->getId(), array('language'=>$options['language']), 'users');
        
        return array('response'=>true);
    }
    
    public function saveForm($options){
        $data = array();
        foreach($options['options'] as $row){
            $data[$row['name']] = $row['value'];
        }  
        
        switch($data['formName']){
            case 'customer':
                $form = new CustomerForm();
                $form->populate($data);
                $isValid = $form->isValid();
                
                if($isValid){
                    $customerRepo = new CustomerRepository();
                    $id = $data['id'];
                    $customerRepo->setOptions($data);
                    
                    if(!is_null($id) && trim($id) != ''){
                        $customerRepo->update($id,$customerRepo->getOptions());
                    }else{
                        $customerRepo->save($customerRepo->getOptions());
                        $id = $customerRepo->getLastInsertId();
                    }
                    
                    return array(
                        'response'=>true,
                        'customer_id'=>$id
                    );                    
                }else{
                    return array(
                        'response'=>false,
                        'msg'=>$this->flashmessenger->getMessageString(),
                        'errorElements'=>$form->getNameElementWithError()
                    );
                }
                break;
                
            case 'customerAddress':
                $form = new CustomerAddressForm();
                $form->populate($data);
                $isValid = $form->isValid();
                
                if($isValid){
                    $customerAddressRepo = new CustomerAddressRepository();
                    $id = $data['id'];
                    $customerAddressRepo->setOptions($data);
                    
                    if(!is_null($id) && trim($id) != ''){
                        $customerAddressRepo->update($id,$customerAddressRepo->getOptions());
                    }else{
                        $customerAddressRepo->save($customerAddressRepo->getOptions());
                    }
                    
                    return array(
                        'response'=>true
                    );                    
                }else{
                    return array(
                        'response'=>false,
                        'msg'=>$this->flashmessenger->getMessageString(),
                        'errorElements'=>$form->getNameElementWithError()
                    );
                }
                break;
                
             case 'paymentterms':
                $form = new PaymentTermsForm();
                $form->populate($data);
                $isValid = $form->isValid();
                
                if($isValid){
                    $paymentTermsRepo = new PaymentTermsRepository();
                    $id = $data['id'];
                    $paymentTermsRepo->setOptions($data);
                    
                    if(!is_null($id) && trim($id) != ''){
                        $paymentTermsRepo->update($id,$paymentTermsRepo->getOptions());
                    }else{
                        $paymentTermsRepo->save($paymentTermsRepo->getOptions());
                        $id = $paymentTermsRepo->getLastInsertId();
                    }
                    
                    return array(
                        'response'=>true,
                        'payment_terms_id'=>$id
                    );                    
                }else{
                    return array(
                        'response'=>false,
                        'msg'=>$this->flashmessenger->getMessageString(),
                        'errorElements'=>$form->getNameElementWithError()
                    );
                }
                break;
        }
    }
    
    public function getCustomerList($options){
        $customerRepo = new CustomerRepository();
        $customerList = $customerRepo->getListSelectCustomers();
        
        $string = '<option value="">'.$this->flashmessenger->_getTranslation('Selccionar una opcion...').'</option>';
        if($customerList){
            foreach($customerList as $key => $value){
                $string .= "<option value='{$key}'>{$value}</option>";
            }
        }
        
        return array(
            'response'=>true,
            'customerList'=>$string
        );
       
    }
    
    public function getPaymentTermsList($options){
        $customerRepo = new PaymentTermsRepository();
        $paymentTermList = $customerRepo->getListSelectPaymentTerms();
        
        $string = '<option value="">'.$this->flashmessenger->_getTranslation('Selccionar una opcion...').'</option>';
        if($paymentTermList){
            foreach($paymentTermList as $key => $value){
                $string .= "<option value='{$key}'>{$value}</option>";
            }
        }
        
        return array(
            'response'=>true,
            'paymentTermList'=>$string
        );
       
    }
}