<?php
class RewardsReportListasEntity Extends RewardsReportListasRepository{
    
    public $flashmessenger = null;
    private $saveFile = null;
    private $options = array(
        'reporte'=>null,
        'fechaInicio'=>null,
        'fechaFin'=>null,
        'startDate'=>null,
        'endDate'=>null,
        'customer_id'=>null,
        'store_id'=>null,
        'status'=>null,

    );
    private $nombreArchivo = null;
    private $reporte = null;
    private $tempFolder = null;
    private $headerExcelReport = null;
    
    private $reportes = array(
        'sales_by_customer_grouped_by_product'=>'salesByCustomerGroupedByProduct',
     );
    
    private $nombreReportes = array(
        'sales_by_customer_grouped_by_product'=>'Ventas por cliente agrupado por producto'      
    );
    
    private $reportesEspeciales = array(
        'sales_by_customer_grouped_by_product'=>'sales_by_customer_grouped_by_product',       
    );
    
    private $reportesEspecialesPantalla = array(
        'inventario'=>'inventario',   
    );  
    
    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){        //var_dump($data);exit;
      foreach ($this->options as $option => $value){
          if(isset($data[$option])){
            $this->options[$option] = $data[$option];
          }
      }
      
        if(isset($data['store_id'])){
            $sucursalRepo = new SucursalRepository();
            $store_id = $data['store_id'];
            
            if(isset($data['store_id']) && is_array($data['store_id']) && count($data['store_id']) > 0){
                $store_id = implode(',', $data['store_id']);                
            }        

          $this->options['store_name'] = $sucursalRepo->getStoreName($store_id);
      }
      
      $this->createReporte();
    }
    
    public function getOptions(){
        return $this->options;
    }
    
    public function getNombreReporte(){
        return $this->options['reporte'];
    }
    
    public function getTituloReporte(){
        return $this->nombreReportes[$this->options['reporte']];
    }
    
    public function getNombreArchivo(){
        return str_replace(' ', '', $this->nombreArchivo);
    }
    
    public function setNombreArchivo(){
        if(isset($this->nombreReportes[$this->getNombreReporte()])){
            $this->nombreArchivo = $this->nombreReportes[$this->getNombreReporte()];
        }
    }
    
    public function setNombreReporteManual($nombreArchivo){
        $this->nombreArchivo = $nombreArchivo;
    }
    
    public function setHeaderExcelReportManual($headerReport){
        $this->headerExcelReport = $headerReport;
    }
    
    public function createReporte(){
        ini_set('max_execution_time', 18000);
        ini_set('mysql.connect_timeout', 18000);
        ini_set('default_socket_timeout', 18000);
        ini_set('memory_limit', '-1');
       
        $nombreReporte = $this->reportes[$this->getNombreReporte()];
        $this->setNombreArchivo();
        
        $this->setReporte($this->$nombreReporte());  
        
        $array = array();
        foreach($this->getOptions() as $option => $value){
            if(is_array($value)){$array[$option] = implode(',', $value);}
            else{$array[$option] = $value;}
        }
        
        $_SESSION['optionsCurrentReport'] = array(
            'options'=>$array
        );
    }
    
    public function getStringToSendGET(){
        $options = $this->getOptionsCurrentReport();
        $string = "?";
        foreach($options['options'] as $key => $value){
            $string .= $key."=".$value."&";
        }
        
        $string = trim($string,"&");
        return $string;
    }
    
    public function getOptionsCurrentReport(){
        return $_SESSION['optionsCurrentReport'];
    }
    
     public function setReporte($data){ 
        if($data == null){ 
            $this->flashmessenger->addMessage(array('info'=>'No se encontraron resultados.'));
            header('location: '.ROOT_HOST.'/Controller/Reports.php');
            exit;
        }   
            
        $this->reporte = $data; 
    }
    
    public function getReporte(){
       return $this->reporte;
    }
    
    public function salesByCustomerGroupedByProduct(){
        return parent::getSalesByCustomerGroupedByProduct($this->getOptions());
    }
    
    public function getReporteOnFile($formato = null){    
        $empresa = new EmpresaEntity();
        $empresa = $empresa->getById(1);
        //echo "Asdf";exit;
        $startDate = $this->options['fechaInicio'];
        $endDate = $this->options['fechaFin'];
        if(trim($startDate)=='' && trim($endDate)==''){
            $startDate = $this->_getTranslation("Desde el inicio de los tiempos");
            $endDate = strftime('%B %d, %Y',strtotime('now'));
        }elseif(trim($startDate)=='' && trim($endDate)!=''){
            $startDate = $endDate;
        }elseif(trim($startDate)!='' && trim($endDate)==''){
            $endDate = $startDate;
        }
        $this->setHeaderExcelReportManual($empresa['nombre']."\n".$this->_getTranslation($this->getTituloReporte())."\n".$startDate." - ".$endDate);
      
        if($formato == 'excel'){            
            if(isset($this->reportesEspeciales[$this->options['reporte']])){                
             $this->reporteEspecial();
            }else{
                $this->reporteDefault();
            }
        }elseif($formato == 'pdf'){
           if(isset($this->reportesEspecialesPDF[$this->options['reporte']])){ 
             $this->reporteEspecialPDF();
            }else{
                $this->reporteToPDF();
            }
        }            
    }
    
    public function reporteEspecial(){
        $data = $this->reporte;
        include ROOT.'/Rewards/View/Reports/Excel/'.$this->options['reporte'].".php";
    }
    
    public function reporteEspecialPDF(){
        $data = $this->reporte;
        include ROOT.'/Rewards/View/Reports/PDF/'.$this->options['reporte'].".php";
    }
    
    public function getTemplateReporteOnScreen(){
        if(isset($this->reportesEspecialesPantalla[$this->options['reporte']])){
            $login = new Login();
            $filename = ROOT."/Rewards/View/Reports/Pantalla/role_{$login->getRole()}/{$this->options['reporte']}.php";
          
            if (file_exists($filename)) {
                 return ROOT."/Rewards/View/Reports/Pantalla/role_{$login->getRole()}/".$this->options['reporte'].".php";
            }
        
            return ROOT.'/Rewards/View/Reports/Pantalla/'.$this->options['reporte'].".php";
        }else{
            return ROOT.'/Rewards/View/Reports/Pantalla/default.php';
        }
    }
    
    public function getTemplateReporteOnMobile(){
        if(isset($this->reportesEspecialesMobile[$this->options['reporte']])){
            return ROOT.'/Rewards/View/Reports/Mobile/'.$this->options['reporte'].".php";
        }else{
            return ROOT.'/Rewards/View/Reports/Mobile/default.php';
        }
    }
    
    public function reporteDefault(){
        $arrayData = $this->reporte;
        $colTitulosTemp = $arrayData[0];
       
        foreach($colTitulosTemp as $titulo => $value){
            $colTitulos[] = $titulo;
        }
        
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getActiveSheet()->freezePane('A3');
        $col = count($colTitulos);
        $lastCol = $this->getColLetter($col-1);

        $objPHPExcel->getActiveSheet()->mergeCells("A1:".$lastCol."1");            
        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(50);
        $objPHPExcel->getActiveSheet()->getStyle("A1")->getFont()->setBold(true);
        $objPHPExcel->getActiveSheet()->setCellValue("A1", $this->headerExcelReport);
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setWrapText(true);
        $objPHPExcel->getActiveSheet()->getStyle("A1")->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle("A1")->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);

        $objPHPExcel->getActiveSheet()->getStyle("A2:".$lastCol."2")->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->fromArray($colTitulos,NULL,'A2');   
           
        $row=3;
        foreach ($arrayData as $key => $data) {
            $i=0;
            foreach ($data as $col => $value) {
                $col = $this->getColLetter($i);
                $objPHPExcel->getActiveSheet()->setCellValue($col . $row, $value);
                $i++;
            }
            $row++;
        }
       
        foreach(range('A',$lastCol) as $columnID) {
            $objPHPExcel->getActiveSheet()->getColumnDimension($columnID)
                ->setAutoSize(true);
        } 
        $objPHPExcel->setActiveSheetIndex(0);
        // Redirect output to a client�s web browser (Excel2007)
        ob_end_clean();
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header("Content-Disposition: attachment;filename=".$this->getNombreArchivo().".xlsx");
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        unset($objWriter);
        exit;
    }
    
    public function saveFile(){
        $this->setTempFolder();
        $this->saveFile = true;
    }
    
    private function getColLetter($i){
        $colName = array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","AA","AB","AC","AD","AE","AF","AG","AH","AI");
        
        return $colName[$i];
    }
    
    private function setTempFolder(){
        $login = new Login();
        $this->tempFolder = PATH_TEMP_DOCS.$login->getId();
        if(!is_dir($this->tempFolder)){
            mkdir($this->tempFolder,0777,true);
        }
    }
    
    private function getTempFolder(){
        return $this->tempFolder;
    }
    
    public function getFileSaved(){
        return $this->getTempFolder()."/".$this->getNombreArchivo().'.xlsx';
    }
}