<?php
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class InventarioRepository extends EntityRepository {

    private $table = 'inventario';

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

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

    public function getById($id, $table = null,$selectAux = null) {
        return parent::getById($id, $this->table,$selectAux);
    }
    
    public function getListInventarioPorSucursal($storeId) {
        $select = "SELECT * from $this->table WHERE id_store = '{$storeId}' ";
        $result = $this->query($select);

        if ($result->num_rows > 0) {
           $result = $this->resultToArray($result);           
            
           $array = array();
           foreach ($result as $row){
               $array[$row['id_product']] = $row;
           }
           
           return $array;
        }
        return null;
    }
    
     public function getInventorySucursalByIdProduct($idProduct,$idStore){
        $query = "SELECT id,IFNULL(stock,0)as stock FROM $this->table WHERE id_product = $idProduct AND id_store = $idStore ";
        $result = $this->query($query);
        
        if($result->num_rows > 0){            
            return $this->resultToArray($result)[0];
        }
        return null;
    }
    
     public function addInventory($array){
        $idProduct = $array['id_product'];
        $quantity = $array['quantity'];
        $sucursal = $array['sucursal'];
        
        if($quantity != 0){
            $currentStock = null;
            $data = $this->getInventorySucursalByIdProduct($idProduct,$sucursal);
            if($data){$currentStock = $data['stock'];}    
            
            if($currentStock != null){ 
                $currentStock += $quantity;                
                return parent::update($data['id'],array('stock'=>$currentStock,'controller'=>$array['controller']), $this->table);   
            }else{                
               return parent::save(array('id_product'=>$idProduct,'id_store'=>$sucursal,'controller'=>$array['controller'],'stock'=>$quantity), $this->table);
            }          
        }        
        return true;
    }
    
    public function subInventory($array){
        $idProduct = $array['id_product'];
        $quantity = $array['quantity'];
        $sucursal = $array['sucursal'];
        
        if($quantity != 0){
            $currentStock = null;
            $data = $this->getInventorySucursalByIdProduct($idProduct,$sucursal);            
            if($data){$currentStock = $data['stock'];}         
            
            if($currentStock != null){
                $currentStock -= $quantity;
                return parent::update($data['id'],array('stock'=>$currentStock,'controller'=>$array['controller']), $this->table);  
            }else{
               $quantity *= -1;
               return parent::save(array('id_product'=>$idProduct,'id_store'=>$sucursal,'stock'=>$quantity,'controller'=>$array['controller']), $this->table);
            }                
        }        
        return true;
    }
    
    public function updateAddInventory($array){
        $idProduct = $array['id_product'];
        $currentQuantity = $array['current_quantity'];
        $newQuantity = $array['new_quantity'];
        $currentSucursal = $array['current_sucursal'];
        $newSucursal = $array['new_sucursal'];
       
        if($currentSucursal != $newSucursal){
            $this->subInventory(array('id_product'=>$idProduct,'quantity'=>$currentQuantity,'sucursal'=>$currentSucursal,'controller'=>$array['controller']));
            return $this->addInventory(array('id_product'=>$idProduct,'quantity'=>$newQuantity,'sucursal'=>$newSucursal,'controller'=>$array['controller']));
        }else{
            $diff = $newQuantity - $currentQuantity;
            
           
            if($diff > 0){ 
                return $this->addInventory(array('id_product'=>$idProduct,'quantity'=>$diff,'sucursal'=>$newSucursal,'controller'=>$array['controller']));
            }elseif($diff < 0){
                return $this->subInventory(array('id_product'=>$idProduct,'quantity'=>abs($diff),'sucursal'=>$newSucursal,'controller'=>$array['controller']));
            }        
        }
       
        return true;
    }
    
    public function deleteAddInventory($products){
        if(is_array($products)){
            foreach($products as $product){
                $rs = $this->subInventory(array('id_product'=>$product['id_product'],'quantity'=>$product['quantity'],'sucursal'=>$product['sucursal']));
                if(!$rs){
                    return null;
                }
            }
        }
        return true;
    }
    
    public function updateSubInventory($data){        
        $currentQuantity = $data['current_quantity'];
        $newQuantity = $data['new_quantity'];
       
        $diff = $newQuantity - $currentQuantity;
        
        if($diff > 0){  
            $data['quantity'] = $diff;
            return $this->subInventory($data); 
        }elseif($diff < 0){
            $data['quantity'] = abs($diff); 
            return $this->addInventory($data);
        }
        
        return true;
    }
    
    public function deleteSubInventory($products){       
        if(is_array($products)){
            foreach($products as $product){
                $rs = $this->addInventory(array('id_product'=>$product['id_product'],'quantity'=>$product['quantity'],'sucursal'=>$product['sucursal']));
                if(!$rs){
                    return null;
                }
            }
        }
        return true;
    }  
    
    /*Lo ocupo para editar inventario manual desde Reportes*/
    public function updateInventory($array){
        $login = new Login();
        $idProduct = $array['id_product'];
        $quantity = $array['quantity'];
        $sucursal = $array['sucursal'];
        $notes = '';
        if(isset($array['notes'])){$notes = $array['notes'];}        

        $data = $this->getInventorySucursalByIdProduct($idProduct,$sucursal);
        $currentStock = $data['stock'];

        if($currentStock != null){            
            return parent::update($data['id'],array('stock'=>$quantity,'notes'=>$notes,'controller'=>'Manual - Usuario '.$login->getNombreCompleto()), $this->table);
        }else{                
           return parent::save(array('id_product'=>$idProduct,'id_store'=>$sucursal,'stock'=>$quantity,'notes'=>$notes,'controller'=>'Manual - Usuario '.$login->getNombreCompleto()), $this->table);
        }          
    
        return true;
    }
    
    /*Lo uso en Production cuando se edita registro y se cambia el producto */
    public function changeProduct($options){
        $this->startTransaction();
        $sub = $this->subInventory(array(
                    'id_product'=>$options['origin_id_product'],
                    'quantity'=>$options['origin_quantity'],
                    'sucursal'=>$options['origin_sucursal'],
                    'controller'=>$options['controller']
                ));
        
        if($sub){
            $add = $this->addInventory(array(
                    'id_product'=>$options['id_product'],
                    'quantity'=>$options['quantity'],
                    'sucursal'=>$options['sucursal'],
                    'controller'=>$options['controller']
                ));
            
            if($add){
                $this->commit();
                return true;
            }
        }
        $this->rollback();       
        return null;
    }
}
