<?php

class ProductoRepository extends EntityRepository {
    
    private $table = 'productos';
    private $images = null;
    private $options_image = array(
        'allowedExtensions'=>array('jpg','jpeg','png'),
        'maxFileSizeAllowed'=>1000000,
        'pathToSave'=>PATH_IMG_PRODUCTS
    );
    
    public $flashmessenger = null;    
         
    public function __construct() {
        if(!$this->flashmessenger instanceof FlashMessenger){
            $this->flashmessenger = new FlashMessenger();
        }
    }
    
    public function _getTranslation($text){
        return $this->flashmessenger->_getTranslation($text);
    }
    
    public function setImage($file){
        $this->images['main'] = $file;
    }
    
    public function saveImage($idProduct){
        $file = new UploadFile();
        $file->setAllowedExtensions($this->options_image['allowedExtensions']);
        $file->setMaxFileSizeAllowed($this->options_image['maxFileSizeAllowed']);
        $file->setTempFolder($this->options_image['pathToSave']);

        $rsUpload = $file->uploadFile($this->images['main'],null,'main_'.$idProduct);
        if(!$rsUpload){
            $this->flashmessenger->addMessage(array('info'=>$file->getMessageError()));                    
        }
    }
    public function getUUID()
    {

        $query = "SELECT SUBSTRING(UUID()1,10) as uuid ";
        $result = $this->query($query);

        if ($result->num_rows > 0) {

            return $this->resultToArray($result);

        }
        return null;
    }
    public function save(array $data, $table = null) {
        $login = new Login();
        $data['creado_por'] = $login->getId();
        $data['creado_fecha'] = date('Y-m-d H:i:s');
        unset($data['modificaciones']);
        $data['p_uuid'] = implode($this->getUUID()[0]);
        if(trim($data['descuento'])==''){$data['descuento'] = 0;}
        if(trim($data['punitarioventa'])==''){$data['punitarioventa'] = 0;}
        
        if(is_array($data['proveedores']) && count($data['proveedores']) > 0){
            $sucursal = implode(',', $data['proveedores']);
            $data['proveedores'] = trim($sucursal,',');
        }        
        if($this->images !== null){
            $data['con_imagen'] = 1; //UG La imagen del producto fue agregada
        }
        foreach($data as $key => $value){
            if(trim($value) == '' || trim($value) === null ){
                unset($data[$key]);
            }
        }
        
        $this->startTransaction();
        $result =  parent::save($data, $this->table);             
        
        if($result){
            $idProduct = $this->getInsertId();

            //UG Obtener el uuid insertado 
            $dataProducto = $this->getById($idProduct);

            $this->setLastInsertId($idProduct);//Para utilizarlo en el Controller action insert  
            $this->commit();
            if($this->images !== null){
                $this->saveImage($dataProducto['p_uuid']);//UG ahora se envia el uuid para crear el name de la imagen
            }
            return true;                         
        }

    }

    public function update($id, $data, $table = null) {

        unset($data['creado_fecha'],$data['creado_por'],$data['modificaciones']);
        
        if(trim($data['descuento'])==''){$data['descuento'] = 0;}
        if(trim($data['punitarioventa'])==''){$data['punitarioventa'] = 0;}
        
        if(is_array($data['proveedores']) && count($data['proveedores']) > 0){
            $sucursal = implode(',', $data['proveedores']);
            $data['proveedores'] = trim($sucursal,',');
        }        
        if($this->images !==null){
            $data['con_imagen'] = 1; //UG La imagen del producto fue agregada
        }

        foreach($data as $key => $value){
            if($value == '' || $value === null ){
                $data[$key] = array('key'=>$key,'value'=>'_NULL');                
            }
        }       
      

        if($this->images !==null){
            //UG Obtener el uuid insertado 
            $dataProducto_ = $this->getById($id);
          
            $this->saveImage($dataProducto_['p_uuid']);
        }
        
        return parent::update($id, $data, $this->table);

    }

    public function getById($id, $table = null,$selectAux = null) {
        $selectAux = " fxGetImpuestosTasa(impuestos)as impuestosTasa,"
                   . "fxGetUnidadMedidaDescripcion(unidad_de_medida) as umName,"
                   . " fxGetCategoriaDescripcion(categoria)as categoriaName " ;
        return parent::getById($id, $this->table,$selectAux);
    }
    
    public function getByCode($code) {
        $query = "SELECT * FROM $this->table WHERE codigo = '$code' LIMIT 1";
        $result = $this->query($query);
        
        if($result->num_rows > 0){
            $result = $this->resultToArray($result);
            return $result[0];
        }
        return null;
    }
    
