<?php
include_once(_DIR_EXT.'/aspmo_rmv/report_mo_rmv.php') ;
class report_faceid_stats extends report_mo_rmv
{
 var $title='faceid - статистика' ;
 var $allow_to_rol=array() ;
 var $filter=array() ;
 var $view_by_space_filter=1 ;
 public $use_fusioncharts=1 ;
 //var $use_jwplayer=1 ;

    function setting()
         {
             //$arr_accounts=ACCOUNTS()->get_list_members(array('group_id'=>MEMBER()->cur_group_id,'rol'=>'2,3')) ;
             $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) ;
             $arr_terminals=ESMO()->get_list_terminals(MEMBER()->cur_group_id) ;
             $arr_readers=execSQL_line('select distinct(reader) from obj_site_mo_session where reader!="" and reader!="0"') ;
             if (!$this->filter['data_from'])
             { $now=getdate() ;
               $from_time=mktime(0,0,0,$now['mon']-1,$now['mday'],$now['year']);
               $this->filter['data_from']=date('d.m.Y',$from_time) ;
             }

             ?><div id="panel_filter">
               <form id="sky-form" class="sky-form"><input type="hidden" name="filter_dir" value="<?echo $this->url_report?>">
                    <fieldset>
                        <div class="row">
                            <? $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) ;
                               $this->filter_section_input_text('name','ФИО:',4,array('auto_complete'=>"autocomplette_personal_name")) ;
                               $this->filter_section_input_text('propusk','Пропуск:',2) ;
                               $this->filter_section_select('intrusion','FaceControl:',2,$this->arr_intrusion) ;
                            ?>
                        </div>
                        <div class="row">
                            <? $this->filter_section_input_text('id_mo','ID МО:',2) ;
                               $this->filter_section_select('terminal_id','Терминал:',2,$arr_terminals,array('key_fname'=>'id')) ;
                               $this->filter_section_select('tk','Тип контроля:',2,$_SESSION['ARR_mo_tk_type'],array('use_id_plus_1'=>1)) ;
                               $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>
          <?
        }


 function panel_list_items_top_navigat(&$options=array()) {}

 function print_template_HTML($list_recs,$options=array())
 {
    //damp_array($this);
    $usl_select=[] ;
    //if ($this->usl_items) $usl_select[]=$this->usl_items ;
    $usl_select[]='c_data_d>0' ;
    $usl_select[]=$this->usl_items ;

    //$usl_select[]='reader!="" and reader!="0"' ;
    $usl_select[]='reader!=""' ;
    //$usl_select[]='(reason="intrusion" or reason="" or reason is null)' ;
    $usl=implode(' and ',$usl_select) ;
    $recs=execSQL('select c_data_d,reader,reason,count(pkey) as cnt 
                   from obj_site_mo_session
                   where '.$usl.'
                   group by c_data_d,reader,reason
                   order by c_data_d desc,reader,reason
                   ',0,1) ;

     $recs2=array(); $arr_readers=array() ;
    if (_sizeof($recs)) foreach($recs as $rec)
    { $reader=($rec['reader'])? $rec['reader']:'Нет данных' ;
      $recs2[$rec['c_data_d']][$reader]+=$rec['cnt'] ;
      //$recs2[$rec['c_data_d']]['all']+=$rec['cnt'] ;
      //if ($rec['reason']=='intrusion') $recs2[$rec['c_data_d']]['intrusion_1']+=$rec['cnt'] ;
      //else                             $recs2[$rec['c_data_d']]['intrusion_0']+=$rec['cnt'] ;
      $arr_readers[$reader]=1 ;
    }

    $this->report_graf($recs2,$arr_readers) ;


    //damp_array($recs2) ;
    ?><table class="basic fz_small auto">
           <tr>
               <th rowspan="2">Дата</th>
               <!--<th colspan="<?echo _sizeof($arr_readers)?>">Способ авторизации</th><th colspan="2">Результат FaceControl</th>-->
           </tr>
            <tr>
               <?if (_sizeof($arr_readers)) foreach($arr_readers as $reader=>$temp){?><th><?echo $reader?></th><?}?>
              <th>Всего</th>
              <!--<th>Не пройден</th>-->
            </tr>
     <? if (_sizeof($recs2)) foreach($recs2 as $t=>$rec)
         { ?><tr>
                <td><?echo date('d.m.Y',$t)?></td>
                <?if (_sizeof($arr_readers)) foreach($arr_readers as $reader=>$temp) {?><td><a><?echo '<a href="/cab/faceid/facecontrol_log/[reader='.$reader.',data_from='.date('d.m.Y',$t).',data_to='.date('d.m.Y',$t).']/" class="new_window" target="_blank" title="win_second">'.$rec[$reader]?></a></td><?}?>
                <td><?echo array_sum($rec)?></td>
                <!--<td><? echo ($rec['intrusion_0'])? '<a href="/cab/faceid/facecontrol_log/[intrusion,data_from='.date('d.m.Y',$t).',data_to='.date('d.m.Y',$t).']/" class="new_window" target="_blank" title="win_second"><span class=green>'.$rec['intrusion_0'].'</span></a>':'-' ; ?></td>
                <td><? echo ($rec['intrusion_0'])? '<a href="/cab/faceid/facecontrol_log/[intrusion=2,data_from='.date('d.m.Y',$t).',data_to='.date('d.m.Y',$t).']/" class="new_window" target="_blank" title="win_second"><span class=red>'.$rec['intrusion_1'].'</span></a>':'-' ; ?></td>
                -->
                <!--<td><? if (_sizeof($rec[0])) echo '<a href="/cab/faceid/facecontrol_log/[intrusion,reader=faceid,data_from='.date('d.m.Y',$t).',data_to='.date('d.m.Y',$t).']/" class="new_window" target="_blank" title="win_second">'._sizeof($rec[0]).'</a>' ; else echo '-' ;
                        /*if (_sizeof($rec[0])) foreach($rec[0] as $id_mo){?><a class="new_window" target="_blank" title="win_second" href="/cab/mo/<?echo $id_mo?>/db/facecontrol/"><?echo $id_mo?></a> <?}*/
                    ?>
                </td>
                <td><? if (_sizeof($rec[1])) echo '<a href="/cab/faceid/facecontrol_log/[intrusion=2,reader=faceid,data_from='.date('d.m.Y',$t).',data_to='.date('d.m.Y',$t).']/" class="new_window" target="_blank" title="win_second">'._sizeof($rec[1]).'</a>' ; else echo '-' ;
                        /*if (_sizeof($rec[1])) foreach($rec[1] as $id_mo){?><a class="new_window" target="_blank" title="win_second" href="/cab/mo/<?echo $id_mo?>/db/facecontrol/"><?echo $id_mo?></a> <?}*/

                     ?>
                </td>-->
             </tr>
           <?
         }

     ?>
      </table>
    <?
 }


 function report_graf($result,$arr_readers)
 {   //print_2x_arr($result);
     $result=array_reverse($result,TRUE) ;
     $arr_cnt_all=array() ; $arr_faceid=array() ; $arr_faceid_proc=[]; $arr_other=[] ;
     foreach($result as $t=>$recs)
     { foreach($recs as $reader=>$cnt)
         { $arr_cnt_all[$t]+=$cnt ; // общее число МО
           $arr_faceid[$t]+=($reader=='faceid')? $cnt:0 ; // число МО, авторизированные через FaceID
         }
     }
     foreach($arr_cnt_all as $t=>$cnt_all)
     { $arr_faceid_proc[$t]=ENGINE()->get_procent($cnt_all,$arr_faceid[$t]) ;  // число МО, авторизированные через FaceID
       $arr_other[$t]=$arr_cnt_all[$t]-$arr_faceid[$t] ;
     }

     /*$t=strtotime('19.03.2019') ;
     echo '$arr_cnt_all='.$arr_cnt_all[$t].'<br>' ;
     echo '$arr_faceid='.$arr_faceid[$t].'<br>' ;
     echo '$arr_faceid_proc='.$arr_faceid_proc[$t].'<br>' ;
     print_r($result[$t]) ;*/


     $FusionCharts=new i_FusionCharts() ;
     $FusionCharts->head('stackedcolumn2dlinedy') ;
     //$FusionCharts->head('mscombidy2d') ;
     $FusionCharts->dataSource(array('xAxisname'=>'Время','pYAxisName'=>'Кол-во сеансов','sYAxisName'=>'Использование FaceID, %','sYAxisMinValue'=>0,'sYAxisMaxValue'=>100)) ;
     $FusionCharts->categories(array_keys($result),array('view_timecode_as_d_m_y'=>1)) ;
     $FusionCharts->dataSet('Число сеансов без FaceID',$arr_other) ;
     $FusionCharts->dataSet('Число сеансов FaceID',$arr_faceid) ;
     $FusionCharts->dataSet('% FaceID авторизации',$arr_faceid_proc,'',array('parentYAxis'=>'S','renderAs'=>'line','showValues'=>0)) ;
     $FusionCharts->show() ;
 }








}

