<?php
class report_pl_packets extends c_report
{
 var $title='Лог пакетов ПЛ' ;
 var $view_by_space_filter=1 ;
 var $type='' ;
 var $group_id=0 ;
 var $status='' ;
 var $no_view_button=0 ;
 var $left_join=[] ;

 function setting($options=array())
 {    ?><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_input_text('id','ID пакета:',2) ;
                          $this->filter_section_input_text('driver_name','ФИО водителя:',2) ;
                          $this->filter_section_select('type','Тип пакета:',2,PL()->arr_packet_type) ;
                          if ($this->filter['type']) $this->filter_section_select('status','Статус пакета:',2,PL()->arr_packet_titul_status[$this->filter['type']]) ;
                          $this->filter_section_input_text('data_from','От:',2,array('class'=>'datetimepicker')) ;
                          $this->filter_section_input_text('data_to','До:',2,array('class'=>'datetimepicker')) ;
                          ?>
                        </div>
                  </fieldset>
                  <?$this->panel_button_apply();?>
              </form>
       </div><br>
     <?
  }

  function create_usl_select_obj($_params,&$options)
  {  //damp_array($this->filter) ;//
     $usl=array() ;
     $usl[]='true';
     if ($this->filter['type'])              $usl[]='pk.packet_type='.$this->filter['type'] ;
     if ($this->filter['type'] and $this->filter['status'])  $usl[]='pk.status='.$this->filter['status'] ;
     if ($this->type)                        $usl[]='pk.packet_type in ('.$this->type.')' ;
     if ($this->filter['status'])            $usl[]='pk.status in ('.$this->filter['status'].')' ;
     if ($this->status)                      $usl[]='pk.status in ('.$this->status.')' ;
     if ($this->filter['data_from'])        $usl[]='pk.c_data>='.strtotime($this->filter['data_from']) ;
     if ($this->filter['data_to'])          $usl[]='pk.c_data<='.strtotime($this->filter['data_to']) ;
     if ($this->filter['id'])               $usl[]='pk.pkey='.$this->filter['id'] ;
     if ($this->filter['driver_name'])
     {
         $rec_personal=PERSONAL()->get_personal(['obj_name'=>$this->filter['driver_name']]) ;
         //damp_array($rec_personal);
         $usl[]=($rec_personal['pkey'])? 'dr.driver_id='.$rec_personal['pkey']:'false' ;
				 $this->left_join['dr']='left join pl_packet_driver dr on dr.packet_id=pk.pkey' ;
     }
     if ($this->group_id)
     {
         $usl[]='(mo_now.group_id='.$this->group_id.' or mo.group_id='.$this->group_id.')' ;
				 $this->left_join['dr']='left join pl_packet_driver dr on dr.packet_id=pk.pkey' ;
				 $this->left_join['mo_now']='left join obj_site_mo_session_now mo_now on mo_now.pkey=dr.mo_id' ;
				 $this->left_join['mo']='left join obj_site_mo_session mo on mo.pkey=dr.mo_id' ;
     }
		//damp_array($usl);


     $usl_res=implode(' and ',$usl) ;
     return($usl_res) ;
  }