    public function getRealInfoById($id){
        $query = "SELECT id,descripcion,
                            fxGetCategoriaDescripcion(categoria)as categoria,
                            fxGetMarcaDescripcion(marca)as marca,
                            fxGetPresentacionDescripcion(presentacion)as presentacion,
                            punitariocompra,punitarioventa
                   FROM $this->table
                   WHERE id = '$id'";
        
        $result = $this->query($query);
        
        if($result->num_rows > 0){
            $result = $this->resultToArray($result);
            return $result[0];
        }

        return null;
    }
    
    public function delete($id, $table = null) {
        return parent::delete($id, $this->table);
    }
    
    public function exist($idProducto){
        $query = "SELECT descripcion
                    FROM $this->table 
                    WHERE id = '$idProducto'
                    LIMIT 1 ";
        $result = $this->query($query);
        
        if($result->num_rows > 0){
            $result =  $this->resultToArray($result);
            return $result[0];
        }
        return null;
    }
    
    public function existeCodigo($codigo,$idProducto = null){
        $codigo = strtolower(trim($codigo));
        if($codigo == ''){return null;}
        else{$codigo = " codigo = '$codigo' ";}
        if($idProducto != null && trim($idProducto)!=''){$idProducto = " AND id != '$idProducto' ";}
        
        $query = "SELECT codigo,
                         descripcion,
                         fxGetCategoriaDescripcion(categoria) as categoria,
                         fxGetMarcaDescripcion(marca) as marca
                    FROM $this->table 
                    WHERE $codigo $idProducto
                    LIMIT 1 ";
        $result = $this->query($query);
        
        if($result->num_rows > 0){
            $result =  $this->resultToArray($result);
            return $result[0];
        }
        return null;
    }

    public function isUsedInRecord($id, array $buscarEn = null,$andWhere= null) {
        return parent::isUsedInRecord($id, array('ventasdetalles'=>'idProducto'));   
    }
    
    public function getPreciosVentaById($id){
        $query = "SELECT punitarioventa as `precio_menudeo` FROM productos WHERE id = '$id' LIMIT 1";
        $result = $this->query($query);
        
        if($result){
            $result = $result->fetch_object();
            $array[$result->precio_menudeo] = "Precio menudeo - $".$result->precio_menudeo;
            $array[$result->precio_mayoreo] = "Precio mayoreo - $".$result->precio_mayoreo;
            
            return $array;
        }
        
        return null;        
    }
    
    public function getListaProductos($tipo = null,$status = 1){
        if($tipo != null){            
            $tipo = " AND p.type = '$tipo'";            
        }        
        
        $status = " AND p.status = '$status' ";        
        
        $query = "SELECT p.*,
                    c.descripcion as categoria,
                    m.descripcion as marca,
                    um.descripcion as unidad_de_medida,
                    fxGetStatusName(p.status,'status','Product') as statusName,
                    co.hex_color as color
                    FROM $this->table p 
                    LEFT JOIN  categorias c ON p.categoria = c.id 
                    LEFT JOIN  marcas m ON p.marca = m.id
                    LEFT JOIN  unidades_de_medida um ON p.unidad_de_medida = um.id
                    LEFT JOIN  impuestos i ON p.impuestos = i.id
                    LEFT JOIN  productos_colors co ON p.color = co.id
                    WHERE 1=1
                    $status
                    $tipo ORDER BY p.descripcion";
        
        $result = $this->query($query);
        
        if($result){
            return $this->resultToArray($result);
        }        
        return null;
    }
    
    public function getListSelectProductos(){
        $query = "SELECT *, TRIM(descripcion)as descripcion
                    FROM $this->table 
                    WHERE 1=1 
                    AND status = '1' 
                    ORDER BY descripcion";
        $result = $this->query($query);
        
        if($result){
            $array = array();
            while($row = $result->fetch_object()){
                $array[$row->id] = $row->descripcion;
            }
            
            return $array;
        }
        
        return null;
    }
    
    public function getProductosLike($item){
        $query = "SELECT *,
                    fxGetCategoriaDescripcion(categoria)as categoria,
                    fxGetMarcaDescripcion(marca)as marca
                    FROM $this->table WHERE codigo like '%$item%' OR descripcion like '%$item%' AND status = 1 ORDER BY descripcion";
        $result = $this->query($query);
        
        if($result){
            return $this->resultToArray($result);
        }
        
        return null;
    }
    
     public function getListVentaProductos($tipo = null){
        $query = "SELECT *,
                    fxGetCategoriaDescripcion(categoria)as categoria,
                    fxGetMarcaDescripcion(marca)as marca,
                    fxGetPresentacionDescripcion(presentacion)as presentacion
                    FROM $this->table WHERE 1=1 AND(type = '1' OR type = '2') ORDER BY descripcion";
        $result = $this->query($query);
        
        if($result){
            return $this->resultToArray($result);
        }
    }
    
