<?php

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

class SucursalRepository extends EntityRepository {

    private $table = 'sucursales';   
    private $images = null;
    private $options_image = array(
        'allowedExtensions'=>array('image/jpg','image/jpeg','image/png','image/gif'),
        'maxFileSizeAllowed'=>16384
    );
    
    public $flashmessenger = null;
    
    private $options = array(
        'nombre'=>null,       
        'direccion'=>null,
        'ciudad'=>null,
        'estado'=>null,
        'pais'=>'USA',
        'codigopostal'=>null,
        'nombre_contacto'=>null,
        'telefono'=>null,
        'fax'=>null,
        'email'=>null,
        'paginaweb'=>null,
        'status'=>null,
    );
    
    private $options_aux = array(
        'logo'=>null,
        'image_type'=>null,
        'token_form'=>null
    );
    
    public function setOptions($data){  
      foreach ($this->options as $option => $value){
          if(isset($data[$option])){
            $this->options[$option] = $data[$option];
          }
      }
      
      foreach ($this->options_aux as $option => $value){
          if(isset($data[$option])){
            $this->options_aux[$option] = $data[$option];
          }
      }
    }
  
    public function getOptions(){
        return $this->options;
    }
    
    public function getNombre(){
        return $this->options['nombre'];
    }
    
    public function getLogo(){
        return $this->options_aux['logo'];
    }
    
    public function getImageType(){
        return $this->options_aux['image_type'];
    }
    
    public function getDireccion(){
        return $this->options['direccion'];
    }
    
    public function getCiudad(){
        return $this->options['ciudad'];
    }
    
    public function getEstado(){
        return $this->options['estado'];
    }
    
    public function getCodigoPostal(){
        return $this->options['codigopostal'];
    }
    
    public function getTelefono(){
        return $this->options['telefono'];
    }
    
    public function getTable(){
        return $this->table;
    }
    
    public function getTokenForm(){
        return $this->options_aux['token_form'];
    }
    
    public function __construct() {
        if(!$this->flashmessenger instanceof FlashMessenger){
            $this->flashmessenger = new FlashMessenger();
        }
    }
  
    public function _getTranslation($text){
        return $this->flashmessenger->_getTranslation($text);
    }

    public function save(array $data, $table = null) {
        $data['nombre'] = trim(($data['nombre']));
        $data['direccion'] = trim(($data['direccion']));
        $data['status'] = '1';
        
        $this->startTransaction();        
        parent::save($data, $this->table);        
        
        $storeInDetailsTemp = new StoreDetailsTempRepository();
        $idCompra = $this->getInsertId();
        $this->setLastInsertId($idCompra);//Para utilizarlo en el Controller action insert
        
        if($storeInDetailsTemp->saveDetalles($idCompra, $this->getTokenForm())){   
            $this->commit();
            $storeInDetailsTemp->truncate($this->getTokenForm());

            return true;
        }
        
        $this->rollback();   
        $this->flashmessenger->addMessage(array(
            'error'=>$this->_getTranslation('Error. Intenta nuevamente o contacta a tu proveedor de sistemas.')));
        return null;        
    }
    
    public function update($id, $data, $table = null) {
        $data['nombre'] = trim(($data['nombre']));
        $data['direccion'] = trim(($data['direccion']));

        $this->startTransaction();      
        $result = parent::update($id, $data, $this->table);
        
        if($result){
            $repository = new StoreDetailsTempRepository();
            if($repository->updateDetalles($id, $this->getTokenForm())){                                
                $this->commit();
                $repository->truncate($this->getTokenForm());  
                return true;
            }
        }
        
        $this->rollback();
        return null;
    }    
        
    public function delete($id, $table = null) {        
        return parent::delete($id, $this->table);
    }

    public function getById($id, $table = null,$selectAux = null) {
        return parent::getById($id, $this->table);
    }
    
    public function getByToken($token){
        $query = "SELECT * FROM $this->table WHERE token = '$token'";
        $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 null;
        return parent::isUsedInRecord($id, array('alumos' => 'idGrupo'));
    }

    public function getListSelectSucursales($stringIdSucursales = null) {
        if($stringIdSucursales != null && trim($stringIdSucursales != '')){
            $stringIdSucursales = " AND find_in_set(id,'$stringIdSucursales')";
        }    
        
        $select = "SELECT * FROM $this->table WHERE 1 = 1 $stringIdSucursales";
        $result = $this->query($select);

        if ($result) {
            $array = array();
            while ($row = $result->fetch_assoc()) {
                $array[$row['id']] = $row['nombre'];
            }
            return $array;
        }
        return null;
    }
    
     public function getListSucursales() {
        $select = "SELECT *,"
                . "fxGetStatusName(status,'status','Sucursal')as status "
                . "FROM $this->table "
                . "WHERE 1 = 1 ";
        $result = $this->query($select);

        if ($result) {
           return $this->resultToArray($result);
        }
        return null;
    }
    
    public function getListEstados(){
        $query = "SELECT * FROM estados ORDER BY id ASC";
        $result = $this->query($query);
        
        if($result){
            $array = array();
            while($row = $result->fetch_object()){
                $array[$row->id] = $row->nombre;
            }
            
            return $array;
        }
        
        return null;
    }
    
