<?php
include_once(_DIR_TO_CLASS."/c_page.php");
class c_page_cab_esmo_master extends c_page
{
  public $h1='Рабочее место руководителя' ;
  public $use_fusioncharts=1 ;
  public $group_id ; // группа, на котором работает мастер
  public $otdel_ids=array() ; // отделы, в которых мониторятся сотрудники
  public $smena_interval=array() ;
  //public $otdel_ids=array(7130) ; // отделы, в которых мониторятся сотрудники
  //public $otdel_ids=array() ; // отделы, в которых мониторятся сотрудники

  function __construct()
  { parent::__construct();
    $this->group_id=MEMBER()->cur_group_id ;
  }

    function second_menu_config()
  { $this->second_menu['/cab/esmo_master/']=array('title'=>'Статистика') ;
    $this->second_menu['/cab/esmo_master/report_mo/']=array('title'=>'Отчет') ;
    $this->second_menu['/cab/esmo_master/personal/']=array('title'=>'Сотрудники') ;
    $this->second_menu['/cab/esmo_master/messages/']=array('title'=>'Сообщения') ;
    if ($GLOBALS['_SETTING']['modules']['kt']) $this->second_menu['/cab/esmo_master/kt/']=array('title'=>'Контроль трезвости') ;
    if ($GLOBALS['_SETTING']['modules']['quiz']) $this->second_menu['/cab/esmo_master/quiz/']=array('title'=>'Контроль знаний') ;
    if ($GLOBALS['LS_esmo_PMO_event']) $this->second_menu['/cab/esmo_master/pmo/']=array('title'=>'ПМО') ;
    if ($GLOBALS['LS_esmo_OPO_event']) $this->second_menu['/cab/esmo_master/opo/']=array('title'=>'ОПО') ;
    //$this->second_menu['/cab/esmo_master/setting/']=array('title'=>'Настройка подразделений') ;
    //$this->second_menu['/cab/esmo_master/setting_smena/']=array('title'=>'Настройка смен') ;
    //$this->second_menu['/cab/esmo_master/health/']=array('title'=>'Состояние здоровья') ;
    //$this->second_menu['/cab/esmo_master/stats/health/[org_ids=(7106)]/']=array('title'=>'Состояние здоровья') ;

      list($cur_smena_indx,$prev_smena_indx)=$this->get_smena_indx() ; //
      $this->smena_interval['cur']=$this->get_smena_time($cur_smena_indx) ;
      $this->smena_interval['prev']=$this->get_smena_time($prev_smena_indx) ;

      ///class_v2.15/ext/esmo_master/c_esmo_master_setting_smena.php(53):Missing argument 1 for c_page_cab_esmo_master_setting_smena::get_smena_indx(), called in /class_v2.15/ext/esmo_master/c_esmo_master.php on line 23 and define
      //$this->smena_interval['prev']['from']=mktime(0,0,0,6,1,2016);
      //$this->smena_interval['prev']['to']=mktime(0,0,0,  7,1,2016)-1;
      //$this->smena_interval['cur']['from']=mktime(0,0,0 ,7,1,2016);
      //$this->smena_interval['cur']['to']=mktime(0,0,0 ,8,1,2016)-1;
      //damp_array($this->smena_interval) ;
  }

 function block_main()
 { $this->page_title() ;
   $this->panel_source_info() ;

   ?><div class="clear"></div><br><h2>Статистика проведения медицинских осмотров:</h2><?
   //include_once('panel_stats.php');
   $this->panel_stats() ;
   if ($this->filter['type']=='mo') $this->panel_mo_view() ;

   if ($GLOBALS['_SETTING']['modules']['kt']) {
   ?><div class="clear"></div><br><h2>Статистика проведения контроля трезвости:</h2><?
   //include_once('panel_stats.php');
   $this->panel_stats_kt() ;
   if ($this->filter['type']=='kt') $this->panel_kt_view() ;
   }

   //$this->panel_stats_graf() ;
   /*?><br><h2>График работы ЭСМО</h2><?
   include_once('panel_stats.php');
   $this->panel_stats_graf() ;
   ?><br><h2>Интенсивность проведения МО на объектах</h2><?
   */

 }

