<?php
class report_personal_cards extends c_report
{
 var $title='Карточки сотрудников' ;
 var $filter=array() ;
 var $no_view_title=1 ;

 public $button_save_as_DOC=false;
 public $button_view_as_HTML=false ;
 public $button_view_as_PDF=false ;


 var $arr_card_types=array(1=>'Пустые бланки',
                           2=>'Бланки сотрудников (Пропуск)',
                           3=>'Бланки сотрудников (Таб.номер)'
         )    ;

 var $arr_pass_status=array(1=>'Все',
                           2=>'с пропусками',
                           3=>'без пропусков'
         )    ;

 function init($create_options=array())
 {
   //if (!$this->filter['group_id']) $this->filter['group_id']=MEMBER()->cur_group_id ;
 }

 function setting($options=array())
 {
    $arr_groups=ACCOUNTS()->get_arr_groups_to_cur_account() ;
    list($arr_orgs_ids,$arr_otdel_ids,$arr_works_ids)=PERSONAL()->get_org_otdels_works_to_cur_account($this->filter) ;

    ?><div id="panel_filter">
              <form id="sky-form" class="sky-form"><input type="hidden" name="filter_dir" value="<?echo _CUR_REPORT_DIR?>">
                   <fieldset>
                       <div class="row">
                           <? $this->filter_section_select('card_type','Тип бланков:',2,$this->arr_card_types) ;
                              $this->filter_section_select('pass_status','Выборка по пропускам:',2,$this->arr_pass_status) ;
                              $this->filter_section_select('group_id',$GLOBALS['LS_person_group_title'].':',2,$arr_groups) ;
                              $this->filter_section_select_multiple('org_ids','Организация:',2,$arr_orgs_ids) ;
                              $this->filter_section_select_multiple('otdel_ids','Подразделение:',2,$arr_otdel_ids) ;
                           ?>
                       </div>
                       <div class="row">
                            <?
                            $this->filter_section_input_text('number_from','Номера пропусков (для пуст.бланков), от:',3) ;
                            $this->filter_section_input_text('number_to','Номера пропусков (для пуст.бланков), до:',3) ;
                            ?>
                       </div>
                       <div class="row">
                       <?
                                    if (_sizeof($_FILES))
                                           { $recs_files=conver_FILES_to_recs($_FILES['upload_file']) ;
                                             if (_sizeof($recs_files[0]))
                                               { //if ($recs_files[0]['type']=='application/vnd.ms-excel')
                                                 {  $file_name=_TEMP_DIR.safe_file_names($recs_files[0]['name']) ;  $members = array();
                                                    move_uploaded_file($recs_files[0]['tmp_name'],$file_name) ;
                                                    $this->filter['file_name']=basename($file_name) ;
                                                 }
                                                 //else return(array('type'=>'error','code'=>'failed_type','text'=>'Неверный тип файла. Загрузите файл в формате Excel.')) ;
                                               }

                                           }

                                         ?><section  class="col col-2">
                                            <label class="label">Загрузка таб.номеров из файла:</label>
                                            <label class="input">
                                               <?if ($this->filter['file_name'])
                                                   { ?><input type="hidden" name="filter[file_name]" value='<?echo $this->filter['file_name']?>'><?
                                                     echo $this->filter['file_name'] ;
                                                   }
                                               ?>
                                                <button class="button v1" style="margin-left:10px;" cmd="personal/get_panel_upload_file" href="<?echo _CUR_REPORT_DIR?>" no_send_form="1" ><i class="fa fa-ban" aria-hidden="true"></i></button>
                                                <button class="button v2" cmd="personal/get_panel_upload_file">Загрузить</button>&nbsp;&nbsp;&nbsp;

                                            </label>
                                         </section>

                       </div>
                   </fieldset>
                   <?$this->panel_buttons();?>
               </form>
   </div>
   <div class="alert">ВНИМАНИЕ! НЕ печататайте страницу, пока не будут загружены изображения всех QR-кодов</div>
  <?
}