    public function updatePrecios($data){
        unset($data['enviar']);
        unset($data['id']);
        unset($data['action']);
        foreach ($data as $key => $value) {
            foreach ($value as $id => $campos){
                    $query = "UPDATE productos SET ";
                    foreach ($campos as $key => $valor){
                        $query .= $key." = '$valor',";
                    }
                    $query = trim($query,",");
                    $query .= " WHERE id = $id";
                   $this->query($query);
            }
        }
    }    
    
    public function getLastIdProduct(){
        $query = "SELECT id FROM $this->table ORDER BY id DESC LIMIT 1";
        
        $result =$this->query($query);
        
        if($result->num_rows > 0){
            $result = $result->fetch_object();
            return $result->id;
        }else{
            return 0;
        }
    }
    
    public function getListSelectColors() {
        $select = "SELECT * FROM  productos_colors ";
        $result = $this->query($select);

        if ($result) {
            $array = array();
            while ($row = $result->fetch_assoc()) {
                $array[$row['id']] = $row['hex_color'];
            }
            return $array;
        }
        return null;
    }
    
    public function crearTablaDetallesForUser(){
        $login = new Login();
        $query = "DROP TABLE IF EXISTS products_details_".$login->getId();
        $this->query($query);
        
        $query = "CREATE TABLE IF NOT EXISTS products_details_".$login->getId()." 
                 (  `id` int(11) NOT NULL AUTO_INCREMENT,
                    `id_detail` int(11) NULL,
                    `id_product` int(11) NULL,
                    `id_slice` int(11) NOT NULL,
                    `quantity` double NOT NULL,                   
                    PRIMARY KEY (`id`)
                 )ENGINE=InnoDB DEFAULT CHARSET=utf8;";
        
       $result = $this->query($query);
    }
    
    public function insertDetalle($data){
        $storeInDetailsTemp = new ProductDetailsTempRepository();
        
        return $storeInDetailsTemp->save($data);
    }
    
    public function getProductDetails(){
        $login = new Login();
        $query = "SELECT v.*,
                    v.id as idDetailTemp,
                    p.flavor,
                    p.category,
                    p.size,
                    fxGetCategoriaDescripcion(p.category)as categoryName
                  FROM products_details_".$login->getId()." v LEFT JOIN slices p
                  ON v.id_slice = p.id
                  ORDER BY v.id";
        $result = $this->query($query);
        
        if($result){
            $result = $this->resultToArray($result);
            return $result;
        }
        
        return null;
    }
    
    public function getProductDetailsSaved($id){
        $query = "SELECT c.*,
                    p.code as code
                    FROM product_details c LEFT JOIN slices p ON c.id_slice = p.id
                    WHERE c.id_product = '$id'";
        $result = $this->query($query);
        
        if($result){
            $result = $this->resultToArray($result);
            return $result;
        }
        
        return null;
    }
    
     public function getListaSelectImpuestos() {
        $select = "SELECT * FROM taxes ";
        $result = $this->query($select);

        if ($result) {
            $array = array();
            while ($row = $result->fetch_assoc()) {
                $array[$row['id']] = $row['description']." - ".$row['rate']." %";
            }
            return $array;
        }
        return null;
    }
    
        
    public function getSliceById($id){
        $repoSlice = new SliceRepository();
        return $data = $repoSlice->getById($id);
    }
    
    public function getProductForMenu(){
        $query = "SELECT p.* "
                . "FROM productos p "
                . "WHERE mostrar_en_menu = '1' "
                . "ORDER BY p.nombre_para_menu ASC";
        
        $result = $this->query($query);
        
        if($result->num_rows > 0){
            return $this->resultToArray($result);
        }
    }


    public function truncateIfIsEditInfo(){
        $repository = new ProductDetailsTempRepository();
        $repository->truncateIfIsEditInfo();
        
    }    
    
    public function getListStatus(){
        $query = "SELECT * FROM codigo_status WHERE tipo = 'Product'";
        $result = $this->query($query);
        
        if($result->num_rows > 0){
            $array = array();
            foreach($result as $status){
                $array[$status['codigo']] = $status['descripcion'];
            }
            return $array;
        }
        return null;
    }
    
    public function proveedoresStringToArray($sucursales){
        $arraySucursales = array();
        $sucursales = explode(',', $sucursales);
        foreach($sucursales as $key => $sucursal){
            $arraySucursales[$sucursal] = $sucursal;
        }
        return $arraySucursales;
    }
    
     public function getDataTaxesById($id){
        $query = "SELECT * FROM impuestos WHERE id = '$id'";
        $result = $this->query($query);
        
        if($result->num_rows > 0){
            return $this->resultToArray($result)[0];
        }
        
        return null;
    }
}