<?php
class report_events_info_instruktions extends c_report
{
 var $title='Мероприятия' ;
 var $view_by_space_filter=1 ;
 //var $doc_types_names=array() ;
 //var $allow_export_to_csv=1 ;
 var $type ;
 var $status ;
 var $ext ;
 var $arr_types=array('esmo_magnit_instruction.i_event_instruction1'=>'Сезонный инструктаж',
                      'esmo_magnit_instruction.i_event_instruction2'=>'Вводный инструктаж',
                      'esmo_magnit_instruction.i_event_instruction3'=>'Специальный инструктаж',
                      'esmo_magnit_instruction.i_event_training'=>'Учебная программа'
             ) ;
    //var $allow_export_to_csv=1 ;
    //var $report_script=_DIR_EXT.'/events/report_events_info.php' ;
 var $arr_view_status=array(1=>'Выключенные',2=>'Архив',3=>'Все');

    function init($create_options=array())
    {
        //$cnt_active=execSQL_value('select count(pkey) from  obj_site_events_schedule where ext like "'.$this->ext.'" and enabled=1 and status<5');
        //if(!$cnt_active and !$this->filter['view_status']) $this->filter['view_status']=3;
    }

 function setting($options=array())
 {

        $this->form_open();
        $this->fieldset_open();
        $this->row_open();
        $this->filter_section_input_text('name','Наименование:',2,array('_auto_complete'=>"autocomplette_personal_name")) ;
        $this->filter_section_select('type','Тип мероприятия:',2,$this->arr_types) ;
        $this->filter_section_select('view_status','Показывать мероприятия:',2,$this->arr_view_status);
        $this->filter_section_input_text('data_from','От:',2,array('class'=>'datetimepicker')) ;
        $this->filter_section_input_text('data_to','До:',2,array('class'=>'datetimepicker')) ;
        $this->row_close();
        $this->fieldset_close();
        $this->panel_buttons($options);
        $this->form_close();
  }

    function panel_report_buttons($options=array())
    {
        if(MEMBER()->rol==1)
        {
            if($this->status!=5)
            { ?>
                <button use_form="form_report" class="button v2" cmd="events/check_to_arhive">В архив</button>&nbsp;&nbsp;<?
            }
            else
            { ?>
                <button use_form="form_report" class="button v2" cmd="events/check_out_arhive">Из архива</button>&nbsp;&nbsp;<?
            }
    }
        if ($options['show_button_create_event']) {?><button use_form="form_report" class="button v2" cmd="events/create_event" event_type="events_quiz/i_event_quiz">Новое мероприятие КЗ</button><?}
  }

