<?php
//include_once(_DIR_TO_CLASS.'/c_XLS.php') ;
class c_page_XLS //extends c_page_XLS_basic
{ public $rec_member  ;
  public $client ;
  public $fields ;
  public $file_name ;
  public $pExcel ;
  public $aSheet ;
  public $style ;
  public $title ;

  public $first_col_char=65 ; // A
  public $first_row=1 ; // A

  public $cur_col=65 ; // A
  public $cur_row=1 ; // A

  function c_page_XLS()
  {

  }

  function body()
  { // подготовить страницу
    $this->prepare_Sheet() ;
    // заполняем содержимое
    ob_start() ;
    $cmd=$_GET['cmd'] ;
    if ($_GET['cmd']) $this->$cmd($_GET) ;
    $text=ob_get_clean()  ;
    // отдаеи в браузер
    $this->put() ;
    // регистрируем в журнале
    ESMO()->reg_log('XLS export',$cmd.$text,array('member_id'=>MEMBER()->id,'data'=>$_GET)) ;
  }


  function report_to($options)
     {  $this->file_name='report_TO_'.date('d_m_Y',$_GET['time_from']).'_'.date('d_m_Y',$_GET['time_to']).'.xls' ;
        $this->title='Журнал ТО' ;

        global $member ;
        $options['order']='t1.c_data asc' ;
        $options['time_from']=($_GET['time_from'])? $_GET['time_from']:$member->info['smena_in']  ;
        $options['time_to']=($_GET['time_to'])? $_GET['time_to']:time() ;
        $options['member_id']=$_GET['tech'] ;
        if ($_GET['term_ids']) $options['terminal_id']=$_GET['term_ids'] ;
        if ($_GET['org_id']) $options['park_id']=ESMO()->tree[$_GET['org_id']]->get_list_child() ;
         //damp_array($options) ;
        include_once(_DIR_EXT.'/aspmo_rmt/i_mrt.php') ;
        $recs=CAR_TO()->get_TO_recs($options) ; //  print_r($recs) ;

        $arr_cards_ids=array() ; $recs_members=array() ;
        if (_sizeof($recs)) foreach($recs as $rec)
                { $arr_cards_ids[]=$rec['car_id'] ;
                  $arr_personal_ids[]=$rec['personal_id'] ;
                  $arr_member_ids[$rec['member_id']]=1 ;
                  $arr_mo_ids[]=$rec['mo_id'] ;
                }
        $recs_cars=array() ;  $recs_members=array() ;
        if (_sizeof($arr_cards_ids)) $recs_cars=execSQL_row('select pkey,model from obj_site_personals_cars where pkey in ('.implode(',',$arr_cards_ids).')') ;
        if (_sizeof($arr_member_ids)) $recs_members=execSQL_row('select pkey,obj_name from obj_site_account where pkey in ('.implode(',',array_keys($arr_member_ids)).')') ;
        //damp_array($options) ;


        $this->fields=array(  'doc_name'=>array('title'=>'Номер ПЛ','width'=>14,'align'=>'left'),
                              'srok'=>array('title'=>'Срок действия путевого листа','width'=>20,'align'=>'center'),
                              'data1'=>array('title'=>'Дата и время прохождения осмотра','width'=>20,'align'=>'center'),
                              'marka'=>array('title'=>'Марка транспортного средства','width'=>20,'align'=>'left'),
                              'gosmoner'=>array('title'=>'Государственный номер транспортного средства','width'=>10,'align'=>'center'),
                              'fio_driving'=>array('title'=>'Ф.И.О. водителя','width'=>50,'align'=>'left'),
                              'du_driving'=>array('title'=>'№ в/у водителя','width'=>15,'align'=>'left'),
                              'probeg'=>array('title'=>'Показания одометра при выезде','width'=>15,'align'=>'center'),
                              'fuel'=>array('title'=>'Остаток топлива при выезде','width'=>10,'align'=>'center'),
                              'tech_status'=>array('title'=>'Техническое состояние автомобиля при выезде','width'=>10,'align'=>'center'),
                              'fio_meh'=>array('title'=>'Ф.И.О. механика','width'=>30,'align'=>'left'),
                              'org'=>array('title'=>'Организация','width'=>40,'align'=>'left'),
                              'sign'=>array('title'=>'Подпись водителя','width'=>20,'align'=>'center'),
                            ) ;

       // шапка таблицы
       $this->print_table_header() ;
       // данные таблицы
       if (_sizeof($recs)) foreach($recs as $rec)
         { $cur_col_char=$this->first_col_char ;

           $mo_rec=ESMO()->get_mo_by_id($rec['mo_id']) ;

           if (_sizeof($this->fields)) foreach($this->fields as $fname=>$options)
           {  $value='' ;
              $col_char=iconv('windows-1251','UTF-8',chr($cur_col_char)) ;
              switch($fname)
              { case 'doc_name':    $value=str_replace(array('PL','.pdf','_'),' ',$rec['doc_name']) ;  break ;
                case 'srok':        $value=date('d.m.Y',$rec['e_data']).' - '.date('H:i',$rec['e_data']) ; break ;
                case 'data1':       $value=date('d.m.Y',$rec['c_data']).' - '.date('H:i',$rec['c_data']); break ;
                case 'marka':       $value=$recs_cars[$rec['car_id']] ; break ;
                case 'gosmoner':    $value=$rec['car_number'] ; break ;
                case 'fio_driving': $value=$rec['obj_name'] ; break ;
                case 'du_driving':  $value=$rec['driving'] ; break ;
                case 'probeg':      $value=$rec['probeg'] ; break ;
                case 'fuel':        $value=$rec['fuel'] ; break ;
                case 'tech_status': $err=array() ;
                                     if (!$rec['i1']) $err[]='неисправны внешние световые приборы' ;
                                     if (!$rec['i2']) $err[]='неисправны тормозные системы' ;
                                     if (!$rec['i3']) $err[]='неисправен фонарь Такси' ;
                                     if (!$rec['i4']) $err[]='автомобиль грязный' ;
                                     if (!$rec['i5']) $err[]='царапины и повреждения на кузове' ;
                                     if (!$rec['i6']) $err[]='салон грязный' ;
                                     if (!$rec['i7']) $err[]='повреждения в салоне' ;
                                     if (!$rec['i8']) $err[]='посторонние запахи в салоне' ;
                                     if (!$rec['i9']) $err[]='неполный комплект документов на машину' ;
                                     if (!$rec['i10']) $err[]='нет знака аварийной остановки' ;
                                     if (!$rec['i11']) $err[]='неисправно запасное колесо' ;
                                     if (!$rec['i12']) $err[]='нет огнетушителя' ;
                                     if (!$rec['i13']) $err[]='отсутствует домкрат, баллонный ключ, буксировочный крюк' ;
                                     if (!$rec['i14']) $err[]='нет мобильного телефона' ;
                                     if (!$rec['i15']) $err[]='нет фото вид слева' ;
                                     if (!$rec['i16']) $err[]='нет фото вид справа' ;
                                     if (!$rec['i17']) $err[]='нет фото вид спереди' ;
                                     if (!$rec['i18']) $err[]='нет фото вид сзади' ;
                                     if (!$rec['i19']) $err[]='нет фото салона' ;
                                     if (_sizeof($err)) $text_err=implode('<br>',$err) ;
                                     else              $text_err='уд.' ;
                                     $value=$text_err ;
                                     break ;
                case 'fio_meh':      $value=$recs_members[$rec['member_id']] ; break ;
                case 'org':          $value=$mo_rec['_org_name'] ; break ;
                case 'sign':         if ($mo_rec['_member_img_DTW_gen'])
                                     { //$img_dir = _DIR_TO_ROOT.'/public/mo_photo/'.$mo_rec['pkey'].'_DTW_150.png' ;
	                                   $img_dir=ESMO()->get_mo_img_dir_by_id($mo_rec['pkey'],'dir','DTW_150.png',array('no_default_img'=>1)) ;
                                       if (!file_exists($img_dir)) $cont=file_get_contents('/services/esmo_signature/graf_signature/?mo_id='.$mo_rec['pkey'].'&width=150') ;
                                       if (file_exists($img_dir))
                                       { $gdImage = imagecreatefrompng($img_dir);
                                         // Add a drawing to the worksheetecho date('H:i:s') . " Add a drawing to the worksheet\n";
                                         $objDrawing = new PHPExcel_Worksheet_MemoryDrawing();
                                         $objDrawing->setName('Sample image');$objDrawing->setDescription('Sample image');
                                         $objDrawing->setImageResource($gdImage);
                                         $objDrawing->setRenderingFunction(PHPExcel_Worksheet_MemoryDrawing::RENDERING_PNG);
                                         $objDrawing->setMimeType(PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT);
                                         $objDrawing->setWidth(150)->setHeight(100);
                                         $objDrawing->setCoordinates($col_char.$this->cur_row);
                                         $objDrawing->setWorksheet($this->aSheet);
                                         //$objDrawing = new PHPExcel_Worksheet_Drawing();
                                         //$objDrawing->setName('sign')->setDescription('sign')->setPath($img_dir) ;

                                         //$value=$img_dir ;
                                       }

                                       /*?><img src="<?echo $mo_rec['_member_img_DTW_gen']?>" width="150"><?*/
                                     }
                                     $value='' ;
                                     break ;

              }


             //$this->aSheet->setCellValueByColumnAndRow($col_char,$this->cur_row,$value);
             if ($value) $this->aSheet->setCellValue($col_char.$this->cur_row,$value);
             if ($options['align']=='center') $this->aSheet->getStyle($col_char.$this->cur_row)->applyFromArray($this->style['center']);
             if ($options['align']=='left')   $this->aSheet->getStyle($col_char.$this->cur_row)->applyFromArray($this->style['left']);
             $this->aSheet->getStyle($col_char.$this->cur_row)->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
             $cur_col_char++ ;
           }

           $this->aSheet->getRowDimension($this->cur_row)->setRowHeight(100);
           $this->cur_row++ ;
         }



     }