    public function setImage($images){
        $this->images = $images;
    }
    
    public function saveImage($idSucursal){ 
        if($this->images['name'] != ''){
            if (in_array($this->images['type'], $this->options_image['allowedExtensions']) && $this->images['size'] <= $this->options_image['maxFileSizeAllowed'] * 1024){
                $imagen_temporal = $this->images['tmp_name'];

                // Tipo de archivo
                $tipo = $this->images['type']; 
                $size = $this->images['size'];

                // Leemos contenido y escapamos caracteres especiales
                $data = file_get_contents($imagen_temporal);
                //$data = addslashes($data);

                $array = array(
                    'logo'=>$data,
                    'logo_type'=>$tipo,
                    'logo_size'=>$size
                );
                
                parent::update($idSucursal, $array, $this->table);                

            }else{
                $this->flashmessenger->addMessage(array(
                'danger'=>$this->_getTranslation("Formato de archivo no permitido o excede el tamaño límite de {$this->options_image['maxFileSizeAllowed']} Kbytes.")));
                return null;
            }
        }
        return true;
    }
    
    public function crearTablaDetallesForUser(){
        $login = new Login();
        
        $query = "CREATE TABLE IF NOT EXISTS store_details_".$login->getId()." 
                 (  
                    `token_form` char(50) NOT NULL,
                    `id` int(11) NOT NULL AUTO_INCREMENT,
                    `id_detail` int(11) NULL,
                    `id_store` int(11) NULL,
                    `id_product` int(11) NOT NULL,
                    `days` text NOT NULL,
                    `min` double NOT NULL,
                    `max` double NOT NULL,
                    PRIMARY KEY (`id`)
                 )ENGINE=InnoDB DEFAULT CHARSET=utf8;";
        
       $result = $this->query($query);
       
       /*
        * Fernando: marcaba error
       $sucursalRepoTemp = new StoreDetailsTempRepository();
       $sucursalRepoTemp->truncate($this->getTokenForm());
       */
    }
    
    public function insertDetalle($data){
        $storeInDetailsTemp = new StoreDetailsTempRepository();
        
        return $storeInDetailsTemp->save($data);
    }
    
    public function getStoreDetails($token_form){
        $login = new Login();
        $query = "SELECT v.*,
                    v.id as idDetailTemp,
                    p.id as product,
                    p.codigo as code,
                    p.descripcion as description,
                    fxGetTamanoDescripcion(p.tamano)as size
                    FROM store_details_".$login->getId()." v LEFT JOIN productos p ON v.id_product = p.id
                    WHERE token_form = '$token_form' ORDER BY v.id";
        $result = $this->query($query);
        
        if($result){
            $result = $this->resultToArray($result);
            return $result;
        }
        
        return null;
    }
    
    public function getStoreDetailsSaved($id){
        $query = "SELECT c.*,
                    p.code as code,
                    p.description as description,
                    fxGetSizeDescription(p.size)as size
                    FROM store_details c LEFT JOIN products p ON c.id_product = p.id
                    WHERE c.id_store = '$id'";
        $result = $this->query($query);
        
        if($result){
            $result = $this->resultToArray($result);
            return $result;
        }
        
        return null;
    }
    
    public function setStoreDetailsById($idCompra, $tokenForm){
        $repository = new StoreDetailsTempRepository();
        
        return $repository->setStoreDetailsById($idCompra, $tokenForm);
    }
    
    public function truncateIfIsEditInfo(){
        $repository = new StoreDetailsTempRepository();
        $repository->truncateIfIsEditInfo();
        
    }
    
    public function getProductById($idProducto){
        $query = "SELECT * FROM productos 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 getListDays(){
      return array(
          '1'=>'Lun',
          '2'=>'Mar',
          '3'=>'Mie',
          '4'=>'Jue',
          '5'=>'Vie',
          '6'=>'Sab',
          '7'=>'Dom',
      );
  }
  
  public function daysArrayTostring($days){
      $stringDays = '';
      foreach($days as $day){
          $stringDays .= $day.",";
      }
      
      return trim($stringDays,',');
  }
  
    public function getMinimumStockForStoreByDay($days){        
        if(is_array($days) && count($days) > 0){
            $array = array();
            foreach($days as $day){
                $query = "SELECT id_store,id_product,min FROM store_details WHERE FIND_IN_SET($day,days)";
                $result = $this->query($query);
                
                if($result->num_rows > 0){
                    $result = $this->resultToArray($result);
                    foreach($result as $row){
                        if(isset( $array[$row['id_store']][$row['id_product']])){
                             $array[$row['id_store']][$row['id_product']] += $row['min'];
                        }else{
                             $array[$row['id_store']][$row['id_product']] = $row['min'];
                        }
                       
                    }
                }
            }
            return $array;
            
        }else{
            $query = "SELECT id_store,id_product,min FROM store_details WHERE FIND_IN_SET($days,days)";
            $result = $this->query($query);

            if($result->num_rows > 0){
                $result = $this->resultToArray($result);
                foreach($result as $row){                   
                    $array[$row['id_store']][$row['id_product']] = $row['min'];
                }
                
                return $array;
            }
          
        }     
      return null;
    }
}