 function panel_info_filter()
 { $_str=array() ; $info=array() ; $title='' ;
   if ($this->filter['type'])                            $info['Тип пакета']='"'.PL()->arr_packet_type[$this->filter['type']].'"' ;
   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(pk.pkey)
                        from  pl_packets pk
                        '.implode("\n",$this->left_join).'
                        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 ;
    //echo $usl ;
 	$list_rec=execSQL('select pk.*,
 	                   pl.driver_id as _driver_id,pl.car_id as _car_id,pl.number as _pl_number,pl.uid as _pl_uid,pl.date as _pl_date
                       from  pl_packets pk
                       left join pl_put_list pl on pl.pkey=pk.pl_id
                       '.implode("\n",$this->left_join).'
                       where '.$usl.$order.$limit,$options) ;
    //if (_sizeof($list_rec)) foreach($list_rec as $id=>$rec) ESMO()->prepare_public_info_to_mo($list_rec[$id],$options) ;
    return($list_rec) ;
  }


// шаблон - вывод ссылками без разделитея
  function print_template_HTML($list_recs,$options=array())
  { $id=($options['id'])? 'id='.$options['id']:'' ;

    $result_mo=(sizeof($list_recs))? PL()->get_mo_to_packets($list_recs):[] ;
    //print_2x_arr($result_mo);
    ?>
      <table id=report_packets class="basic fz_small full auto" <?echo $id?>>
        <tr>
            <th>ID</th>
            <th>Дата, время создания</th>
            <th>Направление пакета</th>
            <th>Тип пакета</th>
            <th>Статус пакета</th>
            <th>Содержимое пакета</th>
            <th>Подпись пакета</th>
            <!--<th>ID связанного пакета</th>-->
            <!--<th>UID пакета</th>
            <th>Тип пакета</th>-->
            <th>Дата/время пакета</th>
            <th>Путевой лист</th>
            <th>Водитель</th>
            <th>Авто</th>
            <th>Последний МО водителя</th>
            <?if (!$this->no_view_button){?><th>Операции</th><?}?>
        </tr><? ;
        if (_sizeof($list_recs)) foreach($list_recs as $rec)
        {   if (!$rec['_car_number']) $rec['_car_number']=$rec['car_number'] ;
            if (!$rec['_pl_number']) $rec['_pl_number']=$rec['pl_number'] ;
            if (!$rec['_pl_uid']) $rec['_pl_uid']=$rec['pl_uid'] ;
            if (!$rec['_pl_date']) $rec['_pl_date']=$rec['pl_date'] ;
            ?><tr>
              <td><a href="/window/pl/packet/<? echo $rec['pkey'] ?>/" class="new_window"><? echo $rec['pkey'] ?></a></td>
              <td class=data><? echo date('d.m.Y H:i:s',$rec['c_data']) ;?></td>
              <td><? echo PL()->arr_packet_mode[$rec['packet_mode']] ?></td>
              <td><? echo PL()->arr_packet_type[$rec['packet_type']] ?></td>
              <td><?  echo PL()->arr_packet_titul_status_color[$rec['packet_type']][$rec['status']] ;
                      if ($rec['error'])
                      { echo '<div class="alert2">'.PL()->arr_packet_error[$rec['error']].'</div>';
                        if ($rec['obj_name'])
                        { $arr=json_decode($rec['obj_name'],true);
                          //  damp_array($arr);
                          if (_sizeof($arr['driver_not_found'])) echo implode('<br>',$arr['driver_not_found']) ;
                          if (_sizeof($arr['mo_not_found'])) echo implode('<br>',$arr['mo_not_found']) ;
                        }
                      }
                  ?>
              </td>
              <td><? if($rec['xml_size'])
                      { ?><a class="v2" cmd="pl/show_packet_xml" packet_id="<?echo $rec['pkey']?>"><i class="fa fa-file-text size18" aria-hidden="true"></i></a><br><?
                          echo $rec['xml_size'].' байт<br>' ;
                          ?><a href="/services/pl/get_packet/<?echo $rec['pkey']?>/" target="_blank">Скачать</a><?
                      }
                  ?>
              </td>
              <td><? if($rec['sign_size'])
                     {?><!--<a class="v2" cmd="pl/show_packet_sign" packet_id="<?echo $rec['pkey']?>"><i class="fa fa-file-text size18" aria-hidden="true"></i></a><br>--><?
                         echo $rec['sign_size'].' байт<br>' ;
                         ?><a href="/services/pl/get_packet_sign/<?echo $rec['pkey']?>/" target="_blank">Скачать</a><?
                     }
                   ?>
              </td>
              <?/*?><td><? if ($rec['packet_type']==1)
                     {
                         $ids=execSQL_line('select pkey from pl_packets where titul1_id='.$rec['pkey']) ;
                         echo implode(', ', $ids) ;
                     }
                     if ($rec['packet_type']==2) echo $rec['titul1_id'] ;
                  ?>
              </td>*/?>
              <!--<td><? echo mb_substr($rec['file_uid'],0,5).'...'.mb_substr($rec['file_uid'],mb_strlen($rec['file_uid'])-1,-5) ?></td>
              <td><? echo $rec['knd'] ?></td>-->
              <td class=data><?

                  $day_from=date('d.m.Y',$rec['titul_date_from']) ;
                  $day_to=date('d.m.Y',$rec['titul_date_to']) ;
                  if ($day_from!=$day_to) echo $day_from.' - '.$day_to ;
                  else echo $day_from ;


              ?></td>
              <td><? echo $rec['_pl_number'] ?><br><? echo $rec['_pl_uid'] ?><br><?

                  //echo date('d.m.Y',$rec['_pl_date']) ;

                  ?></td>
              <td class="left"><?
                                  $arr_drivers_fio=execSQL_row('select pkey,driver_fio from pl_packet_driver where packet_id='.$rec['pkey']) ;
                                  ?><ul><?
                                  if ($arr_drivers_fio) foreach($arr_drivers_fio as $driver_fio) echo '<li>'.$driver_fio.'</li>' ;
                                  ?></ul><?
              ?></td>
              <td><? echo $rec['_car_number'] ;?></td>
              <td><?
                  $mo_info=$result_mo[$rec['pkey']] ;
									//damp_array($mo_info);
                  if ($mo_info['pkey'])
                  {
                      if ($mo_info['tk']==0) echo 'Предрейсовый' ;
                      if ($mo_info['tk']==1) echo 'Послерейсовый' ;
                      if ($mo_info['tk']==2) echo 'Межрейсовый' ;

                      if ($mo_info['errors']) echo '<div class=red>'.$mo_info['errors'].'</div>' ;
                      else
                          {
                              echo '<div class=green>MO ID '.$mo_info['pkey'].' от '.date('d.m.Y H:i',$mo_info['c_data']).'</div>Допуск: '.date('d.m.Y H:i',$mo_info['dopusk_time']).' - '.date('d.m.Y H:i',$mo_info['dopusk_time_end']) ;
                          }

                  }
                  //echo '<br><strong>'.$rec['driver_mo_id'].'</strong><br>' ;
                  echo '<div class=comment>'.$mo_info['doctor_name'].'</div>' ;
                  echo '<div class=small>'.$mo_info['group_name'].'</div>' ;


                    //if ($rec['mo_id']) echo 'MO ID '.$rec['mo_id'].'<br>'.ESMO()->get_mo_tk_type($rec['tk'],$rec['tkm']).'<br>Пройден '.date('d.m.Y H:i',$rec['mo_c_data']).'<br>Допуск до '.date('d.m.Y H:i',$rec['dopusk_time_end'])?>
              </td>
					 <?if (!$this->no_view_button){?>
            <td><? // входящий пакет, пока не подписан ответ
                   if ($rec['packet_type']==1 and $rec['status']==1) {?><button class=v2 cmd="pl/parse_packet" packet_id="<?echo $rec['pkey']?>">Обработать пакет</button><?} ;
                   // исхощяший пакет, отправлен на подпись
                   if ($rec['packet_type']==2 or $rec['packet_type']==6)
                   {    if ($rec['status']==1) {?><button class=v2 cmd="pl/check_packet_mo" packet_id="<?echo $rec['pkey']?>">Проверить МО</button><?} ;
                        if ($rec['status']==2)
                           { ?><button class=v2 cmd="pl/check_packet_mo" packet_id="<?echo $rec['pkey']?>">Проверить МО</button><?
														 if ($mo_info['pkey'])
                             { ?><button class=v2 cmd="pl/send_to_sing" packet_id="<?echo $rec['pkey']?>" doctor_id="<?echo $mo_info['doctor_id']?>">Отправить пакет на подпись</button><?
														  ?><button class=v2 cmd="pl/check_packet_sign" packet_id="<?echo $rec['pkey']?>">Проверить подпись пакета</button><?
							 							  }
                           }
                   }

            ?></td><?}?>
              <!--<td><? if ($rec['session_uid'] and file_exists(_DIR_TO_ROOT.'/logs/import_trace_'.$rec['session_uid'].'.html')) echo '<a target="blank" href="/logs/import_trace_'.$rec['session_uid'].'.html">'.$rec['session_uid'].'</a>' ?></td>-->

           </tr><?
        }
    ?></table>
      <style type="text/css">
          table#report_packets{}
          table#report_packets ul{margin:0;padding-left:0;}
          table#report_packets ul li{}
      </style>
      <?
  }

}

?>
