<?php
class report_map_mo_drivers extends c_report
{
 var $title='Карта предрейсовых, послерейсовых медицинских осмотров водителей' ;
 var $view_by_space_filter=0 ;
 var $allow_org_ids=1 ;
 var $usl_select_org='' ;
// var $allow_export_to_csv=1 ;
 var $arr_members_mo=[];
 var $arr_members=[];
 var $arr_members_group=[];
 var $arr_members_age_group=[];
 var $arr_itog=[];
 var $days_in_period;
 var $days_array;
 var $arr_type_view=array(  1=>'Неделя',
                            2=>'Две недели',
                            3=>'Месяц',
                            4=>'Интервал');
 var $now_date;
 var $period_name;
 var $period_start;
 var $period_end;
 var $not_send_report = 1; //Не выводить в модуле Отправка отчетов


 function setting($options=array())
 {
     if (!$this->filter['type_view']) $this->filter['type_view']=1;
     $data_info=execSQL_van('select min(c_data) as min_data,max(c_data) as max_data from obj_site_mo_session') ;
     $this->mo_data_min=$data_info['min_data'] ;
     $this->mo_data_max=$data_info['max_data'] ;
     $t=$this->mo_data_min ;
     if ($this->mo_data_max>$this->mo_data_min) while($t<$this->mo_data_max)
     {   $ts=getdate($t) ;
         $cur_month=mktime(0,0,0,$ts['mon'],1,$ts['year']) ;
         $arr_from[$cur_month]=get_month_year($cur_month,'month year') ;
         $t=mktime(0,0,0,$ts['mon']+1,1,$ts['year']) ;
     }

     $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) ;