 function create_usl_select_obj($_params,&$options)
    {
       if ($this->filter['file_name'])  $this->upload_personal_from_file() ;
        //damp_array($this->filter,1,-1) ;
       $usl=array() ;
       $usl[]='clss=211' ;
       if ($this->filter['pass_status']==2)   $usl[]='(propusk is null or propusk=0 or propusk="")';
       if ($this->filter['pass_status']==3)   $usl[]='not (propusk is null or propusk=0 or propusk="")';
       //if ($this->filter['card_type']==2)     $usl[]='tab_number>0';
       //if ($this->filter['card_type']==3)     $usl[]='tab_number>0';
       if ($this->filter['group_id'])         $usl[]='group_id in ('.ACCOUNTS()->get_childs_id($this->filter['group_id']).')' ;
       if ($this->filter['name'])             $usl[]='obj_name like "'.$this->filter['name'].'%"' ;
       if ($this->filter['client_id'])        $usl[]='client_id="'.$this->filter['client_id'].'"' ;
       if ($this->filter['org_ids'])          $usl[]='parent2 in ('.implode(',',array_keys($this->filter['org_ids'])).')' ;
       if ($this->filter['otdel_ids'])        $usl[]='parent3 in ('.implode(',',array_keys($this->filter['otdel_ids'])).')' ;
       if ($this->filter['org_id'])           $usl[]='_org_id="'.$this->filter['org_id'].'"' ;
       if ($this->filter['otdel_id'])         $usl[]='_otdel_id in ('.$this->filter['otdel_id'].')' ;
       if ($this->filter['uid'])              $usl[]='uid='.$this->filter['uid'] ;
       if ($this->filter['ids'])              $usl[]='pkey in ('.implode(',',array_keys($this->filter['ids'])).')' ;
       if ($this->filter['person_ids'])              $usl[]='pkey in ('.implode(',',$this->filter['person_ids']).')' ;
       if ($this->filter['propusk'])          $usl[]='propusk="'.$this->filter['propusk'].'"' ;
       if ($this->filter['working'])          $usl[]='working="'.$this->filter['working'].'"' ;
       if (!$this->filter['status'])          $usl[]='enabled=1' ;
       else if ($this->filter['status']==1)   $usl[]='enabled=0' ;
       if ($this->filter['ext']==1)          $usl[]='ext=1' ; else $usl[]='(ext=0 or ext is null)' ;
       //if ($this->filter['fired'])           $_usl[]='enabled=0'; else  $_usl[]='enabled=1';


       $usl_res=implode(' and ',$usl) ;
       //damp_array($usl,1,-1) ;
       return($usl_res) ;
    }

 function panel_info_filter()
   { $_str=array() ; $info=array() ; $title='' ;
     if ($this->filter['group_id'])                        $info['Группа']=ACCOUNTS()->get_member_name_by_id($this->filter['group_id'])  ;
     if ($this->filter['org_ids'])                         $info['Организации']=PERSONAL()->get_org_names_by_ids(array_keys($this->filter['org_ids']))  ;
     if ($this->filter['otdel_ids'])                       $info['Подразделения']=PERSONAL()->get_org_names_by_ids(array_keys($this->filter['otdel_ids']))  ;
     if ($this->filter['number_from'])                     $info['Номера пропусков, от']=$this->filter['number_from'] ;
     if ($this->filter['number_to'])                       $info['Номера пропусков, до']=$this->filter['number_to'] ;
     if ($this->filter['pass_status'])                     $info['Персонал']=$this->arr_pass_status[$this->filter['pass_status']] ;

     if (_sizeof($info)) foreach($info as $title=>$value) $_str[]=$title.': <strong>'.$value.'</strong>' ;
     if (_sizeof($_str)) $title='<p class=center>'.implode(' ',$_str).'</p>' ;
     return $title ;
   }