class i_FusionCharts
{ var $data=[] ;
  function head($type)
  { $this->data['type']=$type ;
    $this->data['renderAt']='chart-container' ;
    $this->data['width']='1000' ;
    $this->data['height']='400' ;
    $this->data['dataFormat']='json' ;
  }


  function dataSource($options=array())
  {
      if ($options['caption'])          $chart['caption']=$options['caption'] ;
      if ($options['xAxisname'])        $chart['xAxisname']=$options['xAxisname'] ;
      if ($options['pYAxisName'])       $chart['sYAxisName']=$options['pYAxisName'] ;
      if ($options['sYAxisName'])       $chart['sYAxisName']=$options['sYAxisName'] ;
      if ($options['sYAxisMaxValue'])   $chart['sYAxisMaxValue']=$options['sYAxisMaxValue'] ;
      if ($options['sYAxisMinValue'])   $chart['sYAxisMinValue']=$options['sYAxisMinValue'] ;
       //"numberPrefix": "",
       //"sNumberSuffix" : "",
       //Cosmetics
      $chart['paletteColors']="#0075c2,#1aaf5d,#f2c500" ;
      $chart['baseFontColor']="#333333" ;
      $chart['baseFont']="Helvetica Neue,Arial" ;
      $chart['captionFontSize']="14" ;
      $chart['subcaptionFontSize']="14";
      $chart['subcaptionFontBold']="0";
      $chart['showBorder']="0";
      $chart['bgColor']="#ffffff";
      $chart['showShadow']="0";
      $chart['canvasBgColor']="#ffffff";
      $chart['canvasBorderAlpha']="0";
      $chart['divlineAlpha']="100";
      $chart['divlineColor']="#999999";
      $chart['divlineThickness']="1";
      $chart['divLineIsDashed']="1";
      $chart['divLineDashLen']="1";
      $chart['divLineGapLen']="1";
      $chart['usePlotGradientColor']="0";
      $chart['showplotborder']="0";
      $chart['showXAxisLine']="1";
      $chart['xAxisLineThickness']="1";
      $chart['xAxisLineColor']="#999999";
      $chart['showAlternateHGridColor']="0";
      $chart['showAlternateVGridColor']="0";
      $chart['legendBgAlpha']="0";
      $chart['legendBorderAlpha']="0";
      $chart['legendShadow']="0";
      $chart['legendItemFontSize']="10";
      $chart['legendItemFontColor']="#666666";

      $this->data['dataSource']['chart']=$chart ;
  }