  function create_usl_select_obj($_params,&$options)
    {   //damp_array($this->filter);
        $usl=array();

     $usl[]='clss=222' ;
     if ($this->type) $usl[]='type='.$this->type ;
     if ($this->filter['group_id'])
        {
            $arr1=ACCOUNTS()->tree[$this->filter['group_id']]->get_arr_child();
            echo '<br>';
            $arr2=ACCOUNTS()->tree[$this->filter['group_id']]->get_arr_parent();
            echo '<br>';
         $arr_ids=array_merge($arr1,$arr2) ;
         if (_sizeof($arr_ids)) $usl[]='group_id in ('.implode(',',$arr_ids).')'  ;
     }
     if ($this->filter['name'])        $usl[]='obj_name like "%'.$this->filter['name'].'%"' ;
     if ($this->filter['data_from'])        $usl[]='c_data>='.strtotime($this->filter['data_from']) ;
     if ($this->filter['data_to'])         $usl[]='c_data<='.strtotime($this->filter['data_to']) ;
        //if ($this->status)                    $usl[]='status='.$this->status ;
        // else                                 $usl[]='status!=5' ;
     if ($this->filter['status'])          $usl[]='status='.$this->filter['status'] ;
        if(!$this->filter['view_status']) $usl[]='enabled=1 and status<5';
        elseif($this->filter['view_status']==1) $usl[]='enabled=0 and status<5';
        elseif($this->filter['view_status']==2) $usl[]='status=5';
        if($this->ext) $usl[]='ext like "'.$this->ext.'"';
     if ($this->filter['type'])            $usl[]='ext="'.addslashes(str_replace('.','/',$this->filter['type'])).'"' ;
     // если у сотрудника есть фильтр по персоналу, то показывать только те мероприятия, в которых участвуют его сотрудники
     if (MEMBER()->rol!=1)  // фильтр сортрудников аккаунта
        { $event_ids=execSQL_line('select distinct(event_id) 
                                   from view_event_personals t1
                                   left join '.MEMBER()->personal_viewer_name.' t2 on t2.pkey=t1.personal_id
                                   where not t2.pkey is null
                                   ') ;
           if (_sizeof($event_ids)) $usl[]='pkey in ('.implode(',',$event_ids).')' ;
           else                    $usl[]=0 ;
        }

     $usl_res=implode(' and ',$usl) ;
     //damp_array($usl,1,-1) ;
     return($usl_res) ;
  }

 function panel_info_filter()
    {
        $_str=array();
        $info=array();
        $title='';
   //if ($this->filter['group_id'])        $info['Группа']=ACCOUNTS()->get_member_name_by_id($this->filter['group_id']) ;
   //if ($this->filter['personal_id'])     $info['Сотрудник']=PERSONAL()->get_name_by_id($this->filter['personal_id']) ;
   if ($this->filter['name'])              $info['Наименование']='"'.htmlspecialchars_decode($this->filter['name']).'"' ;
        if($this->filter['view_status']) $info['Показывать']='"'.$this->arr_view_status[$this->filter['view_status']].'"';
   if ($this->filter['type'])              $info['Тип мероприятия']='"'.$this->arr_types[$this->filter['type']].'"' ;
   if ($this->filter['status'])            $info['Cтатус']='"'.$_SESSION['ARR_events_status'][$this->filter['status']].'"' ;
   if ($this->status)                      $info['Cтатус']='"'.$_SESSION['ARR_events_status'][$this->status].'"' ;
   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())
    {
        $cnt=execSQL_value('select count(pkey)
                        from  obj_site_events_schedule
                        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' ;
    $order=($options['order'])? ' order by '.$options['order']:' order by pkey desc' ;
    //$options['debug']=2 ;
 	$list_rec=execSQL('select * from  obj_site_events_schedule where '.$usl.$order.$limit,$options) ;
    if (_sizeof($list_rec)) foreach($list_rec as $id=>$rec) EVENTS()->prepare_public_info_to_event($list_rec[$id],$options) ;
    return($list_rec) ;
  }

// шаблон - вывод ссылками без разделитея
  function print_template_HTML($list_recs,$options=array())
    {
        $id=($options['id'])? 'id='.$options['id']:'';
        ?>
        <form id="form_report">
        <table class="basic fz_small full auto"<? echo $id ?>>
            <tr><? if(MEMBER()->rol==1)
                {
                    ?>
                    <th>Выбор</th><?
                } ?>
                <th>ID</th>
                <th>Дата/время<br>создания</th>
                <th>Статус</th>
                <th>Тип</th>
                <th>Наименование</th>
                <th>Переодичность</th>
                <th>Сроки проведения</th>
                <!--<th>Место проведения</th>-->
                <th>Отбор персонала</th>
                <th>Всего</th>
                <th>Подлежат участию</th>
                <th>Направлены</th>
                <th>Проходят</th>
                <th>Прошли</th>
                <th>КВ</th>
            </tr><?
          if (_sizeof($list_recs)) foreach($list_recs as $rec)
            {

                $cnt_in=0;
                $cnt_start=0;
                $cnt_process=0;
                $cnt_end=0;
                // данные по участникам мероприятия с учетом группы текущего аккаунта
              $arr_personals_status=EVENTS()->get_event_personals_status($rec['pkey']) ;
              $personals_count=array_sum($arr_personals_status) ;
              // считаем чисто подлежащих по условию отбора
              if ($rec['dyn_pass'])
                {
                    $use_select=($rec['_ext_info']['usl_select'])? $rec['_ext_info']['usl_select']:'clss=211 and enabled=1';
                 //echo $use_select ;

                    $personals_count=execSQL_value('select count(pkey) from  '.$rec['viewer_name']);
                 $arr_personals_status[1]=$personals_count-$arr_personals_status[3] ;
                 $arr_personals_status[7]=$arr_personals_status[3] ;
                 $arr_personals_status[3]=0 ;
              }

              $cnt_in=$arr_personals_status[1] ;
              $cnt_start=$arr_personals_status[2]+$arr_personals_status[3] ;
              $cnt_process=$arr_personals_status[4]+$arr_personals_status[5]+$arr_personals_status[6] ;
              $cnt_end=$arr_personals_status[7]+$arr_personals_status[8];
              if ($rec['type']==1)
                {
                    $cnt_in=$arr_personals_status[1];
                $cnt_start=$arr_personals_status[2]+$arr_personals_status[22]+$arr_personals_status[3]+$arr_personals_status[4]+$arr_personals_status[5] ;
                $cnt_process=$arr_personals_status[6]+$arr_personals_status[7] ;
                $cnt_end=$arr_personals_status[8]+$arr_personals_status[9];
              }
              $kv=($personals_count)? $cnt_end/$personals_count*100:0 ;
                ?>
                <tr>
                <? if(MEMBER()->rol==1)
            {
                ?>
                <td><input type="checkbox" name="_check[<? echo $rec['pkey'] ?>]" value="1"></td><?
            } ?>
                  <td><?echo $rec['pkey']?></td>
                  <td><?echo date('d.m.Y H:i',$rec['c_data'])?><??></td>
                <td><? echo $rec['_status']; ?></td>
                  <td><?echo $rec['__type_name']?></td>
                <td class="left"><? echo $rec['__href_name'] ?></td>
                <td><? echo $rec['_mode'] ?></td>
                <td><? echo $rec['_date_from_to'].$rec['_day_status'].$rec['_time_status'] ?></td>
                <!--<td><? echo $rec['_group_ids'] ?></td>-->
                <td  class="left"><div style="max-height:100px;overflow:auto;"><? PERSONALS_FILTER()->get_personals_filter_info_to_item($rec['_reffer']) ;?></div></td>
                  <td><?echo ($personals_count)? $personals_count:'-'?></td>
                  <td><?echo ($cnt_in)? $cnt_in:'-'?></td>
                  <td><?echo ($cnt_start)? $cnt_start:'-'?></td>
                  <td><?echo ($cnt_process)? $cnt_process:'-'?></td>
                  <td><?echo ($cnt_end)? $cnt_end:'-'?></td>
                <td><? echo ($kv)? '<span class="nowrap">'.round($kv,2).' %</span>':'-' ?></td></tr><?
          }
       ?></table></form><?
      //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)
        {
            $arr_personals_status=EVENTS()->get_event_personals_status($rec['pkey']);
              $personals_count=array_sum($arr_personals_status) ;

              $cnt_in=$arr_personals_status[1] ;
              $cnt_start=$arr_personals_status[2]+$arr_personals_status[3] ;
              $cnt_process=$arr_personals_status[4]+$arr_personals_status[5]+$arr_personals_status[6] ;
              $cnt_end=$arr_personals_status[7]+$arr_personals_status[8];
              if ($rec['type']==1)
            {
                $cnt_in=$arr_personals_status[1];
                $cnt_start=$arr_personals_status[2]+$arr_personals_status[22]+$arr_personals_status[3]+$arr_personals_status[4]+$arr_personals_status[5] ;
                $cnt_process=$arr_personals_status[6]+$arr_personals_status[7] ;
                $cnt_end=$arr_personals_status[8]+$arr_personals_status[9];
              }
              $kv=($personals_count)? $cnt_end/$personals_count*100:0 ;

            $data=array() ;
            $data['№']=$i+1 ;
            $data['Дата/время создания']=date('d.m.Y H:i',$rec['c_data'])  ;
            $data['Наименование']=$rec['obj_name']  ;
            $data['Тип']=$rec['__type_name']  ;
            $data['Переодичность']=($rec['mode'])? $_SESSION['ARR_events_mode'][$rec['mode']]:''  ;
            $data['Дата от']=($rec['date_from'])? date('d.m.Y',$rec['date_from']):''  ;
            $data['Дата до']=($rec['date_to'])? date('d.m.Y',$rec['date_to']):''  ;
            $data['Место проведения']=(_sizeof($rec['_ext_info']['_group_ids']))? implode(', ',$rec['_ext_info']['_group_ids']):'все АТП'  ;
            $data['Всего']=($personals_count)? $personals_count:0 ;
            $data['Подлежат участию']=($cnt_in)? $cnt_in:0 ;
            $data['Направлены']=($cnt_start)? $cnt_start:0 ;
            $data['Направлены']=($cnt_start)? $cnt_start:0 ;
            $data['Проходят']=($cnt_process)? $cnt_process:0 ;
            $data['Прошли']=($cnt_end)? $cnt_end:0 ;
            $data['КВ']=($kv)? round($kv,2).' %':'-' ;
            // вносим данные в csv
            $this->put_data_to_CSV($data,$i) ;
            $i++ ;
        }
    }
}

?>
