<?php
class report_docs extends c_report
{
 var $title='Документы' ;
 var $view_by_space_filter=1 ;
 var $allow_org_ids=1 ;
 var $usl_select_org='' ;
 var $doc_types_names=array() ;
 var $allow_export_to_csv=1 ;
 var $arr_unique_types_code=array() ;
 var $arr_unique_types_names=array() ;
 var $arr_unique_types_types_id=array() ;


 function init($options=array())
 {
 if (!_sizeof($_SESSION['arr_unique_types_names']))
 {
    //if (!$this->filter['group_id']) $this->filter['group_id']=MEMBER()->cur_group_id ;
    $exist_doc_types=execSQL_row('select distinct(t1.report_code) as report_code,(select obj_name from  obj_site_docs t2 where t2.report_code=t1.report_code and obj_name!="" limit 1) as doc_name 
                                  from obj_site_docs t1
                                  where t1.clss=215 and t1.report_code!="" and doc_name!=""  
                                  order by doc_name') ;
    if (_sizeof($exist_doc_types)) foreach($exist_doc_types as $code=>$name)
    {  $arr=explode('№',$name) ; //print_r($arr) ; echo '<br>' ;
       if (_sizeof($arr)<=2) $exist_doc_types[$code]=trim($arr[0]) ;
       else                 $exist_doc_types[$code]=trim($arr[0]).' № '.$arr[1]  ;
    }
    $arr_unique_types=array() ;
    $this->arr_unique_types_code[]='' ; // для удаление нулевого индекса
     if (_sizeof($exist_doc_types)) foreach($exist_doc_types as $code=>$name) { $arr_unique_types[$name][]='"'.$code.'"'; $arr_unique_types2[$name][]=$code; }
     if (_sizeof($exist_doc_types)) foreach($exist_doc_types as $code=>$name)
     { $this->arr_unique_types_code[$name]=implode(',',$arr_unique_types[$name]) ;
       if (sizeof($arr_unique_types2[$name])) foreach($arr_unique_types2[$name] as $type) $this->arr_unique_types_types_id[$type]=sizeof($this->arr_unique_types_code)-1 ;
     }
    $this->arr_unique_types_names=array_keys($this->arr_unique_types_code) ;
    $this->arr_unique_types_code=array_values($this->arr_unique_types_code) ;
    unset($this->arr_unique_types_names[0]) ;
    unset($this->arr_unique_types_code[0]) ;

    $_SESSION['arr_unique_types_names']=$this->arr_unique_types_names ;
    $_SESSION['arr_unique_types_code']=$this->arr_unique_types_code ;

}
else
{
      $this->arr_unique_types_names=$_SESSION['arr_unique_types_names'] ;
     $this->arr_unique_types_code=$_SESSION['arr_unique_types_code'] ;

}

    //damp_array($this->arr_unique_types_code) ; damp_array($this->arr_unique_types_names) ;
    //damp_array(REPORTS()->docs_list);
    //damp_array($arr_unique_types);
    //damp_array($this->arr_unique_types_types_id);
    //damp_array($this->arr_unique_types_names);
    //damp_array($this->arr_unique_types_code);
    //if (sizeof($exist_doc_types)) foreach($exist_doc_types as )

 }

 function setting($options=array())
 {
    $arr_accounts=ACCOUNTS()->get_list_members(array('group_id'=>MEMBER()->cur_group_id)) ;
    $arr_groups=ACCOUNTS()->get_arr_groups_to_cur_account() ;

    // внимание! исправить!
    // добавить список IL_doc_types
    // при создании нового документа, тип документа добавляется в список, если его там еще нет

    //$all_doc_types=execSQL('select * from reports order by obj_name',2) ;

    ?><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('group_id',$GLOBALS['LS_person_group_title'].':',2,$arr_groups) ;
                          $this->filter_section_select_multiple('doctor_ids','Автор документа:',2,$arr_accounts) ;
                          $this->filter_section_input_text('data_from','От:',2,array('class'=>'datetimepicker')) ;
                          $this->filter_section_input_text('data_to','До:',2,array('class'=>'datetimepicker')) ;
                          $this->filter_section_select_multiple('doc_types','Код документа:',2,$this->arr_unique_types_names) ;
                          $this->filter_section_input_text('doc_number','Номер:',1,array('auto_complete'=>"autocomplette_personal_name")) ;
                      ?>
                        <section class="col col-1">
                             <label class="label">Подпись</label>
                             <label class="checkbox"><input type="checkbox" name="filter[is_sign]" value="1" <?if ($this->filter['is_sign']==1) echo 'checked'?>><i></i> Да</label>
                             <label class="checkbox"><input type="checkbox" name="filter[not_sign]" value="1" <?if ($this->filter['not_sign']==1) echo 'checked'?>><i></i> Нет</label>
                           </section>
                        </div>
                  </fieldset>
                  <?$this->panel_buttons();?>
              </form>
       </div><br>
     <?
  }

  function create_usl_select_obj($_params,&$options)
  {  //damp_array($this->filter) ;
     $usl=array() ;
     $usl[]='clss=215' ;
     if (MEMBER()->rol==2)                 $usl[]='group_id='.MEMBER()->cur_group_id ; //фельшер должен видеть только документы, выданные в своей группе
     if ($this->filter['group_id'])        $usl[]='group_id in ('.ACCOUNTS()->get_childs_id($this->filter['group_id']).')' ;
     if ($this->filter['doctor_id'])       $usl[]='member_id='.$this->filter['doctor_id'] ;
     if ($this->filter['doctor_ids'])       $usl[]='member_id in ('.implode(', ',array_keys($this->filter['doctor_ids'])).')' ;
     if ($this->filter['doc_type'])
     {  $type_id=$this->arr_unique_types_types_id[$this->filter['doc_type']] ;
        //echo 'doc_type='.$this->filter['doc_type'].'<br>' ;
        //echo 'type_id='.$type_id.'<br>' ;
        if ($type_id) $usl[]='report_code in ('.$this->arr_unique_types_code[$type_id].')' ;
       // damp_array($this->arr_unique_types_types_id);

/*         $doc_type=str_replace('|','/',$this->filter['doc_type']) ;
        $arr_usl_types=array() ;
        $arr_usl_types[]='report_code="'.$doc_type.'"' ;
       // обеспечиваем совместимость старого и нового формата
       // старый формат: doc/esmo_magnit_pmo/zakluchenie
       // новый формат: esmo_magnit_pmo/doc_zakluchenie
       $arr=explode('/',$doc_type) ;
       //print_r($arr) ;
       if (_sizeof($arr)==3)
       { $new_format_doc_type=$arr[1].'/'.$arr[0].'_'.$arr[2] ;
         $arr_usl_types[]='report_code="'.str_replace('|','/',$new_format_doc_type).'"' ;
       }
       // последний вариант, получаем report_code из массива REPORTS()->docs_list
       if (isset(REPORTS()->docs_list[$this->filter['doc_type']])) $arr_usl_types[]='report_code="'.str_replace('.php','',REPORTS()->docs_list[$this->filter['doc_type']]['script_dir']).'"' ;

       $usl[]='('.implode(' or ',$arr_usl_types).')' ;
*/


     }
     if ($this->filter['doc_types'] and _sizeof($this->filter['doc_types']))
     {   $arr=array() ;
         foreach($this->filter['doc_types'] as $doc_type=>$ttt) $arr[]='report_code in ('.$this->arr_unique_types_code[$doc_type].')' ;
         $usl[]=implode(' or ',$arr) ;
     }
     if ($this->filter['doc_number'])      $usl[]='indx="'.$this->filter['doc_number'].'"' ;
     if ($this->filter['name'])            $usl[]='_personal_name="'.$this->filter['name'].'"' ;
     if ($this->filter['is_sign'])         $usl[]='sign_member>0' ;
     if ($this->filter['not_sign'])        $usl[]='sign_member=0' ;
     if ($this->filter['data_from'])       $usl[]='c_data>='.strtotime($this->filter['data_from']) ;
     if ($this->filter['data_to'])         $usl[]='c_data<='.strtotime($this->filter['data_to']) ;
     if ($this->filter['personal_id'])     $usl[]='personal_id='.$this->filter['personal_id'] ;
     if ($this->filter['event_id'])        $usl[]='event_id='.$this->filter['event_id'] ;
     if ($this->filter['lession_id'])        $usl[]='lession_id='.$this->filter['lession_id'] ;
     if ($this->filter['obj_reffer'])     $usl[]='obj_reffer="'.$this->filter['obj_reffer'].'"' ;
     $usl_res=implode(' and ',$usl) ;
     //damp_array($usl,-1,1) ;
     return($usl_res) ;
  }

 function panel_info_filter()
 { $_str=array() ; $info=array() ; $title='' ;
   if (MEMBER()->rol==2)                 $info['Группа документа']=ACCOUNTS()->get_group_name(MEMBER()->cur_group_id) ;
   if ($this->filter['group_id'])        $info['Группа']=ACCOUNTS()->get_group_name($this->filter['group_id']) ;
   if ($this->filter['doctor_id'])       $info['Автор документа']=ACCOUNTS()->get_member_name_by_id($this->filter['doctor_id']) ;
   if ($this->filter['doctor_ids'])      $info['Авторы документов']=ACCOUNTS()->get_members_names_by_ids(array_keys($this->filter['doctor_ids'])) ;
   if ($this->filter['name'])            $info['ФИО сотрудника']=$this->filter['name'];
   if ($this->filter['doc_type'])        $info['Тип документа']=$this->doc_types_names[$this->filter['doc_type']] ;
   if ($this->filter['doc_types'] and _sizeof($this->filter['doc_types']))
   {  $arr=array() ;
      foreach($this->filter['doc_types'] as $doc_type=>$ttt) $arr[]=$this->arr_unique_types_names[$doc_type] ;
      $info['Тип документа']=implode(', ',$arr) ;
   }
   if ($this->filter['doc_number'])      $info['№']=$this->filter['doc_number'] ;
   if ($this->filter['is_sign'])         $info['Подпись']='Есть' ;
   if ($this->filter['not_sign'])        $info['Подпись']='Нет' ;
     if ($this->filter['data_from'])     $info['дата от']='"'.$this->filter['data_from'].'"' ;
     if ($this->filter['data_to'])       $info['дата до']='"'.$this->filter['data_to'].'"' ;
   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  view_docs_scan
                        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 pkey desc' ;
    //$options['debug']=2 ;
 	$list_rec=execSQL('select *
                       from  view_docs_scan
                       where '.$usl.$order.$limit,$options) ;
    if (_sizeof($list_rec)) foreach($list_rec as $id=>$rec) DOCS()->prepare_public_info_to_doc($list_rec[$id],$options) ;
    return($list_rec) ;
  }


// шаблон - вывод ссылками без разделитея
  function print_template_HTML($list_recs,$options=array())
  { $id=($options['id'])? 'id='.$options['id']:'' ;
    $recs_account=execSQL_row('select pkey,obj_name from obj_site_account where clss=210') ;
    ?><table class="basic fz_small full auto"<?echo $id?>>
        <tr><th>№</th><th>Создан</th><th>Группа</th><th>Автор</th><th>Наименование</th><th>Сотрудник</th><th>Подписан</th><th>Дата подписи</th><th>Мероприятие</th><th>Дата сдачи</th></tr><?
          if (_sizeof($list_recs)) foreach($list_recs as $rec)
          {   if (!$rec['code']) $rec['code']='PDF' ; // для совместимости с документами прежней версии
              $url=$rec['__href'] ;
              $rec_pass=array() ;
              //if (!$options['doc_url_template']) $url=$rec['__href'] ;
              //else $url=str_replace('***',$rec['pkey'],$options['doc_url_template']) ;

              // иещем мероприятие по ID документа в pass
              /*$rec_pass=execSQL_van('select * from obj_site_events_pass where doc_id='.$rec['pkey']) ;
              $obj_event=null ;
              if ($rec_pass['pkey'])
              { $rec_event=EVENTS()->get_event_by_id($rec_pass['event_id']) ;
                $obj_event=EVENTS()->get_event_obj_by_ext($rec_event['ext']) ;
              } else $rec_event=array() ;
              */
              // ищем мероприятие по source_pkey и source_obj
              $obj_event=null ;
              if ($rec['source_obj'] and $rec['source_pkey'] and function_exists('EVENTS'))
              { $obj_event=EVENTS()->get_event_obj_by_ext($rec['source_obj']) ;
                if ($rec['source_tkey']==_DOT('obj_site_events_schedule')->pkey) $rec_event=EVENTS()->get_event_by_id($rec['source_pkey']) ;
                if ($rec['source_tkey']==_DOT('obj_site_events_pass')->pkey)
                { $rec_pass=EVENTS()->get_event_pass_by_id($rec['source_pkey']) ;
                if ($rec_pass['event_id']) $rec_event=EVENTS()->get_event_by_id($rec_pass['event_id']) ;
                }
              } else $rec_event=array() ;

              ?><tr>
                  <td><?echo $rec['pkey']?></td>
                  <td><?echo date('d.m.Y H:i',$rec['c_data'])?></td>
                  <td><?echo $rec['_group_name']?></td>
                  <td class="left"><?echo $recs_account[$rec['member_id']]?></td>
                  <td class="left"><a href="<?echo $url?>" class="new_window" title="doc_<?echo $rec['pkey']?>"><?echo $rec['obj_name']?></a></td>
                  <td class="left"><?
                      if ($rec['personal_id'])
                      { $arr=array() ;
                        $arr[]='<a href="/window/personal/person/'.$rec['personal_id'].'/" class="new_window" title="person_'.$rec['personal_id'].'">'.$rec['_personal_name'].'</a>' ;
                        if ($rec['_personal_dr']) $arr[]=$rec['_personal_dr'].' г.р.' ;
                        if ($rec['_personal_org_name']) $arr[]=$rec['_personal_org_name'] ;
                        if ($rec['_personal_work_id']) $arr[]=_IL('IL_works')->recs[$rec['_personal_work_id']]['obj_name'] ;
                        echo implode('<br>',$arr) ;
                      }
                      ?></td>
                  <td><?echo ($rec['sign'])? 'Да':''?></td>
                  <td><?echo ($rec['sign'])? date('d.m.Y H:i',$rec['sign_data']):''?></td>
                  <td><? if ($obj_event!=null) echo $obj_event->name.'<br>"'.$rec_event['obj_name'].'"<br>['.$rec['source_pkey'].']' ; ?></td>
                  <td><? // для выдачи документов пишет правильно - "сдача просрочена", для остальных меропритий это не подходит так как arr_status - статусы сотрудника, а не документа
                         //if ($rec_pass['status'] and is_object($obj_event)) echo $obj_event->arr_status[$rec_pass['status']].'<br>';
                      if (stripos($rec['source_obj'],'event_docs')!==false)
                        {  $doc_status=($rec['pkey'])? EVENT_DOCS()->arr_status[$rec_pass['status']]:'' ;
                           $doc_close_time=($rec['scan_data_set'])? date('d.m.Y H:i:s',$rec['scan_data_set']):$doc_status ;
                           $doc_close_time=($rec_pass['close_data'])? date('d.m.Y H:i:s',$rec_pass['close_data']):$doc_close_time ;
                        }
                        else
                        {  $doc_status=($rec['scan_data_set'])? 'Документ сдан':'' ;
                           $doc_close_time=($rec['scan_data_set'])? date('d.m.Y H:i:s',$rec['scan_data_set']):$doc_status ;
                        }
                        echo $doc_close_time ;
                      ?>
                  </td>
              </tr><?
          }
      ?></table><?
      //damp_array($rec) ;
  }

// шаблон - вывод ссылками без разделитея
  function template_HTML_check($list_recs,$options=array())
  { $id=($options['id'])? 'id='.$options['id']:'' ;
    $recs_account=execSQL_row('select pkey,obj_name from obj_site_account where clss=210') ;
    ?><table class="basic fz_small full auto"<?echo $id?>>
        <tr><th>Выбор</th><th>№</th><th>Создан</th><th>Группа</th><th>Автор</th><th>Наименование</th><th>Сотрудник</th><th>Подписан</th><th>Дата подписи</th><!--<th>Информация ЭЦП</th>--></tr><?
          if (_sizeof($list_recs)) foreach($list_recs as $rec)
          {   if (!$rec['code']) $rec['code']='PDF' ; // для совместимости с документами прежней версии
              if (!$options['doc_url_template']) $url=$rec['__href'] ;
              else $url=str_replace('***',$rec['pkey'],$options['doc_url_template']) ;

              ?><tr>
                  <td><input type="<?echo ($options['check_type'])? $options['check_type']:'checkbox'?>" name="_check[]" value="<?echo $rec['_reffer']?>"></td>
                  <td><?echo $rec['pkey']?></td>
                  <td><?echo date('d.m.Y H:i',$rec['c_data'])?></td>
                  <td><?echo $rec['_group_name']?></td>
                  <td class="left"><?echo $recs_account[$rec['member_id']]?></td>
                  <td class="left"><a href="<?echo $url?>" class="new_window" title="doc_<?echo $rec['pkey']?>"><?echo $rec['obj_name']?></a></td>
                  <td class="left"><?
                      if ($rec['personal_id'])
                      { $arr=array() ;
                        $arr[]='<a href="/window/personal/person/'.$rec['personal_id'].'/" class="new_window" title="person_'.$rec['personal_id'].'">'.$rec['_personal_name'].'</a>' ;
                        if ($rec['_personal_dr']) $arr[]=$rec['_personal_dr'].' г.р.' ;
                        if ($rec['_personal_org_name']) $arr[]=$rec['_personal_org_name'] ;
                        if ($rec['_personal_work_id']) $arr[]=_IL('IL_works')->recs[$rec['_personal_work_id']]['obj_name'] ;
                        echo implode('<br>',$arr) ;
                      }
                      ?></td>
                  <td><?echo ($rec['sign'])? 'Да':''?></td>
                  <td><?echo ($rec['sign'])? date('d.m.Y H:i',$rec['sign_data']):''?></td>
                  <!--<td class="left small"><?$arr=unserialize($rec['sign']);
                        if (is_array($arr)) foreach($arr as $id=>$value) if ($value) echo '<strong>'.$id.'</strong>: '.$value.'<br>' ;
                  ?></td>-->
              </tr><?
          }
      ?></table><?
      //damp_array($rec) ;
  }

  function print_template_CSV($list_recs,$options=array())
   { $i=$options['from'] ;
     $recs_account=execSQL_row('select pkey,obj_name from obj_site_account where clss=210') ;
     if (_sizeof($list_recs)) foreach($list_recs as $rec)
       { //$sign_info=($rec['sign'])? unserialize($rec['sign']):array() ;
         $data=array() ;
         $data['id']=$rec['pkey'] ;
         $data['mo_id']=$rec['mo_id'] ;
         $data['Дата/время']=date('d.m.Y H:i:s',$rec['c_data']) ;
         $data['АТП']=$rec['_group_name'] ;
         $data['Код документа']=$rec['report_code'] ;
         $data['Наименование документа']=$rec['obj_name'] ;
         $data['Подпиcан']=($rec['sign'])? 'Да':'' ;
         $data['Автор документа']=$recs_account[$rec['member_id']] ;
         $data['ФИО сотрудника']=$rec['_personal_name'] ;
         $data['Дата рождения']=$rec['_personal_dr'] ;
         $data['Организация']=$rec['_personal_org_name'] ;

         $this->put_data_to_CSV($data,$i) ;
         $i++ ;
       }

   }

}

?>