 function get_cnt_items($usl,$options=array())
    {   //$options['debug']=2 ;
        $cnt=execSQL_value('select count(pkey)
                          from  '.PERSONAL()->view_personal.'
                          where '.$usl,$options) ;
      return($cnt) ;
    }

 function get_items($usl,$options=array())
 { $limit=($options['limit'])? ' '.$options['limit']:'' ;
   $order=($this->filter['order'])? ' order by '.$this->filter['order']:' order by obj_name' ;
   $list_recs=array() ;
  // $options['debug']=2 ;
   if ($this->filter['card_type']>=2)
   { $list_recs=execSQL('select * from  '.PERSONAL()->view_personal.' where '.$usl.$order.$limit,$options) ;
     if (_sizeof($list_recs)) foreach($list_recs as $id=>$rec) PERSONAL()->prepare_public_info_to_personal($list_recs[$id],$options) ;
   }
    else
    { $from=$this->filter['number_from']? $this->filter['number_from']:1 ;
      $to=$this->filter['number_to']? $this->filter['number_to']:10 ;
      for ($i=$from;$i<=$to;$i++)  $list_recs[]=array('propusk'=>$i) ;
    }
   return($list_recs) ;
 }


// function HTML_report_body($options=array())
function print_template_HTML($list_recs,$options=array())
{   ?><div id="report_personal_cards">
        <div id="list_items"><?
          $k=0 ;
          if (_sizeof($list_recs)) foreach($list_recs as $rec)
             { $k++ ;
               if ($rec['pkey']) $this->panel_card($rec) ;
               else              $this->panel_card_space($rec) ;
               if ($k==9) {?> <div style="page-break-after:always; clear:both"></div><? $k=0 ;}
             }
         ?></div><div class="clear"></div>
         <style type="text/css">
         /*@media print {  .more {  page-break-after: always;  }  }*/
            div#list_items{font-family:Arial, Helvetica, sans-serif;font-size:12px;}
            div#list_items div.clear{clear:both;page-break-after: always;}
            div#list_items div.item{width:300px;height:180px;float:left;margin:5px 10px;border:1px solid gray;position:relative;overflow:hidden;page-break-inside:avoid;}
            div#list_items div.item h2{margin:10px 0 0 80px;padding:0;text-align:left;font-family:arial, helvetica, sans-serif;font-size:13px;text-transform:uppercase;}
            div#list_items div.item img.logo{position:absolute;top:10px;left:25px;}
            div#list_items div.item img.qrcode{position:absolute;top:25px;left:1px;}
            div#list_items div.item table{position:absolute;top:25px;right:29px;width:130px;table-layout:fixed;border-collapse:collapse;font-family:arial, helvetica, sans-serif;font-size:10px;}
            div#list_items div.item table tr td{text-align:left;vertical-align:top;padding:1px;border-bottom:1px solid gray;height:20px;}
            div#list_items div.item.personal{line-height:1.2em;}
            div#list_items div.item.personal table tr td{border-bottom:none;padding-bottom:5px;}
         </style>
       </div>
    <?
    $debug_db=0 ;
}

  function panel_card($rec)
  {  switch($this->filter['card_type'])
      { case 2: $number=$rec['propusk'] ; break ;
        case 3: $number=$rec['tab_number'] ; break ;

      }
     ?><div class="item personal">
       <h2>№ <?echo $number?></h2>
       <img class="logo" src="<?echo _PATH_TO_SITE?>/images/logo.png" width="50">
       <img class=qrcode src="<?echo _PATH_TO_SITE?>/services/qrcode/<?echo $number?>/" />
       <table>
           <tr><td><strong><?echo $rec['obj_name']?></strong></td></tr>
           <tr><td><strong>Подразделение:</strong> <? echo $rec['_org_name'].' '.$rec['_otdel_name']?></td></tr>
           <tr><td><strong>Должность:</strong> <? echo $rec['_work_name']?></td></tr>
       </table>
     </div>
   <?
  }

  function panel_card_space($rec)
  { ?><div class=item>
       <h2>№ <?echo $rec['propusk']?></h2>
       <img class="logo" src="<?echo _PATH_TO_SITE?>/images/logo.png" width="50">
       <img class=qrcode src="<?echo _PATH_TO_SITE?>/services/qrcode/<?echo $rec['propusk']?>/" />
       <table>
           <tr><td>ФИО:</td></tr>
           <tr><td></td></tr>
           <tr><td></td></tr>
           <tr><td>Подразделение:</td></tr>
           <tr><td></td></tr>
           <tr><td>Должность:</td></tr>
           <tr><td></td></tr>
       </table>
     </div>
   <?
  }


function upload_personal_from_file()
  {   //damp_array($this->filter) ;
      ob_start() ;
      ?><h2>Загрузка файла <?echo $this->filter['file_name'] ;

      $members=$this->parse_excel_file(_TEMP_DIR.$this->filter['file_name']) ;
      //damp_array($members) ;
      $arr_person_ids=array()  ;
      if (_sizeof($members)) foreach($members as $i=>$tabnumber)
        {  echo ($i+1).'. ' ;
          $rec=execSQL_van('select pkey,obj_name from obj_site_personals where tab_number="'.trim($tabnumber).'" ') ;
          if ($rec['pkey'])
          { echo $tabnumber.' - <span style="color:green;">ok</span><br>' ;
            $arr_person_ids[$rec['pkey']]=$tabnumber ;
          }
          else echo  $tabnumber.'<span style="color:red;"> - не найден </span><br>' ;
        }
      $text=ob_get_clean() ;
      $log_url=LOGS()->reg_file_log('upload_personal_from_xls',$text) ;

      if ($this->filter['view']!='CSV') echo 'Обработка файла "<strong>'.$this->filter['file_name'].'</strong>": Найдено <strong>'._sizeof($arr_person_ids).'</strong> из <strong>'._sizeof($members).'</strong> прочитанных записей, <a href="'.$log_url.'" target=_blank>смотреть лог</a><br>'  ;
        //damp_array($arr_person_ids) ;

      if (_sizeof($arr_person_ids)) $this->filter['person_ids']=array_keys($arr_person_ids) ;
  }

  function parse_excel_file($file_name)
  { $members = array();
    set_include_path(_DIR_TO_ROOT.'/AddOns/PHPExcel/');
    include_once 'PHPExcel/IOFactory.php';
    $objPHPExcel = PHPExcel_IOFactory::load($file_name);
    $objPHPExcel->setActiveSheetIndex(0);
    $aSheet = $objPHPExcel->getActiveSheet();
    if (is_object($aSheet))
    {   $rowIterator = $objPHPExcel->getActiveSheet()->getRowIterator();
        foreach($rowIterator as $row)
        { $cellIterator = $row->getCellIterator();
          $cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set
          foreach ($cellIterator as $cell) { $members[]=$cell->getCalculatedValue(); break ; }
        }
    }
    return($members) ;
 }



}

?>
