<?php
class report_members extends c_report
{
 var $title='Персонал ЭСМО' ;
 var $view_by_space_filter=1 ;
 var $allow_org_ids=1 ;
 var $usl_select_org='' ;
 var $group_id=0 ;
 public $use_datepicker=1 ;
 var $allow_export_to_csv=1 ;
 var $arr_props=array('autorize'=>'Авторизованные',
                      'active'=>'Дежурная смена',
                      'no_ecp'=>'Без ЭЦП',
                      'is_emulate'=>'С эмуляцией ЭЦП',
                      'AD'=>'ActiveDirectory',
                      'only_enabled'=>'Только активные',
                      'only_disabled'=>'Только заблокированные',


         ) ;

 function setting($options=array())
    {   if ($this->filter['personal_id'] and !$this->filter['name']) $this->filter['name']=PERSONAL()->get_name_by_id($this->filter['personal_id']) ;
        $arr_groups=ACCOUNTS()->get_list_workgoups() ;
        $members=ACCOUNTS()->get_list_members() ;
    ?><div id="panel_filter"><?
        $this->form->form_open(array('id'=>'panel_hand_mo')) ;
        $this->form->row_open() ;
        $this->form->filter_section_select_multiple('account_ids','Персонал',2,$members) ;
        $this->form->filter_section_select('rol','Роль',2,$_SESSION['ARR_roll']) ;
        $this->form->filter_section_select('group_id','Группа',2,$arr_groups) ;
        $this->form->filter_section_select_multiple('props','Свойства аккаунта',2,$this->arr_props) ;
        $this->form->row_close() ;
        $this->panel_buttons();
        $this->form->form_close() ;
    ?></div><br><?
     }

  function create_usl_select_obj($_params,&$options)
  {  //damp_array($this->filter,1,-1) ;
     $usl=array() ;
     $usl[]='clss=210' ;
     if ($this->filter['name'])             $usl[]='obj_name like "'.$this->filter['name'].'%"' ;
     if (_sizeof($this->filter['account_ids']))     $usl[]='pkey in ('.implode(',',array_keys($this->filter['account_ids'])).')' ;
     if ($this->filter['rol'])              $usl[]='rol='.$this->filter['rol'].'' ;
     if ($this->filter['group_id'])         $usl[]='(group_id='.$this->filter['group_id'].' or parent='.$this->filter['group_id'].')' ;
     if ($this->filter['props']['autorize'])         $usl[]='time_login>0 and (time_logout=0 or time_logout is null)' ;
     if ($this->filter['props']['active'])           $usl[]='smena=1' ;
     if ($this->filter['props']['only_enabled'])     $usl[]='enabled=1' ;
     if ($this->filter['props']['only_disabled'])     $usl[]='enabled=0' ;
     if ($this->filter['props']['no_ecp'])           $usl[]='(sign_data=0 or sign_data is null)' ;
     if ($this->filter['props']['is_emulate'])       $usl[]='evulate_ECP=1' ;
     if ($this->filter['props']['AD'])               $usl[]='(UID!="" and not UID is null)' ;
     if ($this->group_id)
     { $str_ids=ACCOUNTS()->tree[$this->group_id]->get_list_child() ;
       $usl[]='(group_id in ('.$str_ids.') or parent in ('.$str_ids.'))' ;
     }
     $usl_res=implode(' and ',$usl) ;
     //damp_array($usl,1,-1) ;
     return($usl_res) ;
  }

