<?php

class RewardsRulesRepository extends EntityRepository {
    
    private $table = 'rewards_rules';
    private $options = array (
        'name' => null,
        'type_of_points'=>null,
        'product_id' => null,
        'start_date' => null,
        'end_date' => null,
        'status'=>null   
     );
    
    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) {   
        $tools = new Tools();
        $data['start_date'] = $tools->setFormatDateTimeToDB($data['start_date']);
        $data['end_date'] = $tools->setFormatDateTimeToDB($data['end_date']);
        
        return parent::save($data, $this->table);
    }

    public function update($id, $data, $table = null) {
        $tools = new Tools();
        $data['start_date'] = $tools->setFormatDateTimeToDB($data['start_date']);
        $data['end_date'] = $tools->setFormatDateTimeToDB($data['end_date']);
        
        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 delete($id, $table = null) {        
        return parent::delete($id, $this->table);
    }

    public function isUsedInRecord($id, array $buscarEn = null,$andWhere= null) {
        return parent::isUsedInRecord($id, array('rewards_records'=>'reward_customer_id'));   
    }
    
     public function getListRules(){
        $query = "SELECT "
                . "id,"
                . "name,"
                . "product_id,"
                . "type_of_points,"
                . "DATE_FORMAT(start_date,'%m/%d/%Y %h:%i %p')as formated_start_date,"
                . "DATE_FORMAT(end_date,'%m/%d/%Y %h:%i %p')as formated_end_date,"
                . "fxGetStatusName(status,'status','RewardsRules')as status_name "
                . " FROM $this->table ORDER BY id ASC";
        
        $result = $this->query($query);
        
        if($result){
            $data = $this->resultToArray($result);
            
            $productsRepo = new PosProductoRepository();
            $productList = $productsRepo->getListaProductos();
            
            if($productList){
                $productArray = array();
                foreach($productList as $product){$productArray[$product['id']] = $product['descripcion'];}
                
                /*Obtener nombre de prodctos*/              
                foreach($data as $keyData => $row){
                    $productName = '';
                    $productForRule = explode(',', $row['product_id']);
                    foreach($productForRule as $key => $productId){
                        $productName .= $productArray[$productId];
                    }       
                
                    $data[$keyData]['product_name'] = $productName;
                }
            }         
            
            return $data;
        }
        
        return null;
    }  

    public function calculateRewards($saleId,$rewardSettingsData){       
        $activeRules = $this->getActiveRules(); 
        
        $ventaRepo = new VentaRepository();
        $products =  $ventaRepo->getVentaDetallesSaved($saleId);        
          
        $precio = 'precio_sin_impuestos';
        if($rewardSettingsData['calculate_points_with_price_without_taxes'] == '2'){$precio = 'precio';}
        
        $pointsGenerated = 0;
        foreach($products as $product){
            $muliplier = 1;          
            $amount = round((float)$product['cantidad'] * (float)$product[$precio],2);
            
            if(key_exists($product['idProducto'], $activeRules)){
                $muliplier = (float)$activeRules[$product['idProducto']];                
            }
            
            $pointsByProduct = intdiv(round($amount,2),(float)$rewardSettingsData['min_amount_to_assign_points']);            
            $pointsGenerated += $pointsByProduct * $muliplier;            
        }
        
        $amount = $pointsGenerated * (float)$rewardSettingsData['value_for_each_point'];

        return array(
            'points'=>$pointsGenerated, 
            'amount'=>$amount,
        ); 
    }
    
    public function getActiveRules(){
        $query = "SELECT * FROM $this->table "
                . "WHERE status = 1 "
                . "AND NOW() BETWEEN start_date AND end_date ";
        
        $result = $this->query($query);
        
         $arrayRules = array();
        if ($result->num_rows>0) {           
            $rules = $this->resultToArray($result);
            if($rules){
                foreach($rules as $rule){
                    if(strpos(trim($rule['product_id'],','), ',') ){
                        $productIds = explode(',', $rule['product_id']);                    
                        foreach($productIds as $productId){
                             $arrayRules[$productId] = $rule['type_of_points'];
                        }
                    }else{
                        $arrayRules[$rule['product_id']] = $rule['type_of_points'];
                    }                
                }
            }
        }
        
       return $arrayRules;
    }
    
     public function getListStatus(){
        $query = "SELECT * FROM status_code WHERE operation = 'RewardsRules'";
        $result = $this->query($query);
        
        if($result->num_rows > 0){
            $array = array();
            foreach($result as $status){
                $array[$status['code']] = $status['description'];
            }
            return $array;
        }
        return null;
    }

    public function createFilterFecha($options,$campoFecha = null ){
        $fechaInicio = $options['fechaInicio'];
        $fechaFin = $options['fechaFin'];
        $fecha = null;
        $tools = new Tools();
        if($fechaInicio!=null){
            $fechaInicio = $tools->setFormatDateToDB($fechaInicio);
            if($fechaFin!=null){
                $fechaFin = $tools->setFormatDateToDB($fechaFin);
                $fecha .=" AND $campoFecha BETWEEN '{$fechaInicio}' AND '{$fechaFin}' ";
            }else{
                $fecha .=" AND $campoFecha BETWEEN '{$fechaInicio}' AND '{$fechaInicio}' ";
            }
        }elseif($fechaFin!=null){
            $fecha .=" AND $campoFecha BETWEEN '{$fechaFin}' AND '{$fechaFin}' ";
        }
        
        return $fecha;
    }
}