<?php
/**
 * Description of Ajax
 *
 * @author carlos
 */
class RewardsAjax extends RewardsRepository {
    
    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 getRewardData($options){
        /*Validar primero si cajero ingreso un telefono en la pantalla de POS
         Si cajero ingreso numero, este numero sobreescribe lo que se haya ingresado desde tablet */        
        if(!empty($options['phone'])){
            /*Eliminados customer_id que se haya ingresado desde tablet*/
            $this->clearCustomerBuying();
            
            /*Validamos que numero sea correcto*/
            if(strlen($options['phone']) == '14'){
                /*Si es correcto buscamos y asignamos customer_id en campo customer_buying*/
                $this->setCustomerBuyingFromPos($options['phone']);
            }else{
                /*Sino es correcto mandamos mensaje en ventana de pago*/
                $this->flashmessenger->addMessage(array('danger'=>'Formato de telefono ingresado no es correcto.'));
                return array(
                    'response'=>null,
                    'msj'=>$this->flashmessenger->getMessageString()
                );
            }            
        }
        
        $sales_balance = $options['balance'];
        
        $rewardsRepo = new RewardsRepository();
        $customerRewardData = $rewardsRepo->getCustomerBuying();
      
        if(is_null($customerRewardData)){
            $this->flashmessenger->addMessage(array('danger'=>'No se encontro cliente para acumular puntos.'));
            return array(
                'response'=>null,
                'msj'=>$this->flashmessenger->getMessageString());
        }
        
        $rewardSedttings = $rewardsRepo->getRewardsSettings();       
        $minPointToReedem = $rewardSedttings['min_point_to_reedem'];
        $customerAcumulatedPoints = $customerRewardData['rewards'];
        $valueForPoint = $rewardSedttings['value_for_each_point'];
        
        $pointsAvailableToUse = 0;
        if($customerAcumulatedPoints >= $minPointToReedem){
            $pointsAvailableToUse = intdiv((float)$customerAcumulatedPoints,(float)$minPointToReedem);  
            $pointsAvailableToUse = $pointsAvailableToUse * $minPointToReedem;
            
            $amountAvailableToUse = round($pointsAvailableToUse * (float)$valueForPoint,2);
        }else{
            /*Verifico sin en venta existen productos con Reedem Especial*/
            $ventasRepo = new VentaRepository();
            $productosVendidos = $ventasRepo->getVentaDetalles();
            
            $rewardsReedem = new RewardsReedemRepository();
            $activeReedems = $rewardsReedem->getActiveReedem();            
            
            foreach($productosVendidos as $producto){
                if(key_exists($producto['idProducto'], $activeReedems)){
                    $rewardsRequired = $activeReedems[$producto['idProducto']];
                    
                    if($customerAcumulatedPoints > $rewardsRequired){
                        $customerAcumulatedPoints -= $rewardsRequired;
                        $pointsAvailableToUse += $rewardsRequired;
                    }                    
                }
            }
            
            $amountAvailableToUse = round($pointsAvailableToUse * (float)$valueForPoint,2);            
        }
        
        if($pointsAvailableToUse > 0){
            $msj = "Cliente <strong>{$customerRewardData['name']} {$customerRewardData['last_name']}</strong> tiene puntos listos para canjear.";
            $msj .= "<p>Puntos: ".$pointsAvailableToUse." |  Monto: $".number_format($amountAvailableToUse,2)."</p>";
                       
            if((float)$sales_balance >= (float)$amountAvailableToUse){
                $amountToApply = $amountAvailableToUse;
            }else{
                $amountToApply = (float)$sales_balance;
            }
            
            return array(
                'response'=>true,
                'msj'=>$msj,
                'points'=>$pointsAvailableToUse,
                'amount'=>$amountAvailableToUse,
                'amount_to_apply'=>$amountToApply
            );
            
        }else{                      
            $this->flashmessenger->addMessage(array('warning'=>'Cliente no tiene puntos disponibles para canjear.'));
            $msj = $this->flashmessenger->getMessageString();
            
            return array(
                'response'=>null,  
                'msj'=> $msj
            );
        }                       
    }
}