<?php
class report_poll_emulator extends c_report
{
 var $title='Генератор данных контроля знаний' ;
 var $filter=array() ;
 public $use_fusioncharts=1 ;
 var $PDF_master='TCPDF' ;  // короткие отчеты выгружвать через обычный  PDF
 var $arr_obzor=array('last_week'=>'неделя (по дням)',
                      'last_month'=>'месяц (по дням)',
                      'last_year'=>'год (по месяцам)',
                      'select_week'=>'выбрать неделю (по дням)',
                      'select_month'=>'выбрать месяц (по дням)',
                      //'select_year'=>'выбрать год (по дням)',
                      //'select_range'=>'выбрать интервал',


         ) ;  // короткие отчеты выгружвать через обычный  PDF

  var $arr_group=array(1=>'Организациям',
                       2=>'Подразделениям',
                       3=>'Должности',


         ) ;  // короткие отчеты выгружвать через обычный  PDF

    var $stats_themes ;

 function setting()
   {
     $data_info=execSQL_van('select min(day) as min_data,max(day) as max_data from poll_stats') ;
      // damp_array($data_info) ;
     $t=$data_info['min_data'] ;
     while($t<$data_info['max_data'])
     {   $ts=getdate($t) ;
         $cur_month=mktime(0,0,0,$ts['mon'],1,$ts['year']) ;
         $arr[$cur_month]=get_month_year($cur_month,'month year') ;
         $t=mktime(0,0,0,$ts['mon']+1,1,$ts['year']) ;
     }

     $data_info=execSQL_van('select min(c_data) as min_data,max(c_data) as max_data from poll_result') ;
     $t=$data_info['min_data'] ;
	 if ($data_info['max_data']>$data_info['min_data']) while($t<$data_info['max_data'])
         {   $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') ;
            $cur_month=mktime(0,0,0,$ts['mon']+1,1,$ts['year'])-1 ;
            $arr_to[$cur_month]=get_month_year($cur_month,'month year') ;
    	    $t=mktime(0,0,0,$ts['mon']+1,1,$ts['year']) ;
        }


     list($arr_orgs_ids,$arr_otdel_ids,$arr_works_ids)=PERSONAL()->get_org_otdels_works_to_cur_account($this->filter) ;

     $poll_themes=execSQL_row('select pkey,obj_name from  poll_themes where parent=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">
                             <?
                             $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_select_multiple('theme_ids','Темы:',2,$poll_themes) ;
                             $this->filter_section_input_text('data_from','От:',2,array('class'=>'datepicker')) ;
                             $this->filter_section_input_text('data_to','До:',2,array('class'=>'datepicker')) ;
                             $this->filter_section_input_text('proc_from','Уровень знаний, от:',2) ;
                             $this->filter_section_input_text('proc_to','Уровень знаний, до:',2) ;
                             ?>
                         </div>
                     </fieldset>
                     <div id="panel_buttons"><input type="submit" class="button v2" cmd="set_filter" value="Сгенерировать данные"></div>
                 </form>
         </div>
     <?
   }

 function get_arr_weeks($from=0,$count=10)
 {   $arr_weeks=array() ;
     $ts=($from)? getdate($from):getdate() ;
     $cur_week_start=mktime(0,0,0,$ts['mon'],$ts['mday']-$ts['wday']+1,$ts['year']) ;
     //damp_array($ts) ;
     for ($i=1;$i<=10;$i++)
     { $ts=getdate($cur_week_start) ;
       $from=$cur_week_start ;
       $to=mktime(0,0,0,$ts['mon'],$ts['mday']+6,$ts['year']) ;
       $arr_weeks[$from]=get_month_year($from,'day month').'  - '.get_month_year($to,'day month') ;
       $cur_week_start=mktime(0,0,0,$ts['mon'],$ts['mday']-7,$ts['year']) ; ;
     }
     //damp_array($arr_weeks) ;
     return($arr_weeks) ;
 }

 function get_arr_month($from=0,$count=10)
 {   $arr_weeks=array() ;
     $ts=($from)? getdate($from):getdate() ;
     $cur_week_start=mktime(0,0,0,$ts['mon'],1,$ts['year']) ;
     //damp_array($ts) ;
     for ($i=1;$i<=12;$i++)
     { $ts=getdate($cur_week_start) ;
       $from=$cur_week_start ;
       $arr_weeks[$from]=get_month_year($from,'month year') ; //.' '.date('d.m.Y H:i:s',$from) ;
       $cur_week_start=mktime(0,0,0,$ts['mon']-1,$ts['mday'],$ts['year']) ; ;
     }
     //damp_array($arr_weeks) ;
     return($arr_weeks) ;
 }


    function panel_info_filter()
    { $_str=array() ; $info=array() ; $title='' ;
      if ($this->filter['time_from'])                       $info['с']=date('d.m.Y H:i',$this->filter['time_from']) ;
      if ($this->filter['time_to'])                         $info['по']=date('d.m.Y H:i',$this->filter['time_to']) ;
      if ($this->filter['month_from'])                       $info['с']=date('d.m.Y H:i',$this->filter['month_from']) ;
      if ($this->filter['month_to'])                         $info['по']=date('d.m.Y H:i',$this->filter['month_to']) ;
      //if ($this->filter['time_int'])                        $info['временной интрервал']=$this->time_int[$this->filter['time_int']] ;
      if ($this->filter['group_id'])                        $info['Группа терминалов']=ACCOUNTS()->get_member_name_by_id($this->filter['group_id'])  ;
      if ($this->filter['org_id'])                          $info['Организация']=PERSONAL()->get_name_by_id($this->filter['org_id'])  ;
      if ($this->filter['org_ids'])
      {   $arr_names=execSQL_line('select obj_name from obj_site_personals where pkey in ('.implode(',',array_keys($this->filter['org_ids'])).')') ;
          $info['Организация']=implode(', ',$arr_names)  ;
      }
      if ($this->filter['group_id'])                        $info['Группа']=ACCOUNTS()->get_member_name_by_id($this->filter['group_id'])  ;
      if ($this->filter['dep_id'])                          $info['Подразделение']=PERSONAL()->get_full_dep_name_by_dep_id($this->filter['dep_id'])  ;
      //if ($this->filter['min_mo'])                          $info['Минимальное число МО']=$this->filter['min_mo']  ;
      //if ($this->filter['min_proc'])                        $info['Порог']=$this->filter['min_proc'].' %'  ;
      if (_sizeof($info)) foreach($info as $title=>$value)   if (is_array($value)) $_str[]=$title.': <strong>'.implode(',',$value).'</strong>' ; else $_str[]=$title.': <strong>'.$value.'</strong>' ;
      if (_sizeof($_str)) $title='<p class=center>'.implode(' ',$_str).'</p>' ;
      return $title ;
    }

    function HTML_report_body($options=array())
    {  //$GLOBALS['debug_db']=1 ;
        //damp_array($this->filter) ;
        execSQL_update('delete from poll_result where temp=1',2) ;
        //return ;





        $arr_usl_select_persons=array('clss=211 and enabled=1') ;
        if (_sizeof($this->filter['org_ids'])) $arr_usl_select_persons[]='parent2 in ('.implode(',',array_keys($this->filter['org_ids'])).')';
        if (_sizeof($this->filter['otdel_ids'])) $arr_usl_select[]='(parent3 in ('.implode(',',array_keys($this->filter['otdel_ids'])).') or parent4 in ('.implode(',',array_keys($this->filter['otdel_ids'])).') or parent5 in ('.implode(',',array_keys($this->filter['otdel_ids'])).'))';
        $usl_select_persons=implode(' and ',$arr_usl_select_persons) ;
        $personal_ids=execSQL_line('select pkey from obj_site_personals where '.$usl_select_persons) ;

        $theme_ids=(_sizeof($this->filter['theme_ids']))? array_keys($this->filter['theme_ids']):execSQL_line('select pkey from poll_themes where parent=1') ;
        $section_ids=execSQL_line('select pkey from poll_themes where parent2 in ('.implode(',',$theme_ids).')') ;
        $question_ids=execSQL_line('select pkey from poll_questions where parent in ('.implode(',',$section_ids).')') ;
        //print_r($theme_ids) ;
        $proc_from=($this->filter['proc_from'])? $this->filter['proc_from']:0 ;
        $proc_to=($this->filter['proc_to'])? $this->filter['proc_to']:0 ;
        echo '$proc_from='.$proc_from.'<br>' ;
        echo '$proc_to='.$proc_to.'<br>' ;



        if ($this->filter['data_from'] and $this->filter['data_to'])
        {  $t=strtotime($this->filter['data_from']) ;
           $t_to=strtotime($this->filter['data_to']) ;
           // считаем число дней между началом и концом,
           $count_day=($t_to-$t)/(60*60*24) ;
           echo '$count_day='.round($count_day).'<br>' ;
           $dp=($proc_to-$proc_from)/$count_day ;
           $proc=$proc_from ;
           while($t<=$t_to)
            {
               $ts=getdate($t) ;
               // задаем по одному вопросу кажлый день каждому сотруднику
               foreach($personal_ids as $personal_id)
               {  // $question_id
                  $question_id=$question_ids[rand(0,_sizeof($section_ids))-1] ;
                  $correct=(rand(0,100)<$proc)? 1:0 ;
                  $c_data=mktime(rand(1,23),rand(0,59),rand(0,56),$ts['mon'],$ts['mday'],$ts['year']) ;
                  multiSQL_insert('poll_result')->append(['c_data'=>$c_data,
                                                          'personal_id'=>$personal_id,
                                                          'mo_id'=>0,
                                                          //'event_id'=>$event_id,
                                                          'theme_id'=>0,
                                                          'poll_id'=>0,
                                                          'question_id'=>$question_id,
                                                          'answer_id'=>0,
                                                          'temp'=>1
                                                        ]) ;
               }


               echo 'Добавлены данные за <strong>'.date('d.m.Y',$t).'</strong><br>' ;
               $proc+=$dp ;
               $t=mktime(0,0,0,$ts['mon'],$ts['mday']+1,$ts['year']) ;
            }
            multiSQL_insert('poll_result')->flush() ;

        }


        execSQL_update('delete from poll_stats',1) ;
        POLL()->update_stats() ;

    }
}

?>