     if (!$this->filter['violation_time'] or !is_numeric($this->filter['violation_time'])) $this->filter['violation_time']=12;

//    damp_array($_POST,1,-1);
     ?><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">
                         <div class="row">
                             <?
                             $this->filter_section_select('group_id','Группа:',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) ;
                             $this->filter_section_input_text('name','ФИО, пропуск или UID:',2,array('auto_complete'=>"autocomplette_personal_name")) ;
                             $this->filter_section_select('type_view','Тип отображения:',2,$this->arr_type_view,array('nospace_element'=>1)) ;
                             ?>
                         </div>
                         <div class="row">
                             <?
                             $this->filter_section_input_text('violation_time','Разрыв между заездом и выездом не менее:',3) ;
                             $this->filter_section_input_text('data_from','От:',2,array('class'=>'datepicker')) ;
                             $this->filter_section_input_text('data_to','До:',2,array('class'=>'datepicker')) ;
                             ?>
                         </div>
                         <div class="row">
                             <section class="col col-3">
                                 <label class="checkbox"><input type="checkbox" name="filter[no_display_table]" value="1"  <?if ($this->filter['no_display_table']=='1') echo 'checked'?>><i></i>Не отображать таблицу</label>
                             </section>
                         </div>
                 </fieldset>
                 <div id="panel_buttons">
                     <?if ($this->filter['type_view']!=4){?>
                     <div>
                         <?
                         $view_value_arr=$this->get_view_type($this->filter['type_view'],$this->filter['view_value']);
                         $this->period_name=$view_value_arr['name'];
                         ?>
                         <button class="button v2" cmd="report/set_filter_with_button" view_value="<?echo $view_value_arr['prev']?>" style="margin:0; padding: 0 20px;">
                             <i class="fa fa-arrow-left" aria-hidden="true"></i>
                         </button>
                         <?echo $view_value_arr['name'];?>
                         <button class="button v2" cmd="report/set_filter_with_button" view_value="<?echo $view_value_arr['next']?>" style="margin:0; padding: 0 20px;">
                             <i class="fa fa-arrow-right" aria-hidden="true"></i>
                         </button>
                     </div>
                     <?} else $this->get_days_array($this->filter['type_view'])?>
                     <input type="submit" class="button v2" cmd="report/set_filter_with_button" <?if ($this->filter['view_value']) echo 'view_value="'.$this->filter['view_value'].'"'?> value="<?echo ($this->editing)? 'Получить данные':'Сформировать отчет'?>">&nbsp;&nbsp;<?
                     if (!$this->editing)
                     {?><button class="button v2" cmd="docs/doc_create">Сохранить в документах</button>&nbsp;&nbsp;<??>
                         <button class="button v2" cmd="report/view_as_html_with_button" <?if ($this->filter['view_value']) echo 'view_value="'.$this->filter['view_value'].'"'?>>HTML</button>&nbsp;&nbsp;
                         <button class="button v2" cmd="report/view_as_pdf_with_button" mode="<?echo $this->PDF_master?>" <?if ($this->filter['view_value']) echo 'view_value="'.$this->filter['view_value'].'"'?>>PDF</button>&nbsp;&nbsp;
                         <?if ($this->allow_export_to_excel){?><button class="button v2" cmd="surgut_import/view_as_xls" <?if ($this->filter['view_value']) echo 'view_value="'.$this->filter['view_value'].'"'?>>Excel</button>&nbsp;&nbsp;<?}?>
                         <?if ($this->allow_export_to_csv){?><button class="button v2" cmd="surgut_import/view_as_CSV" <?if ($this->filter['view_value']) echo 'view_value="'.$this->filter['view_value'].'"'?>>Excel CSV</button>&nbsp;&nbsp;<?}?>
                         <button class="button v2" cmd="report/to_print_with_button" <?if ($this->filter['view_value']) echo 'view_value="'.$this->filter['view_value'].'"'?>>Печать</button>&nbsp;&nbsp;
                     <?}
                     ?></div>
              </form>
       </div><br>
     <?
  }

  function get_days_array($type)
  {
    if ($type==4)
    {
        if ($this->filter['data_from'] and $this->filter['data_to'])
        {
            $data_from=strtotime($this->filter['data_from']);
            $data_to=strtotime($this->filter['data_to']);
            $this->period_start=$data_from;
            $this->period_end=$data_to;
            if ($data_to>$data_from)
            {
                $date_diff=date_diff(
                    date_create($this->filter['data_to']),
                    date_create($this->filter['data_from'])
                )->format('%a')+1;
                for($i=0;$i<$date_diff;$i++)
                {
                    //формируем дату на день $i от $data_from
                    $ts=getdate($data_from+(60*60*24*$i));
                    $temp_array=[];
                    $now_date=getdate();
                    if ($now_date['year']==$ts['year'] and $now_date['mon']==$ts['mon'] and $now_date['mday']==$ts['mday']) $temp_array['now_date']=1;
                    $temp_array['number']=$ts['mday'];
                    if ($ts['wday']==6 or $ts['wday']==0)  $temp_array['day_off']=1;
                    $this->days_array[]=$temp_array;
                }
            }
        }
    }
  }

  function get_view_type($type,$value=0,$options=array()){

      if ($type==2) $this->days_in_period=14;   //для типа отображения 2 недели и неделя запоминаем кол-во дней в периоде
      elseif ($type==1) $this->days_in_period=7;

      if (!$value){ //если начало периода не задано, то вычисляем его
          $ts=getdate();
          if ($type==3) {
            $t=mktime(0,0,0,$ts['mon'],1,$ts['year']);
          } else {
            $dw=($ts['wday'])? $ts['wday']-1:6 ;
            $t=mktime(0,0,0,$ts['mon'],$ts['mday']-$dw-($this->days_in_period-7),$ts['year']);
          }
          $period_time_start=$t;
      } else { //если начало периода задано
          $ts=getdate($value);
          if ($type!=3) {
            $dw=($ts['wday'])? $ts['wday']-1:6 ;
          }
          $period_time_start=$value;
      }
      $now_date=getdate();
      switch ($type){
          case 3:
              $this->days_in_period=cal_days_in_month(CAL_GREGORIAN, $ts['mon'], $ts['year']);
              $result['prev']=mktime(0,0,0,$ts['mon']-1,1,$ts['year']);
              $result['next']=mktime(0,0,0,$ts['mon']+1,1,$ts['year']);
              for($i=1;$i<=$this->days_in_period;$i++){
                $temp_array=[];
                $temp_array['number']=$i;
                $week_day=getdate(mktime(0,0,0,$ts['mon'],$i,$ts['year']));
                if ($period_time_start<=time() and time()<$result['next']) {
                  if ($now_date['mday']==$week_day['mday']) $temp_array['now_date']=1;
                }
                if ($week_day['wday']==6 or $week_day['wday']==0)  $temp_array['day_off']=1;
                $this->days_array[]=$temp_array;
              }
              $result['name']=get_month_year($period_time_start,'month year') ;
              break;
          default:
              $time_array=getdate($period_time_start);
              $result['prev']=mktime(0,0,0,$time_array['mon'],$time_array['mday']-$this->days_in_period,$time_array['year']);
              $result['next']=mktime(0,0,0,$time_array['mon'],$time_array['mday']+$this->days_in_period,$time_array['year']);
              $now_date_in_array=false;
              if ($period_time_start<=time() and time()<$result['next']) {
                  $now_date_in_array=true;
              }
              $time_start_array=getdate($period_time_start);
              $time_end_array=getdate($result['next']-1);
              if ($time_start_array['mon']==$time_end_array['mon']) { //если месяц один и тотже
                  for ($i=$time_start_array['mday'];$i<=$time_end_array['mday'];$i++) { //заполняем массив с числами
                      $temp_array=[];
                      $temp_array['number']=$i;
                      if ($now_date_in_array) if ($now_date['mday']==$i) $temp_array['now_date']=1;
                      $this->days_array[]=$temp_array;
                  }
                  $this->days_array[5]['day_off']=1; $this->days_array[6]['day_off']=1; //заполняем выходные для первой недели
                  if ($this->days_in_period==14) { //если тип отображения две недели, то заполняем второю неделю
                      $this->days_array[12]['day_off']=1; $this->days_array[13]['day_off']=1;
                  }
              } else {
                  //если месяц меняется
                  for($i=$time_start_array['mday'];$i<=cal_days_in_month(CAL_GREGORIAN, $time_start_array['mon'], $time_start_array['year']);$i++){
                      //заполняем массив числами первого месяца
                      $temp_array=[];
                      $temp_array['number']=$i;
                      if ($now_date_in_array) if ($now_date['mday']==$i) $temp_array['now_date']=1;
                      $this->days_array[]=$temp_array;
                  }
                  for ($i=1;$i<=$time_end_array['mday'];$i++) {
                      //заполняем массив числами второго месяца
                      $temp_array=[];
                      $temp_array['number']=$i;
                      if ($now_date_in_array) if ($now_date['mday']==$i) $temp_array['now_date']=1;
                      $this->days_array[]=$temp_array;
                  }
                  $this->days_array[5]['day_off']=1; $this->days_array[6]['day_off']=1;
                  if ($this->days_in_period==14) {
                      $this->days_array[12]['day_off']=1; $this->days_array[13]['day_off']=1;
                  }
              }
              if ($time_start_array['mon'] == $time_end_array['mon'])
              {
                  $result['name'] = date('d',$period_time_start).' - '.get_month_year(($result['next']-1),'day month year',array('no_year_word'=>1));
              } elseif ($time_start_array['year'] == $time_end_array['year'])
              {
                  $result['name'] = get_month_year($period_time_start,'day month').' - '.get_month_year(($result['next']-1),'day month year',array('no_year_word'=>1));
              } else
                  $result['name'] = get_month_year($period_time_start,'day month year',array('no_year_word'=>1)).' - '.get_month_year(($result['next']-1),'day month year',array('no_year_word'=>1));
              break;
      }
      if ($period_time_start<=time() and time()<$result['next']) {
        $this->now_date=getdate()['mday'];
      }
      $this->period_start=$period_time_start;
      $this->period_end=$result['next']-1;
      return $result;
  }

 function panel_info_filter()
 { $_str=array() ; $info=array() ; $title='' ;

   if ($this->filter['org_ids'])               $info['Организация']=PERSONAL()->get_org_names_by_ids(array_keys($this->filter['org_ids']))  ;
   if ($this->filter['otdel_ids'])             $info['Подразделениe']=PERSONAL()->get_org_names_by_ids(array_keys($this->filter['otdel_ids']))  ;
   if ($this->filter['type_view'])            {
       $info['Тип отображения']=$this->arr_type_view[$this->filter['type_view']] ;
   } else {
       $info['Тип отображения']=$this->arr_type_view[0] ;
   }
   if ($this->filter['type_view']!=4) {
   $info['Период']=$this->period_name;
   } else {
       $info['Период']='от '.$this->filter['data_from'].' до '.$this->filter['data_to'];
   }
   if ($this->filter['group_medic'])
   {   $arr=array() ;
       if (_sizeof(_IL('IL_group_medic')->recs)) foreach(_IL('IL_group_medic')->recs as $rec_group) if (isset($this->filter['group_medic'][$rec_group['pkey']])) $arr[]=$rec_group['obj_name'] ;
       if (_sizeof($arr)) $info['Группы']=implode(', ',$arr) ;
   }
   if ($this->filter['violation_time'])             $info['Разрыв между заездом и выездом не менее']=$this->filter['violation_time']  ;


   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 prepare_data($options=array())
    {
//        $options['debug']=1 ;
        $usl=array() ;
        $usl[]='t1.model>0' ;
        $usl[]='t1.dopusk=1';
        $usl[]='t1.tk!=2';
        if ($this->filter['name'])              $usl[]='(t1.personal_name like "'.$this->filter['name'].'%")' ;
        if ($this->filter['group_id'])   $usl[]='t1.group_id in ('.ACCOUNTS()->tree[$this->filter['group_id']]->get_list_child().')' ;
        if ($this->filter['org_ids'])          $usl[]='personal_parent2 in ('.implode(',',array_keys($this->filter['org_ids'])).')' ;
        if ($this->filter['otdel_ids'])        $usl[]='personal_parent3 in ('.implode(',',array_keys($this->filter['otdel_ids'])).')' ;

        $usl[]='t1.c_data>='.$this->period_start.' and t1.c_data<='.$this->period_end ;

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

        $recs=execSQL('select pkey,status,member_id,dopusk_time,tk,personal_age,personal_name,_otdel_name,_org_name,group_name,group_id
                        from '.ESMO()->view_mo_session.' t1
                        where '.$usl_res.'
                        '.$order.$limit,$options) ;

        if (_sizeof($recs)) foreach ($recs as $rec) {
            $day=(int) (($rec['dopusk_time']-$this->period_start)/(86400)); //86400=60*60*24

            $temp_array=[];
            $temp_array['time']=$rec['dopusk_time'];
            $temp_array['mo_id']=$rec['pkey'];

//            $this->arr_members_mo[$rec['member_id']][$day][$rec['tk']][]=$rec['dopusk_time'];
            $this->arr_members_mo[$rec['member_id']][$day][$rec['tk']][]=$temp_array;
            $this->arr_members[$rec['member_id']]=$rec['personal_name'];
            $this->arr_itog['itog'][$day][$rec['tk']]++;
            if ($rec['personal_age']>=55) $this->arr_members_age_group[$rec['member_id']]=1;
        }
        if (_sizeof($this->arr_members)) {
            asort($this->arr_members);
            $this->arr_members_group=execSQL('select o_id,count(pkey) as cnt from obj_site_link where p_clss=254 and o_clss=211 and o_id in ('.implode(',',array_keys($this->arr_members)).') group by o_id',$options);
        }
    }

    function HTML_report_body($options=array())
    {

//        damp_array($this->days_array,1,-1);
        $time_violation_departure_style='position: relative; background-color: #f59782;';
        $time_violation_arrival_style='background-color: #f59782;';
        $day_off_tr_style='background-color: #afc6c2';
        $day_off_td_style='background-color: #d3dfdd';
        $now_day_style='background-color: #548C86';
        $cnt_gr_cv=0; $cnt_gr_other=0; $cnt_gr_age=0;
        $gr_cv_itog_link_array=[]; $gr_other_itog_link_array=[]; $gr_age_itog_link_array=[];
        $age_ids_file_name=''; $cv_ids_file_name=''; $other_ids_file_name='';
        $this->prepare_data($options);
        $i=1;
        ?>
            <table class="basic fz_small full auto">
                <tr>
                    <th rowspan="2">№</th>
                    <th rowspan="2">ФИО</th>
                    <th rowspan="2">МО за период В/З</th>
                    <?
                        foreach ($this->days_array as $key_date=>$value_date) {
                            ?><th colspan="2" <?if ($value_date['now_date']) echo 'style="'.$now_day_style.'"'; elseif ($value_date['day_off']) echo 'style="'.$day_off_tr_style.'"'?>><?echo $value_date['number']?></th><?
                        }
                    ?>
                </tr>
                <tr>
                    <?
                        foreach ($this->days_array as $value_date) {
                            ?>
                            <th <?if ($value_date['day_off']) echo 'style="'.$day_off_tr_style.'"'?>>В</th>
                            <th <?if ($value_date['day_off']) echo 'style="'.$day_off_tr_style.'"'?>>З</th>
                            <?
                        }
                    ?>
                </tr>
        <?
        if (_sizeof($this->arr_members)) foreach ($this->arr_members as $key=>$rec) { //поиск групп по болезни
            if ($this->arr_members_group[$key]) {
                $is_gr=true;
                $arr_disease=execSQL('select t1._id,t1.gr_sss from view_IL_group_medic t1, obj_site_link t2 where t2.o_id='.$key.' and t1.pkey=t2.p_id');
                $gr_cv=false; $gr_age=false; $gr_other=false;
                if (_sizeof($arr_disease)) foreach ($arr_disease as $disease) {
                    if ($disease['gr_sss']) $gr_cv=true; //
                    else $gr_other=true; //другое
//                    if ($disease['_id']==16) $gr_age=true; //возраст //убрано из списка болезней
                }
//                $color='';
                //перебор групп для подсчета и отображения в отчете
                if ($gr_cv) {  //если у сотрудника есть группы риска по АГ, то отображаем и считаем для него группу риска с заболеваниями ССС
                    $style_color='style="background-color: #CF5C85"';
                    $gr_cv_itog_link_array[]=$key;
                    $cnt_gr_cv++;
                } elseif ($gr_other){ //если у сотрудника нет группы риска по АГ, но есть группа риска с прочими заболеваниями, то отображаем и считаем для него группу риска с прочими заболеваниями
                    $style_color='style="background-color: #94A676"';
                    $gr_other_itog_link_array[]=$key;
                    $cnt_gr_other++;
                    //закоменченно т.к. в списке болезней нет болезни по возрасту
//                } elseif ($gr_age) { //если у сотрудника нет группы риска по АГ и прочих заболеваний, то считаем и отображаем для него группу риска по возрасту
//                    $style_color='style="background-color: #C8E203"';
//                    $gr_age_itog_link_array[]=$key;
//                    $cnt_gr_age++;
                }
            } else {
                //группа риска по возрасту
                if ($this->arr_members_age_group[$key]) {
                    $is_gr=true;
                    $style_color='style="background-color: #C8E203"';
                    $gr_age_itog_link_array[]=$key;
                    $cnt_gr_age++;
                } else {
                    $is_gr=false;
                    $style_color='';
                }
            }
            $driver_options=[];
            $driver_options['time_violation_departure_style']=$time_violation_departure_style;
            $driver_options['time_violation_arrival_style']=$time_violation_arrival_style;
            $driver_options['day_off_td_style']=$day_off_td_style;
            $driver_options['is_gr']=$is_gr;
            $driver_options['style_color']=$style_color;

            $this->print_drivers_table($key,$rec,$i,$driver_options);
            $i++;
        }
        if (_sizeof($this->arr_itog)){
            ?>
                <tr>
                    <td colspan="3">На линию</td>
                    <?
                    foreach ($this->days_array as $key_date=>$value_date) {
                        ?>
                        <td <?if ($value_date['day_off']) echo 'style="'.$day_off_td_style.'"'?>><?echo $this->arr_itog['itog'][$key_date][0]?></td>
                        <td <?if ($value_date['day_off']) echo 'style="'.$day_off_td_style.'"'?>></td>
                        <?
                    }
                    ?>
                </tr>
                <tr>
                    <td colspan="3">С линии</td>
                    <?
                    foreach ($this->days_array as $key_date=>$value_date) {
                        ?>
                        <td <?if ($value_date['day_off']) echo 'style="'.$day_off_td_style.'"'?>></td>
                        <td <?if ($value_date['day_off']) echo 'style="'.$day_off_td_style.'"'?>><?echo $this->arr_itog['itog'][$key_date][1]?></td>
                        <?
                    }
                    ?>
                </tr>
                <tr>
                    <td colspan="3">Ремонт</td>
                    <?
                    foreach ($this->days_array as $key_date=>$value_date) {
                        ?>
                        <td <?if ($value_date['day_off']) echo 'style="'.$day_off_td_style.'"'?>></td>
                        <td <?if ($value_date['day_off']) echo 'style="'.$day_off_td_style.'"'?>></td>
                        <?
                    }
                    ?>
                </tr>
                <tr>
                    <td colspan="3">Группа риска</td>
                    <?
                    foreach ($this->days_array as $key_date=>$value_date) {
                        ?>
                        <td <?if ($value_date['day_off']) echo 'style="'.$day_off_td_style.'"'?>></td>
                        <td <?if ($value_date['day_off']) echo 'style="'.$day_off_td_style.'"'?>></td>
                        <?
                    }
                    ?>
                </tr>
                <tr>
                    <td colspan="3">на линию</td>
                    <?
                    foreach ($this->days_array as $key_date=>$value_date) {
                        if (_sizeof($this->arr_itog['gr_itog'][$key_date][0]['mo_ids']))
                            $gr_itog_text='<a href="/window/reports/report_mo_sess/[mo_ids=('.implode(';',$this->arr_itog['gr_itog'][$key_date][0]['mo_ids']).')]/" class="new_window" target="_blank" title="win_second">'.$this->arr_itog['gr_itog'][$key_date][0]['cnt'].'</a>';
                        else
                            $gr_itog_text=$this->arr_itog['gr_itog'][$key_date][0]['cnt'];
                        ?>
                        <td <?if ($value_date['day_off']) echo 'style="'.$day_off_td_style.'"'?>><?echo $gr_itog_text?></td>
                        <td <?if ($value_date['day_off']) echo 'style="'.$day_off_td_style.'"'?>></td>
                        <?
                    }
                    ?>
                </tr>
                <tr>
                    <td colspan="3">с линии</td>
                    <?
                    foreach ($this->days_array as $key_date=>$value_date) {
                        if (_sizeof($this->arr_itog['gr_itog'][$key_date][1]['mo_ids']))
                            $gr_itog_text='<a href="/window/reports/report_mo_sess/[mo_ids=('.implode(';',$this->arr_itog['gr_itog'][$key_date][1]['mo_ids']).')]/" class="new_window" target="_blank" title="win_second">'.$this->arr_itog['gr_itog'][$key_date][1]['cnt'].'</a>';
                        else
                            $gr_itog_text=$this->arr_itog['gr_itog'][$key_date][1]['cnt'];
                        ?>
                        <td <?if ($value_date['day_off']) echo 'style="'.$day_off_td_style.'"'?>></td>
                        <td <?if ($value_date['day_off']) echo 'style="'.$day_off_td_style.'"'?>><?echo $gr_itog_text?></td>
                        <?
                    }
                    ?>
                </tr>
            <?
        }
        ?>
            </table>
            <br>
        <?
            $itog_on=0; $itog_from=0; $gr_itog_on=0; $gr_itog_from=0;
            if (_sizeof($this->arr_itog['itog'])) foreach ($this->arr_itog['itog'] as $value){
                $itog_on+=$value[0];
                $itog_from+=$value[1];
            }
            $gr_itog_on_link=''; $gr_itog_from_link='';
            if (_sizeof($this->arr_itog['gr_itog'])) foreach ($this->arr_itog['gr_itog'] as $value){
                if (_sizeof($value[0]['mo_ids'])) {
                    if ($gr_itog_on_link) $gr_itog_on_link.=';'.implode(';',$value[0]['mo_ids']);
                        else $gr_itog_on_link=implode(';',$value[0]['mo_ids']);
                }
                if (_sizeof($value[1]['mo_ids'])) {
                    if ($gr_itog_from_link) $gr_itog_from_link.=';'.implode(';',$value[1]['mo_ids']);
                        else $gr_itog_from_link=implode(';',$value[1]['mo_ids']);
                }
                $gr_itog_on+=$value[0]['cnt'];
                $gr_itog_from+=$value[1]['cnt'];
            }
            /*if ($gr_itog_on_link) $gr_itog_on_text='<a href="/window/reports/report_mo_sess/[mo_ids=('.$gr_itog_on_link.')]/" class="new_window" target="_blank" title="win_second">'.$gr_itog_on.'</a>';
                else*/ $gr_itog_on_text=$gr_itog_on;
            /*if ($gr_itog_from_link) $gr_itog_from_text='<a href="/window/reports/report_mo_sess/[mo_ids=('.$gr_itog_from_link.')]/" class="new_window" target="_blank" title="win_second">'.$gr_itog_from.'</a>';
                else*/ $gr_itog_from_text=$gr_itog_from;


        $ids_file_name = ENGINE()->generate_UID();
        if (_sizeof($gr_age_itog_link_array)) {
            $gr_age_itog_link_text  = implode(',',$gr_age_itog_link_array);
            $age_ids_file_name = $ids_file_name.'_age.txt';
            file_put_contents(_TEMP_DIR.$age_ids_file_name,$gr_age_itog_link_text);
        }

        if (_sizeof($gr_cv_itog_link_array)) {
            $gr_cv_itog_link_text  = implode(',',$gr_cv_itog_link_array);
            $cv_ids_file_name = $ids_file_name.'_cv.txt';
            file_put_contents(_TEMP_DIR.$cv_ids_file_name,$gr_cv_itog_link_text);
        }

        if (_sizeof($gr_other_itog_link_array)) {
            $gr_other_itog_link_text  = implode(',',$gr_other_itog_link_array);
            $other_ids_file_name = $ids_file_name.'_other.txt';
            file_put_contents(_TEMP_DIR.$other_ids_file_name,$gr_other_itog_link_text);
        }

            ?>
            <table class="bottom_info">
                <tr>
                    <td colspan="2" class="col2">Всего осмотров</td>
                    <td class="bottom_border col2" colspan="2"><?echo ($itog_on+$itog_from)?></td>
                    <td colspan="5"></td>
                </tr>
                <tr>
                    <td class="col1">Из них</td>
                    <td class="col1">на линию</td>
                    <td class="bottom_border col2" colspan="2"><?echo $itog_on?></td>
                    <td></td>
                    <td colspan="2">в т.ч. на линию из "группы риска"</td>
                    <td></td>
                    <td class="bottom_border"><?echo $gr_itog_on_text?></td>
                </tr>
                <tr>
                    <td class="col1"></td>
                    <td class="col1">с линии</td>
                    <td class="bottom_border" colspan="2"><?echo $itog_from?></td>
                    <td></td>
                    <td colspan="2">в т.ч. с линии из "группы риска"</td>
                    <td></td>
                    <td class="bottom_border"><?echo $gr_itog_from_text?></td>
                </tr>
                <tr>
                    <td class="col1"></td>
                    <td class="col1">ремонт</td>
                    <td class="bottom_border" colspan="2"></td>
                    <td colspan="2"></td>
                    <td>Водители 55 лет и старше</td>
                    <td></td>
                    <td class="gr_age cnt_gr">
                        <?
                        if ($age_ids_file_name) {
                            ?>
                            <a href="<?echo '/window/personal/[ids_file='.$age_ids_file_name.']/'?>" class="new_window" target="_blank" title="win_second"><?echo $cnt_gr_age?></a>
                            <?
                        }
                        ?>
                    </td>
                </tr>
                <tr>
                    <td class="col1"></td>
                    <td class="col1">не допуск</td>
                    <td class="bottom_border" colspan="2"></td>
                    <td colspan="2"></td>
                    <td>Гр. риска с заболев. ССС</td>
                    <td></td>
                    <td class="gr_cv cnt_gr">
                        <?
                        if ($cv_ids_file_name) {
                            ?>
                            <a href="<?echo '/window/personal/[ids_file='.$cv_ids_file_name.']/'?>" class="new_window" target="_blank" title="win_second"><?echo $cnt_gr_cv?></a>
                            <?
                        }
                        ?>
                    </td>
                </tr>
                <tr>
                    <td colspan="3"  class="col3">Заведующий здравпунктом</td>
                    <td class="bottom_border col1"></td>
                    <td class="col1"></td>
                    <td class="col1"></td>
                    <td>Гр. риска с прочими забол.</td>
                    <td></td>
                    <td class="col1 gr_other cnt_gr">
                        <?
                        if ($other_ids_file_name) {
                            ?>
                            <a href="<?echo '/window/personal/[ids_file='.$other_ids_file_name.']/'?>" class="new_window" target="_blank" title="win_second"><?echo $cnt_gr_other?></a>
                            <?
                        }
                        ?>
                    </td>
                </tr>
                <tr>
                    <td class="col1"></td>
                    <td class="col1"></td>
                    <td class="col2" colspan="2"></td>
                    <td colspan="2"></td>
                    <td>Нарушений времени труда и отдыха</td>
                    <td></td>
                    <td class="bottom_border">
                        <?
                        if (_sizeof($this->arr_itog['violation']['keys'])){
                            ?>
                            <a href="<?echo '/window/personal/[ids=('.implode(';',$this->arr_itog['violation']['keys']).')]/'?>" class="new_window" target="_blank" title="win_second"><?echo $this->arr_itog['violation']['cnt']?></a>
                            <?
                        } else echo $this->arr_itog['violation']['cnt'];
                        ?>
                    </td>
                </tr>
            </table>
        <style type="text/css">
            table.basic td {border-color: #aaaaaa;}
            table.bottom_info {width:800px;}
            table.bottom_info tr td.col3 {width:30%}
            table.bottom_info tr td.col2 {width:20%}
            table.bottom_info tr td.col1 {width:10%}
            table.bottom_info tr td.cnt_gr {text-align: center;}
            table.bottom_info tr td.gr_cv {background-color: #CF5C85}
            table.bottom_info tr td.gr_age {background-color: #C8E203}
            table.bottom_info tr td.gr_other {background-color: #94A676}
            table.bottom_info tr td.bottom_border{border-bottom: 1px solid black; text-align: center; }
        </style>
        <?

    }

    function print_drivers_table($key,$rec,$i,$options){
        $time_violation=false;
        if (!$this->filter['no_display_table']) {
        ?>
        <tr class=item>
            <td rowspan="2"><?echo $i;?></td>
            <td rowspan="2" class="left" <?echo $options['style_color']?>><a href="/window/personal/person/<?echo $key?>/" class="new_window" target="_blank" title="win_second"><?echo $rec?></a></td>
            <?
        }
            ob_start();
            $member_mo_cnt_in=0; $member_mo_cnt_out=0;
            foreach ($this->days_array as $key_date=>$value_date) {
                $td_value='';
                if ($this->arr_members_mo[$key][$key_date][0]){
                    foreach ($this->arr_members_mo[$key][$key_date][0] as $id=>$time){
                        $member_mo_cnt_in++;
                        if ($options['is_gr']) {
                            $this->arr_itog['gr_itog'][$key_date][0]['cnt']++;
                            $this->arr_itog['gr_itog'][$key_date][0]['mo_ids'][]=$time['mo_id'];
                        }
//                            $td_value.=date('H:i',$time['time']).'<br>';
                        $td_value.='<a href="/window/reports/report_mo_sess/[mo_ids=('.$time['mo_id'].')]/" class="new_window" target="_blank" title="win_second">'.date('H:i',$time['time']).'</a><br>';
                    }
                }
                //
                ?>
                <td rowspan="2" <?if ($time_violation) {echo 'style="'.$options['time_violation_departure_style'].'"'; $time_violation=false; $time_violation_diff=true;} elseif ($value_date['day_off']) echo 'style="'.$options['day_off_td_style'].'"'?>>
                    <?
                    echo $td_value;
                    ?>
                    <?if ($time_violation_diff) {?><div style="position: absolute; left:-16px; top:-2px;"><?echo date("H:i", mktime(0, 0, $time_violation_value))?></div><? $time_violation_diff=false;}?>
                </td>
                <?
                $td_value='';
                if ($this->arr_members_mo[$key][$key_date][1]){
                    foreach ($this->arr_members_mo[$key][$key_date][1] as $id=>$time){
                        $member_mo_cnt_out++;
                        if ($options['is_gr']) {
                            $this->arr_itog['gr_itog'][$key_date][1]['cnt']++;
                            $this->arr_itog['gr_itog'][$key_date][1]['mo_ids'][]=$time['mo_id'];
                        }
                        if (_sizeof($this->arr_members_mo[$key][$key_date][1])==$id+1) { //если текущее значение в столбце заезда последнее
                            if (_sizeof($this->arr_members_mo[$key][$key_date+1][0])) { //то если есть запись в следующем дне на въезд
                                $time_violation_value=$this->arr_members_mo[$key][$key_date+1][0][0]['time']-$time['time'];
                                if ($time_violation_value<(60*60*$this->filter['violation_time'])) {//если разница между этим временем меньше заданного
                                    $this->arr_itog['violation']['cnt']++;
                                    $this->arr_itog['violation']['keys'][]=$key;
                                    $time_violation=true; //запоминаем нарушение режима времени
                                } else {
                                    $time_violation_value=0;
                                }
                            }
                        }
                        $td_value.='<a href="/window/reports/report_mo_sess/[mo_ids=('.$time['mo_id'].')]/" class="new_window" target="_blank" title="win_second">'.date('H:i',$time['time']).'</a><br>';
                    }
                }
                ?>
                <td rowspan="2" <?if ($time_violation) echo 'style="'.$options['time_violation_arrival_style'].'"'; elseif ($value_date['day_off']) echo 'style="'.$options['day_off_td_style'].'"'?>>
                    <?
                    echo $td_value;
                    ?>
                </td>
                <?
            }
            $text=ob_get_clean();
            if (!$this->filter['no_display_table']) {?><td><?echo $member_mo_cnt_in?></td><?}
            if (!$this->filter['no_display_table']) echo $text;
            if (!$this->filter['no_display_table']) {
            ?>
        </tr>
        <tr>
            <td><?echo $member_mo_cnt_out?></td>
        </tr>
        <?
        }
    }



// шаблон - вывод ссылками без разделитея
//  function print_template_HTML($list_recs,$options=array())
//  {
//
//  }

//    function print_template_CSV($list_recs,$options=array())
//    { $i=0 ;
//        $arr_atp_names=execSQL_row('select pkey,obj_name from obj_site_account where clss=206') ;
//       if (_sizeof($list_recs)) foreach($list_recs as $rec)
//       {   $data=array() ;
//      	   $data['№']=$i+1 ;
//           $data['Пропуск']=$rec['propusk']  ;
//           //$data['Табельный номер']=$rec['tabnumber']  ;
//      	   $data['ФИО']=$rec['obj_name']  ;
//           $data['UID']=$rec['uid']  ;
//           $data['Дата рождения']=$rec['dr']  ;
//           $data['Возраст']=$rec['age']  ;
//      	   $data['Организация']=$rec['_org_name'] ;
//      	   $data['Подразделение']=$rec['_otdel_name'] ;
//           $data['Должность']=_IL('IL_works')->recs[$rec['working']]['obj_name'] ;
//           $data['Группа']=(_sizeof($rec['_groups']))? implode(', ',$rec['_groups']):'-' ;
//           $data['Статус направления']=$_SESSION['ARR_mess_status'][$rec['mess_status']] ;
//           $data['Место выдачи']=$arr_atp_names[$rec['mess_atp_id']] ;
//           $data['Дата выдачи']=($rec['mess_c_data'])? date('d.m.Y H:i',$rec['mess_c_data']):'' ;
//           $data['Дата блокировки']=($rec['mess_max_data'])? date('d.m.Y H:i',$rec['mess_max_data']):'' ;
//           $data['Дней до блокировки']=($rec['mess_status']!=4 and $rec['mess_max_data'])? (($rec['mess_max_data']>time())? floor(($rec['mess_max_data']-time())/(60*60*24)):''):'';
//           $data['Дата сдачи']=($rec['mess_status']==4 and $rec['mess_close_data'])? date('d.m.Y',$rec['mess_close_data']):'' ;
//           $data['Блокировка МО']=($rec['mess_status']!=4 and $rec['mess_close_data'] and $rec['mess_max_data']<time() and $rec['mess_block_mo']==1)? 'Да':'' ;
//           // вносим данные в csv
//           $this->put_data_to_CSV($data,$i) ;
//      	   $i++ ;
//  	   }
//
//
//   }



}

?>