   //----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
   //
   //  сттандрантые операции подготовки XLS
   //
   //----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

  //подготовка страницы
  function prepare_Sheet()
  { set_include_path(_DIR_TO_ADDONS.'/PHPExcel/');
    include_once(_DIR_TO_ADDONS.'/PHPExcel/PHPExcel.php');
    include_once(_DIR_TO_ADDONS.'/PHPExcel/PHPExcel/IOFactory.php');

    $this->pExcel = new PHPExcel();
    $this->pExcel->setActiveSheetIndex(0);
    $this->aSheet = $this->pExcel->getActiveSheet();

    //настройки для шрифтов
    $this->style['Font'] = array('font'=>array('name'=>'Arial Cyr','size'=>'12','bold'=>false));
    $this->style['boldFont'] = array('font'=>array('name'=>'Arial Cyr','size'=>'12','bold'=>true));
    $this->style['center'] = array('font'=>array('name'=>'Arial Cyr','size'=>'12'),'alignment'=>array('horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER,'vertical'=>PHPExcel_Style_Alignment::VERTICAL_TOP));
    $this->style['left'] = array('font'=>array('name'=>'Arial Cyr','size'=>'12'),'alignment'=>array('horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_LEFT,'vertical'=>PHPExcel_Style_Alignment::VERTICAL_TOP));
  }

  function print_table_header()
  { // заголовок документа
    $this->aSheet->setTitle($this->title);

    $cur_col_char=$this->first_col_char ;
    if (_sizeof($this->fields)) foreach($this->fields as $fname=>$options)
    { $col_char=iconv('windows-1251','UTF-8',chr($cur_col_char)) ;
      $this->aSheet->getColumnDimension($col_char)->setWidth($options['width']); //
      $this->aSheet->setCellValue($col_char.$this->cur_row,$options['title']);
      $this->aSheet->getStyle($col_char.$this->cur_row)->applyFromArray($this->style['boldFont'])->applyFromArray($this->style['center']);
      $cur_col_char++ ;
    }
    $this->cur_row++ ;
  }

  //отдаем пользователю в браузер
  function put()
  { include("PHPExcel/Writer/Excel5.php");
    $objWriter = new PHPExcel_Writer_Excel5($this->pExcel);
    header('Content-Type: application/vnd.ms-excel;name="'.$this->file_name.'"');
    header('Content-Disposition: attachment;filename="'.$this->file_name.'"');
    header('Cache-Control: max-age=0');
    $objWriter->save('php://output');
  }

}



?>