  function categories($arr,$options=array())
  {  $category=[] ;
     if (_sizeof($arr)) foreach($arr as $value)
     { if ($options['view_timecode_as_d_m_y']) $value=date('d.m.Y',$value) ;
       $category[]=['label'=>$value] ;
     }
     $this->data['dataSource']['categories'][]['category']=$category ;
  }

  function dataSet($seriesName,$data,$fname='',$options=array())
  { $dataset=array('seriesName'=>$seriesName,
                   'showValues'=>(isset($options['showValues']))? $options['showValues']:1
                  ) ;
    if ($options['renderAs'])    $dataset['renderAs']=$options['renderAs'] ;
    if ($options['parentYAxis']) $dataset['parentYAxis']=$options['parentYAxis'] ;
    if (_sizeof($data)) foreach($data as $value) $dataset['data'][]=($fname)? ['value'=>$value[$fname]]:['value'=>$value] ;
    $this->data['dataSource']['dataset'][]=$dataset ;
  }

  function data_to_json()
  {
      echo json_encode($this->data,JSON_UNESCAPED_UNICODE) ;
  }

  function show()
  {
      ?><div id="chart-container">Подождите, идет построение графика</div>
        <script type="text/javascript">
        $j(document).ready(function()
        {
           FusionCharts.ready(function()
           { var revenueChart2 = new FusionCharts(<?$this->data_to_json();?>) ;
             revenueChart2.render();
           }) ;
        }) ;
        </script>
        <style type="text/css">#chart-container{margin:0 auto;width:1000px;}</style>
      <?
  }


    function get_category_values($arr)
    {   $str='[' ;
        foreach($arr as $id=>$rec) $str.='{ "label" : "'.$id.'" },' ;
        $str.=']' ;
        return($str) ;
    }


}


?>