 function panel_source_info()
 {  ?><table class="master_table_info" style="width:100%;table-layout:fixed;">
       <tr><td><h2>Место контроля:</h2></td>
           <td><h2>Контролируемые подразделения:</h2></td>
       </tr>
       <tr><td style="font-size:52px;line-height:1em;color:#0056aa;margin-top:30px;"><? echo ACCOUNTS()->get_member_name_by_id($this->group_id)?></td>
           <td style="font-size:16px;;color:#0056aa;text-align:left;"><?PERSONALS_FILTER()->get_personals_filter_info_to_item(MEMBER()->info['_reffer'],'ВСЕ') ; ?></tr>
      </table>
      <style type="text/css">
         table.master_table_info{width:100%;table-layout:fixed;margin-bottom:30px;}
         table.master_table_info td:first-child{width:400px;}
         table.master_table_info td{width:auto;}
      </style>
    <?
 }

function get_full_zone_path($zone_id,$to_level=1)
{
  if (is_object(PERSONAL()->tree[$zone_id])) return(implode(' / ',PERSONAL()->tree[$zone_id]->get_arr_parent_name(array('to_level'=>$to_level)))) ;
  else return('') ;
}

 function panel_graf_itog6()
 {
     include_once(_DIR_EXT.'/aspmo_reports/report_itog6.php') ;
     $report_obj=new report_itog6() ;
     $report_obj->filter['org_id']=7106 ;
     $report_obj->filter['time_from']=1472677200 ;
     $report_obj->filter['time_to']=1475269199 ;
     $report_obj->view_table=0 ;
     $report_obj->view_as_HTML() ;

 }

/*public $arr_smena=array(array('from_h'=>16,'from_m'=>0,'to_h'=>22, 'to_m'=>59,'day'=>-1, 'name'=>3),
                         array('from_h'=>23,'from_m'=>0,'to_h'=>23, 'to_m'=>59,'day'=>-1,'name'=>1),
                         array('from_h'=>0, 'from_m'=>0,'to_h'=>5,  'to_m'=>59,'day'=>0, 'name'=>1),
                         array('from_h'=>6, 'from_m'=>0,'to_h'=>15, 'to_m'=>59,'day'=>0, 'name'=>2),
                         array('from_h'=>16,'from_m'=>0,'to_h'=>22, 'to_m'=>59,'day'=>0, 'name'=>3),
                         array('from_h'=>23,'from_m'=>0,'to_h'=>23, 'to_m'=>59,'day'=>0, 'name'=>1),
                         array('from_h'=>0, 'from_m'=>0,'to_h'=>7,  'to_m'=>59,'day'=>+1, 'name'=>1),
                         array('from_h'=>8, 'from_m'=>0,'to_h'=>15, 'to_m'=>59,'day'=>+1, 'name'=>2),

            ) ;      */

