<?php

class RewardsRepository extends EntityRepository {
    
    private $table = 'rewards_settings';
    private $customerBuying =  null;
    private $rewardsSettings = null;
    public $flashmessenger = null;
    
    private $options = array (
        'min_amount_to_assign_points' => null,
        'points_assigned_for_min_amount'=>null,
        'calculate_points_with_price_without_taxes' => null,
        'min_point_to_reedem' => null,
        'value_for_each_point' => null,
        'max_life_days_of_points'=>null,
        'status' => null    
     );
    
    public function __construct() {
        if(!$this->flashmessenger instanceof FlashMessenger){
            $this->flashmessenger = new FlashMessenger();
        }
    }
    
    public function _getTranslation($text){
        return $this->flashmessenger->_getTranslation($text);
    }
    
    public function setOptions($data){
        foreach ($this->options as $option => $value){
            if(isset($data[$option])){
              $this->options[$option] = $data[$option];
            }
        }
    }
  
    public function getOptions(){
        return $this->options;
    }    

    public function save(array $data, $table = null) {    
        return parent::save($data, $this->table);
    }

    public function update($id, $data, $table = null) {             
        return parent::update($id, $data, $this->table);
    }

    public function getById($id, $table = null,$selectAux = null) {
        $select = "SELECT * "
                 . "FROM $this->table WHERE id = '$id'";
        $result = $this->query($select);

        if ($result->num_rows>0) {
            $set = $this->resultToArray($result);
            return $set[0];
        }
        return false;
    }
    
    public function getRewardsSettings(){
        if(is_null($this->rewardsSettings)){
            $this->rewardsSettings = $this->getById(1);
        }
        
        return $this->rewardsSettings;
    }
    
    public function setCustomerBuying(){        
        $this->customerBuying = $this->getCustomerBuying();
    }
    
    public function setCustomerBuyingFromPos($phone){
        $customerRepo = new CustomerRewardsRepository();
        $customerData = $customerRepo->getByPhone($phone);
        
        if(is_null($customerData)){
            return true;
        }else{
            $login = new Login();
            return parent::query("UPDATE rewards_customer_buying SET customer_id = '{$customerData['id']}',in_store_from = NOW() WHERE store_id = '{$login->getSucursal()}' ");
        }
    }
    
    public function getCustomerBuying(){
        $login = new Login();
        $idSucursal = $login->getSucursal();
        
        $query = "SELECT c.* "
                . "FROM rewards_customer_buying rc "
                . "LEFT JOIN rewards_customers c ON rc.customer_id = c.id "
                . "WHERE store_id = '$idSucursal' AND c.id > 0 AND DATE_ADD(rc.in_store_from, INTERVAL 3 MINUTE) >= NOW() ORDER BY in_store_from DESC ";
       
        $result = $this->query($query);
        
        if($result->num_rows > 0){
            return $this->resultToArray($result)[0];
        }
        
        return null;
    } 
    
    public function assignPointsToCustomer($saleId){
        /*Validamos si cliente registro su numero para obtener puntos*/
        /*Sino se registro su numero, no se le acumulan puntos*/
        $customerRewardData = $this->customerBuying;        
        if(is_null($customerRewardData)){return true;}
        
        /*Si registro su numero, se deben calcular los pntos*/      
        $rwdRules = new RewardsRulesRepository();        
        $rewards = $rwdRules->calculateRewards($saleId,$this->getRewardsSettings());               
        
        $array = array(
            'date'=>date('Y-m-d H:i:s'),
            'reward_customer_id'=>$customerRewardData['id'],
            'operation'=>'assign',
            'sales_id'=>$saleId,
            'points'=>$rewards['points'],
            'amount'=>$rewards['amount']
        );
        
        /*Se guarda registro de puntos asignados relacionados con la venta*/
        if($this->saveRecordPoints($array)){
            
            /*Calcular Fecha de vencimiento de puntos*/
            $rewardsSettings = $this->getRewardsSettings();
            $currentPoints = $customerRewardData['rewards']; /*Estos puntos son los que tenian antes de asignarles lo puntos de venta actual*/
            
            $cantidadDeCertificadosCurrent = intdiv(round($currentPoints,2),(float)$rewardsSettings['min_point_to_reedem']);             
            $cantidadDeCertificadosNew = intdiv(round((float)$currentPoints - (float) $this->points_used + (float)$rewards['points'] ,2),(float)$rewardsSettings['min_point_to_reedem']); 
            
            if($cantidadDeCertificadosNew > $cantidadDeCertificadosCurrent){
                $rewards_due_date = new DateTime();
                $rewards_due_date->modify("+{$rewardsSettings['max_life_days_of_points']} day");                     
                $rewards['rewards_due_date'] = $rewards_due_date->format('Y-m-d');            
            }        
            
            /*Se agregan puntos a la cuenta del cliente*/
            $rewardCustomerRepo = new RewardsCustomersRepository();
            $rewardCustomerRepo->addRewardsToCustomer($customerRewardData['id'],$rewards);  
                    
                        
        }       
        return true;
    }
    
    public function descontarPointsUsed($sale_id){
        /*Validamos si cliente registro su numero para usar puntos*/
        $customerRewardData = $this->customerBuying;        
        if(is_null($customerRewardData)){return true;}
        
        $query = "SELECT SUM(monto)as monto "
                . "FROM cobros "
                . "WHERE idVenta = $sale_id "
                . "AND formaPago = '10' "
                . "AND status = 1 ";
        
        $result = $this->query($query);
        
        if($result->num_rows > 0){
            $result = $result->fetch_object();
            if((float)$result->monto > 0){
                $rewardSettings = $this->getRewardsSettings();
                
                $points = round($result->monto/$rewardSettings['value_for_each_point'],2);
                $amount = round($result->monto,2);
                
                $array = array(
                    'date'=>date('Y-m-d H:i:s'),
                    'reward_customer_id'=>$customerRewardData['id'],
                    'operation'=>'reddem',
                    'sales_id'=>$sale_id,
                    'points'=>$points,
                    'amount'=>$amount
                );

                /*Se guarda registro de puntos asignados relacionados con la venta*/
                if($this->saveRecordPoints($array)){
                    $rewardCustomerRepo = new RewardsCustomersRepository();
                    $rewards = array('points'=>$points,'amount'=>$amount);
                    $this->points_used = $points;
                    $rewardCustomerRepo->descontarRewardsToCustomer($customerRewardData['id'],$rewards);     
                }
            }            
        }
        
        return true;
    }
    
    /*Historial de registros*/
    public function saveRecordPoints($data){
        return parent::save($data, 'rewards_records');
    }        
    
    public function clearCustomerBuying(){
        $login = new Login();
        $store_id = $login->getSucursal();
        
        $query = "UPDATE rewards_customer_buying "
                . "SET customer_id = 0 "
                . "WHERE store_id = $store_id";
        
        var_dump($this->query($query));exit;
        
        return $this->query($query);
    }
    
    
    public function getListStatus(){
        $query = "SELECT * FROM status_code WHERE operation = 'Rewards'";
        $result = $this->query($query);
        
        if($result->num_rows > 0){
            $array = array();
            foreach($result as $status){
                $array[$status['code']] = $status['description'];
            }
            return $array;
        }
        return null;
    }
    
}