 function panel_info_filter()
 { $_str=array() ; $info=array() ; $title='' ;
   //damp_array($this->filter) ;
   if ($this->filter['name'])                            $info['ФИО']='"'.$this->filter['name'].'"' ;
   if (_sizeof($this->filter['account_ids']))
      {   $arr=array() ;
             foreach($this->filter['account_ids'] as $id=>$temp) $arr[]=ACCOUNTS()->get_member_name_by_id($id) ;
                    $info['Персонал']=implode(',',$arr) ;
                       }
   if ($this->filter['rol'])                             $info['Роль']='"'.$_SESSION['ARR_roll'][$this->filter['rol']]['obj_name'].'"' ;
   if ($this->group_id)                                  $info['Группа']='"'.ACCOUNTS()->get_group_name($this->group_id).'"' ;
   if ($this->filter['group_id'])                        $info['Группа']='"'.ACCOUNTS()->get_group_name($this->filter['group_id']).'"' ;
   if ($this->filter['props']['autorize'])               $info['Авторизованные']='Да' ;
   if ($this->filter['props']['active'])                 $info['Дежурная смена']='Да' ;
   if ($this->filter['props']['no_ecp'])                 $info['Без ЭЦП']='Да' ;
   if ($this->filter['props']['is_emulate'])             $info['Эмуляция ЭЦП']='Да' ;
   if ($this->filter['props']['AD'])                     $info['AD']='Да' ;
   if ($this->filter['props']['only_enabled'])           $info['Активные']='Да' ;
   if ($this->filter['props']['only_disabled'])          $info['Заблокированные']='Да' ;

   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())
  { $cnt=execSQL_value('select count(pkey)
                        from  view_account
                        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 parent,rol,obj_name' ;
    //echo $usl ;
    //  $options['debug']=2 ;
 	$list_rec=execSQL('select *
                       from  view_account
                       where '.$usl.$order.$limit,$options) ;
    if (_sizeof($list_rec))
    { foreach($list_rec as $id=>$rec) ACCOUNTS()->prepare_public_info_to_member($list_rec[$id],$options) ;
    }
    return($list_rec) ;
  }


    // шаблон - вывод ссылками без разделитея
    function print_template_HTML($list_recs,$options=array())
    {  $items_filter_sets=PERSONALS_FILTER()->get_personals_filter_all() ;
       include_once(_DIR_EXT.'/personal/panel_personal_info.php') ;

       ?><div id="report_membes"><?

       ?><table class="basic full fz_small auto"><tr><th>Состояние</th><th>Группа аккаунта</th><th>Группа при авторизации</th><th>Имя</th><th>Роль</th><th>Должность</th><th>Авторизация</th><th>Смена</th><th>Дежурный</th><th>IP</th><th>Фильтр по сотрудникам</th><th>ЭЦП</th></tr><?
       if (_sizeof($list_recs)) foreach($list_recs as $rec) //if (MEMBER()->rol==1 or (MEMBER()->rol!=1 and $rec['rol']!=1))
       {?>
        <tr><td><?echo ($rec['enabled'])? '<span class="green">включен</span>':'<span class="red">выключен</span>'?></td>
            <td><?if (isset(ACCOUNTS()->tree[$rec['parent']])) echo ACCOUNTS()->tree[$rec['parent']]->name?></td>
            <td><?if (isset(ACCOUNTS()->tree[$rec['group_id']])) echo ACCOUNTS()->tree[$rec['group_id']]->name?></td>
            <td class="left"><?if ($rec['UID']) echo '<i class="fab fa-windows" aria-hidden="true"></i> '?><a  class="new_window" target="_blank" title="window_member" href="<?echo $rec['__href_window']?>"><?echo htmlspecialchars($rec['obj_name'])?></a>
                            <div class="comment small"><?echo $rec['login']?></div>
            </td>
            <td class="left"><?echo $_SESSION['ARR_roll'][$rec['rol']]['obj_name']?></td>
            <td class="left"><?echo $rec['working']?></td>
            <td class="left">
                <?  if ($rec['time_login']) echo '<div style="white-space: nowrap;">Вход:&nbsp;&nbsp; <strong>'.date('d.m.Y H:i:s',$rec['time_login']).'</strong></div>' ;
                    if ($rec['time_logout']) echo '<div style="white-space: nowrap;">Выход: <strong>'.date('d.m.Y H:i:s',$rec['time_logout']).'</strong></div>' ;

                ?>
            </td>
            <td class="left">
                <?  if ($rec['smena_in']) echo '<div style="white-space: nowrap;">Начало:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <strong>'.date('d.m.Y H:i:s',$rec['smena_in']).'</strong></div>' ;
                    if ($rec['smena_out']) echo '<div style="white-space: nowrap;">Окончание: <strong>'.date('d.m.Y H:i:s',$rec['smena_out']).'</strong></div>' ;
                ?>
            </td>
            <td><?echo $_SESSION['ARR_smena_status'][$rec['smena']]?></td>

            <td><?echo $rec['ip']?><?if ($rec['ip'] and $rec['_arm_id']) echo '<br><div class="comment">АРМ ID '.$rec['pkey'].'</div>'?></td>
            <td  class="left"><? panel_personals_filter_info($items_filter_sets[$rec['_reffer']]) ; ?></td>
            <td><?//echo $rec['sert_id'] ;
                   if ($rec['certificate']['ValidFromDate']) echo $rec['certificate']['ValidToDate'] ;
                   if ($rec['evulate_ECP']) echo '<div style="color:red;font-weight:bold;">Эмуляция</div>' ;
                ?>
            </td>
         </tr>
     <?}?>
      </table><?
   ?></div><?
       // print_2x_arr($list_recs) ;
  }

    function print_template_CSV($list_recs,$options=array())
    { $i=$options['from'] ;
      if (_sizeof($list_recs)) foreach($list_recs as $rec)
        { $data=array() ;
            // обязательные поля в каждой выгрузке
            $data['ID']=$rec['pkey'] ;
            $data['ФИО']=$rec['obj_name'] ;
            $data['Статус']=($rec['enabled'])? 'Активен':'Заблокирован' ;
            $data['Группа аккакунта']=(isset(ACCOUNTS()->tree[$rec['parent']]))? ACCOUNTS()->tree[$rec['parent']]->name:'' ;
            $data['Группа при авторизации']=(isset(ACCOUNTS()->tree[$rec['group_id']]))? ACCOUNTS()->tree[$rec['group_id']]->name:'' ;
            $data['Логин']=$rec['login'] ;
            $data['UID']=$rec['UID'] ;
            $data['Роль']=($rec['rol'])? $_SESSION['ARR_roll'][$rec['rol']]['obj_name']:'' ;
            $data['Должность']=$rec['working'] ;
            $data['Последняя авторизация, IP']=$rec['ip'];
            $data['Последняя авторизация, вход']=($rec['time_login'])? date('d.m.Y H:i:s',$rec['time_login']):'';
            $data['Последняя авторизация, выход']=($rec['time_logout'])? date('d.m.Y H:i:s',$rec['time_logout']):'';
            $data['Последняя смена, начало']=($rec['smena_in'])? date('d.m.Y H:i:s',$rec['smena_in']):'';
            $data['Последняя смена, окончание']=($rec['smena_out'])? date('d.m.Y H:i:s',$rec['smena_out']):'';
            $data['Статус смены']=$_SESSION['ARR_smena_status'][$rec['smena']] ;
            $data['Эмуляция ЭЦП']=($rec['evulate_ECP'])? 'Да':'';
            $data['Сертификат ЭЦП']=$rec['certificate']['IssuerName'];
            $data['Срок действия, от']=$rec['certificate']['ValidFromDate'];
            $data['Срок действия, до']=$rec['certificate']['ValidToDate'];
            $diff_day='' ;
            if ($rec['certificate']['ValidToDate'])
            {
                $to=strtotime($rec['certificate']['ValidToDate']) ;
                if ($to)
                { $diff=$to-time() ;
                  $diff_day=ceil($diff/(60*60*24)) ;
                }
            }
            $data['Число дней до окончания срока действия сертификата']=$diff_day ;

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

          $i++ ;
        }

    }
}
?>