 /*public $arr_smena2=array(array('from_h'=>0,'from_m'=>0,'to_h'=>23, 'to_m'=>59,'day'=>-1, 'name'=>2),
                         array('from_h'=>0,'from_m'=>0,'to_h'=>23, 'to_m'=>59,'day'=>0,'name'=>1),
                         array('from_h'=>0, 'from_m'=>0,'to_h'=>23,  'to_m'=>59,'day'=>+1, 'name'=>2)

            ) ;
 */
 public $arr_smena=array(array('from_h'=>0,'from_m'=>0,'to_h'=>23, 'to_m'=>59,'day'=>-1,'name'=>2),
                         array('from_h'=>0, 'from_m'=>0,'to_h'=>23,  'to_m'=>59,'day'=>0, 'name'=>1)

            ) ;


// внимание, функция работает только с текщим временем
// подставить прошлое время не получися - неверно вычиляются smena_indx
function get_smena_indx($time=0)
{   $now=getdate() ;
    if (!$time) $time=time() ;
    $smena_indx=0 ;
    foreach($this->arr_smena as $indx=>$rec_smena)
    { $time_from=mktime($rec_smena['from_h'],$rec_smena['from_m'],0,$now['mon'],$now['mday']+$rec_smena['day'],$now['year']);
      $time_to=mktime($rec_smena['to_h'],$rec_smena['to_m'],59,$now['mon'],$now['mday']+$rec_smena['day'],$now['year']);
      //echo $indx.': '.date('d.m.Y H:i:s',$time_from).' - '.date('d.m.Y H:i:s',$time_to).'<br>' ;
      if ($time>=$time_from and $time<=$time_to)
      { $smena_indx=$indx ;
        //echo '<strong>$smena_indx='.$smena_indx.'</strong><br>' ;
      }
    }
    //$prev_smena_indx=($smena_indx)? $smena_indx-1:_sizeof($this->arr_smena)-1 ;
    $prev_smena_indx=$smena_indx-1 ;
    if ($this->arr_smena[$smena_indx]['name']==$this->arr_smena[$prev_smena_indx]['name']) $prev_smena_indx-- ;
    return(array($smena_indx,$prev_smena_indx)) ;
}

function get_smena_time($indx)
{ $indx1=$indx ; $indx2=$indx ;
  if ($this->arr_smena[$indx]['name']==$this->arr_smena[$indx-1]['name']) {$indx1=$indx-1 ; $indx2=$indx ; }
  if ($this->arr_smena[$indx]['name']==$this->arr_smena[$indx+1]['name']) {$indx1=$indx ; $indx2=$indx+1 ; }
  $now=getdate() ;
  $rec_smena=$this->arr_smena[$indx1] ;
  $time_from=mktime($rec_smena['from_h'],$rec_smena['from_m'],0,$now['mon'],$now['mday']+$rec_smena['day'],$now['year']);
  $rec_smena=$this->arr_smena[$indx2] ;
  $time_to=mktime($rec_smena['to_h'],$rec_smena['to_m'],59,$now['mon'],$now['mday']+$rec_smena['day'],$now['year']);
  return(array('from'=>$time_from,'to'=>$time_to)) ;
}

function get_stats_to_smena($smena_from,$smena_to)
{  $stats['time_from']=$smena_from ;
   $stats['time_to']=$smena_to ;
   $_usl=array() ;
   $_usl[]='t1.c_data>='.$smena_from ;
   $_usl[]='t1.c_data<='.$smena_to ;
   $_usl[]='not t2.pkey is null' ;

   // применяем фильтры по выборке персонала к вьюверу на МО
   //if (MEMBER()->personal_viewer_name) $_usl['account_personal_filter']='personal_id in (select pkey from '.MEMBER()->personal_viewer_name.')' ;
    $view_personals=(MEMBER()->personal_viewer_name)?:'view_personals_all' ;

   //damp_array($_usl) ;

   $usl_based=implode(' and ',$_usl) ;
   $stats['dopusk']=execSQL_row('select t1.dopusk,count(t1.pkey) 
                                 from obj_site_mo_session t1
                                 left join '.$view_personals.' t2 on t2.pkey=t1.member_id
                                 where  '.$usl_based.' and t1.member_id>0 and t1.model>0 and t1.dopusk in (1,2)   
                                 group by t1.dopusk 
                                 order by t1.dopusk') ;
   if ($GLOBALS['LS_person_schedule_view'])
   {
       $stats['schedule']['in']=execSQL_row('select t1.dopusk,count(t1.pkey) 
                                             from obj_site_mo_session t1
                                             left join '.$view_personals.' t2 on t2.pkey=t1.member_id
                                             where '.$usl_based.' and t1.member_id>0 and t1.model>0 and t1.dopusk in (1,2) and t1.mo_schedule=1 
                                             group by t1.dopusk 
                                             order by t1.dopusk') ;
       $stats['schedule']['out']=execSQL_row('select t1.dopusk,count(t1.pkey) 
                                             from obj_site_mo_session t1
                                             left join '.$view_personals.' t2 on t2.pkey=t1.member_id
                                             where '.$usl_based.' and t1.member_id>0 and t1.model>0 and t1.dopusk in (1,2) and t1.mo_schedule=2 
                                             group by t1.dopusk 
                                             order by t1.dopusk') ;
   }
   // получаем МО запрет допуска
   $recs_mo=execSQL('select t1.pkey,t1.res_a 
                     from obj_site_mo_session t1
                     left join '.$view_personals.' t2 on t2.pkey=t1.member_id
                     where '.$usl_based.' and t1.member_id>0 and t1.model>0 and t1.dopusk=2') ;
   if (_sizeof($recs_mo)) foreach($recs_mo as $rec_mo)
   { if ($rec_mo['res_a']==2) $stats['denited']['alko']++ ;
     else  $stats['denited']['other']++ ;
   }

   // срок действия МО = срок действия допуска. Если человек за это время не прошел на повторное МО, он считается уклонистом
   // если он пришел на повторное МО спустя 2 часа - у него будет новый сеанс МО
   $recs_mo=execSQL('select t1.pkey,t1.res_a  
                     from obj_site_mo_session t1
                     left join '.$view_personals.' t2 on t2.pkey=t1.member_id
                     where '.$usl_based.' and t1.reason!="cancelTimeout" and t1.member_id>0 and t1.status in (2,3) and t1.dopusk=3 and t1.model>0') ;
   //$recs_mo=execSQL('select * from view_mo_session where '.$usl_based.' and member_id>0 and status in (2,3) and dopusk=0 and model=0 limit 10',2) ;
   if (_sizeof($recs_mo)) foreach($recs_mo as $rec_mo)
    { if ($rec_mo['res_a']==2)
      { $stats['uklon']['alko']++ ;
        //$recs[]=$rec_mo ;

      }
      else  $stats['uklon']['other']++ ;
    }
   //print_2x_arr($recs) ;
   return($stats) ;
}

function get_stats_kt_smena($smena_from,$smena_to)
{  $stats['time_from']=$smena_from ;
   $stats['time_to']=$smena_to ;
   $_usl=array() ;
   $_usl[]='t1.c_data>='.$smena_from ;
   $_usl[]='t1.c_data<='.$smena_to ;
   $_usl[]='not t2.pkey is null' ;

   // применяем фильтры по выборке персонала к вьюверу на МО
   //if (MEMBER()->personal_viewer_name) $_usl['account_personal_filter']='personal_id in (select pkey from '.MEMBER()->personal_viewer_name.')' ;
   $view_personals=(MEMBER()->personal_viewer_name)?:'view_personals_all' ;

   //damp_array($_usl) ;

   $usl_based=implode(' and ',$_usl) ;
   $stats['dopusk']=execSQL_row('select dopusk,count(pkey) 
                                 from obj_site_kt_session 
                                 left join '.$view_personals.' t2 on t2.pkey=t1.member_id
                                 where t1.clss=240 and '.$usl_based.' and t1.member_id>0 
                                 group by t1.dopusk 
                                 order by t1.dopusk') ;
   // получаем МО запрет допуска
   $recs_mo=execSQL('select t1.pkey,t1.res_a 
                     from view_kt_session 
                     left join '.$view_personals.' t2 on t2.pkey=t1.member_id
                     where t1.clss=240 and '.$usl_based.' and t1.member_id>0 and t1.dopusk=2') ;
   if (_sizeof($recs_mo)) foreach($recs_mo as $rec_mo)
   { if ($rec_mo['res_a']==2) $stats['denited']['alko']++ ;
     else  $stats['denited']['other']++ ;
   }

   //print_2x_arr($recs) ;
   return($stats) ;
}

function panel_stats()
 { //$now=getdate() ;
   //$start_day=mktime(0,0,0,$now['mon'],$now['mday'],$now['year']);
   //if (!MEMBER()->use_auch_as_smena) $options['from_time']=mktime($now['hours']-12,$now['minutes'],0,$now['mon'],$now['mday'],$now['year']);
   //print_2x_arr($this->arr_smena) ;
   //$time=time() ;
   $time=time() ;

//'/'''''   echo date('d.m.Y H:i:s',$time).'<br>' ;

   //$cur_smena_to=time();

   //echo '$smena_indx='.$cur_smena_indx.'<br>' ;
   //echo '$prev_smena_indx='.$prev_smena_indx.'<br>' ;
   //echo 'cur_smena: '.date('d.m.Y H:i:s',$cur_smena_from).' - '.date('d.m.Y H:i:s',$cur_smena_to).'<br>' ;
   //echo 'prev_smena: '.date('d.m.Y H:i:s',$prev_smena_from).' - '.date('d.m.Y H:i:s',$prev_smena_to).'<br>' ;

   $stats['prev']=$this->get_stats_to_smena($this->smena_interval['prev']['from'],$this->smena_interval['prev']['to']) ;
   $stats['cur']=$this->get_stats_to_smena($this->smena_interval['cur']['from'],$this->smena_interval['cur']['to']) ;
   //damp_array($stats) ;

   ?><div id="panel_rmv_stats"><table class="basic full">
    <tr>
        <th rowspan="2">Смена</th><th rowspan="2">Допущено</th><th colspan="2">Не допущено</th><th colspan="2">Уклонились</th>
        <?if ($GLOBALS['LS_person_schedule_view']) {?><th colspan="2">График</th><?}?>
    </tr>
    <tr class="small"><th>Алкоголь</th><th>Другое</th><th>Алкоголь</th><th>Другое</th><?if ($GLOBALS['LS_person_schedule_view']) {?><th>В график</th><th>Вне графика</th><?}?></tr>
     <? if (_sizeof($stats)) foreach($stats as $type=>$rec_stat)
     { ?><tr><td class="left"><strong><?echo ($type=='prev')? 'Предыдущая смена':'Текущая смена'?></strong><br><span class="small">Время МО: <?echo date('d.m.Y H:i',$rec_stat['time_from']).' - '.date('d.m.Y H:i',$rec_stat['time_to'])?></span></td>
               <td><?echo ($rec_stat['dopusk'][1])? '<a href="/cab/esmo_master/[type=mo,dopusk=1,time_from='.$rec_stat['time_from'].',time_to='.$rec_stat['time_to'].']/">'.$rec_stat['dopusk'][1].'</a>':'-'?></td>
               <td><?echo ($rec_stat['denited']['alko'])? '<a href="/cab/esmo_master/[type=mo,dopusk=2,a,time_from='.$rec_stat['time_from'].',time_to='.$rec_stat['time_to'].']/"  class="red">'.$rec_stat['denited']['alko'].'</a>':'-'?></td>
               <td><?echo ($rec_stat['denited']['other'])? '<a href="/cab/esmo_master/[type=mo,dopusk=2,no_a,time_from='.$rec_stat['time_from'].',time_to='.$rec_stat['time_to'].']/"class="red">'.$rec_stat['denited']['other'].'</a>':'-'?></td>
               <td><?echo ($rec_stat['uklon']['alko'])? '<a href="/cab/esmo_master/[type=mo,uklon,a,time_from='.$rec_stat['time_from'].',time_to='.$rec_stat['time_to'].']/"  class="red">'.$rec_stat['uklon']['alko'].'</a>':'-'?></td>
               <td><?echo ($rec_stat['uklon']['other'])? '<a href="/cab/esmo_master/[type=mo,uklon,no_a,time_from='.$rec_stat['time_from'].',time_to='.$rec_stat['time_to'].']/"class="red">'.$rec_stat['uklon']['other'].'</a>':'-'?></td>
               <?if ($GLOBALS['LS_person_schedule_view']) {?>
                   <td><?echo ($rec_stat['schedule']['in'][1])? '<a href="/cab/esmo_master/[type=mo,dopusk=1,mo_schedule=2,time_from='.$rec_stat['time_from'].',time_to='.$rec_stat['time_to'].']/">'.$rec_stat['schedule']['in'][1].'</a>':'-'?></td>
                   <td><?echo ($rec_stat['schedule']['out'][1])? '<a href="/cab/esmo_master/[type=mo,dopusk=1,mo_schedule=3,time_from='.$rec_stat['time_from'].',time_to='.$rec_stat['time_to'].']/">'.$rec_stat['schedule']['out'][1].'</a>':'-'?></td>
               <?}?>
         </tr>
      <?
     }
     ?></table><?

   ?></div><?
 }

 function panel_stats_kt()
 { //$now=getdate() ;
   //$start_day=mktime(0,0,0,$now['mon'],$now['mday'],$now['year']);
   //if (!MEMBER()->use_auch_as_smena) $options['from_time']=mktime($now['hours']-12,$now['minutes'],0,$now['mon'],$now['mday'],$now['year']);
   //print_2x_arr($this->arr_smena) ;
   //$time=time() ;
   $time=time() ;

//'/'''''   echo date('d.m.Y H:i:s',$time).'<br>' ;

   //$cur_smena_to=time();

   //echo '$smena_indx='.$cur_smena_indx.'<br>' ;
   //echo '$prev_smena_indx='.$prev_smena_indx.'<br>' ;
   //echo 'cur_smena: '.date('d.m.Y H:i:s',$cur_smena_from).' - '.date('d.m.Y H:i:s',$cur_smena_to).'<br>' ;
   //echo 'prev_smena: '.date('d.m.Y H:i:s',$prev_smena_from).' - '.date('d.m.Y H:i:s',$prev_smena_to).'<br>' ;

   $stats['prev']=$this->get_stats_kt_smena($this->smena_interval['prev']['from'],$this->smena_interval['prev']['to']) ;
   $stats['cur']=$this->get_stats_kt_smena($this->smena_interval['cur']['from'],$this->smena_interval['cur']['to']) ;
   //damp_array($stats) ;

   ?><div id="panel_rmv_stats"><table class="basic full">
     <tr><th>Смена</th><th >Допущено</th><th >Не допущено</th></tr>
     <? if (_sizeof($stats)) foreach($stats as $type=>$rec_stat)
     { ?><tr><td class="left"><strong><?echo ($type=='prev')? 'Предыдущая смена':'Текущая смена'?></strong><br><span class="small">Время МО: <?echo date('d.m.Y H:i',$rec_stat['time_from']).' - '.date('d.m.Y H:i',$rec_stat['time_to'])?></span></td>
               <td><?echo ($rec_stat['dopusk'][1])? '<a href="/cab/esmo_master/[type=kt,dopusk=1,time_from='.$rec_stat['time_from'].',time_to='.$rec_stat['time_to'].']/">'.$rec_stat['dopusk'][1].'</a>':'-'?></td>
               <td><?echo ($rec_stat['denited']['alko'])? '<a href="/cab/esmo_master/[type=kt,dopusk=2,a,time_from='.$rec_stat['time_from'].',time_to='.$rec_stat['time_to'].']/"  class="red">'.$rec_stat['denited']['alko'].'</a>':'-'?></td>
         </tr>
      <?
     }
     ?></table><?

   ?></div><?
 }

 function panel_mo_view()
 {
   include_once(_DIR_EXT.'/aspmo_rmv/report_mo_rmv.php') ;
   $report_obj=new report_mo_rmv() ;
   //damp_array($report_obj->filter) ;
   $report_obj->filter['group_id']=$this->group_id ;
   $report_obj->filter['otdel_ids']=$this->otdel_ids ;

   // фельдщера должны видеть все МО в пределах своей группы
   //if (MEMBER()->info['rol']>1)  $report_obj->filter['doctor_id']=MEMBER()->id ; // для доктора показываем МО только его, для администратора - всех
   ////if (MEMBER()->info['rol']>1)  $options['doctor_id_or_any']=MEMBER()->pkey ; // только с терминалов своей группы
   $report_obj->filter['order']='pkey';
   //$report_obj->setting_small() ;
   //if (strpos('/cab/rmv/',$_SERVER['HTTP_REFERER'])==true)
   $report_obj->view_as_HTML(array('no_reverse_indx'=>1,'order'=>'pkey','template_name'=>'print_template_HTML_small')) ;

 }
 function panel_kt_view()
 {
   include_once(_DIR_EXT.'/kt/report_kt.php') ;
   $report_obj=new report_kt() ;
   //damp_array($report_obj->filter) ;
   //$report_obj->filter['group_id']=$this->group_id ;
   $report_obj->filter['otdel_ids']=$this->otdel_ids ;

   // фельдщера должны видеть все МО в пределах своей группы
   //if (MEMBER()->info['rol']>1)  $report_obj->filter['doctor_id']=MEMBER()->id ; // для доктора показываем МО только его, для администратора - всех
   ////if (MEMBER()->info['rol']>1)  $options['doctor_id_or_any']=MEMBER()->pkey ; // только с терминалов своей группы
   $report_obj->filter['order']='pkey';
   //$report_obj->setting_small() ;
   //if (strpos('/cab/rmv/',$_SERVER['HTTP_REFERER'])==true)
   $report_obj->view(array('no_reverse_indx'=>1,'order'=>'pkey','_template_name'=>'print_template_HTML_small')) ;

 }


}



?>
