<?
class report_poll_graf_stats extends c_report
{ var $title='Отчет по оценке знаний' ;
  var $filter=array() ;
  //var $url_report='/cab/reports/itog6/' ;
  public $use_fusioncharts=1 ;
  //var $PDF_master='TCPDF' ;  // короткие отчеты выгружвать через обычный  PDF
  var $view_graf=1 ;
  var $view_table=1 ;
  var $time_int=array(1=>'Cутки',2=>'Неделя',3=>'Месяц') ;
  var $arr_group=array('1d'=>'Cутки','1w'=>'Неделя','1m'=>'Месяц') ;
  var $view_mode=array(3=>'Год',2=>'Квартал',1=>'Месяц') ;
  var $step='1m' ;
  //var $allow_export_to_csv=1 ;
  //public $PDF_page_orientation='P' ; // L P
  //var $use_csv_easy=1 ;
  var $event_id=0 ;
  var $personal_id=0 ;
  var $section_id=0 ;

  function get_week_period($data_info) {
        $result=[];
        $ts=getdate($data_info['min_data']) ; $wday_shift=0;
        if ($ts['wday']) $wday_shift=$ts['wday']-1; else $wday_shift=6;
        $cur_week_start=mktime(0,0,0,$ts['mon'],$ts['mday']-$wday_shift,$ts['year']) ;
        $cur_week_end=$cur_week_start+60*60*24*7-1;
        $result[$cur_week_start]=date('d.m.Y',$cur_week_start).' - '.date('d.m.Y',$cur_week_end);
        $t1=$cur_week_start+60*60*24*7;
        while ($t1<$data_info['max_data']) {
            $t2=$t1+60*60*24*7-1;
            $result[$t1]=date('d.m.Y',$t1).' - '.date('d.m.Y',$t2);
            $t1+=60*60*24*7;
        }
        krsort($result);
        return $result;
    }

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

     $_usl=array() ;
     $_usl[]='not t3.parent is null' ;
     if ($this->personal_id)    $_usl[]='t1.personal_id='.$this->personal_id ;
     if ($this->event_id)       $_usl[]='t1.event_id='.$this->event_id ;

      if ($this->section_id)
      {
          $section_level=execSQL_value('select level from poll_themes where pkey='.$this->section_id) ;
          $arr_childs=execSQL_line('select pkey from poll_themes where parent'.$section_level.'='.$this->section_id) ;
          $arr_childs[]=$this->section_id ;
          //print_r($arr_childs) ;
          $_usl[]='t3.parent in ('.implode(',',$arr_childs).')' ;
      }

     $usl=(_sizeof($_usl))? implode(' and ',$_usl):'1' ;

       // получаем список всех ТЕМ вопросов, которые задавались сотруднику
         $theme_recs=execSQL('select t4.pkey as theme_id,t4.obj_name as theme_name,
                             t3.pkey as section_id,t3.obj_name as section_name
                             from poll_result t1 
                             left join poll_questions t2 on t2.pkey=t1.question_id 
                             left join poll_themes t3 on t3.pkey=t2.parent 
                             left join poll_themes t4 on t4.pkey=t3.parent2 
                             where '.$usl.'   
                             group by t4.pkey,t3.pkey
                             order by t4.indx,t3.indx
                             ',0,1) ;
          $arr_themes=array() ; $arr_themes_section=array() ;
         if (_sizeof($theme_recs)) foreach($theme_recs as $rec)
         {  $arr_themes[$rec['theme_id']]=$rec['theme_name'] ;
            $arr_themes_section[$rec['theme_id']][$rec['section_id']]=$rec['section_name'] ;

         }
         //damp_array($arr_themes);

       $this->form_open() ;
       $this->row_open() ;
       if (!$this->section_id) $this->filter_section_select('theme_id','Тема опроса:',2,$arr_themes) ;
       if ($this->filter['theme_id']) $this->filter_section_select_multiple('section_ids','Разделы опроса:',4,$arr_themes_section[$this->filter['theme_id']]) ;
       if (!$this->personal_id) $this->filter_section_select_multiple('org_ids','Организация:',2,$arr_orgs_ids) ;
       if (!$this->personal_id) $this->filter_section_select_multiple('otdel_ids','Подразделение:',2,$arr_otdel_ids) ;
       $this->filter_section_select('view_mode','Обзор:',2,$this->view_mode,array('nospace_element'=>1)) ;
       $this->row_close() ;
       $this->panel_buttons();
       $this->form_close() ;



   }

  function setting_small()
      {   $arr_orgs_ids=PERSONAL()->get_arr_orgs_to_cur_account() ;
          $this->form_open() ;
          $this->row_open() ;
          $this->filter_section_select_multiple('org_ids','Организация:',2,$arr_orgs_ids) ;
          $this->row_close() ;
          $this->$this->panel_button_apply();
          $this->form_close() ;
      }

  function get_arr_info_filters()
  { $info=parent::get_arr_info_filters() ;
    if ($this->filter['time_int'])                        $info['временной интервал']=$this->time_int[$this->filter['time_int']] ;
    if ($this->filter['theme_id'])                        $info['Тема опроса']=POLL()->get_theme_name_by_id($this->filter['theme_id']);
    if (_sizeof($this->filter['section_ids']))             $info['Раздел опроса']=POLL()->get_theme_name_by_ids(implode(',',array_keys($this->filter['section_ids'])));
    return $info ;
 }

function HTML_report_body($options=array())
{   $recs=$this->prepare_result_data() ;
    //damp_array($recs,1,-1) ;
    ?><div id="reports_itog1"><?
       //if ($this->view_graf)
           $this->report_graf($recs) ;
       //if ($this->view_table) $this->report_table($recs) ;
    ?></div><?
}

function prepare_result_data()
{
    //$data_info=execSQL_van('select min(c_data) as min_data,max(c_data) as max_data from poll_result where personal_id='.$this->personal_id) ;

    if (!$this->filter['view_mode']) $this->filter['view_mode']=3 ; // по умолчанию обзор за последний год
    // обзор месяца - группировка по дням
    // обзор квартала - группировка по дням
    // обзор года - группировка по месяцам
    // произвольные даты - показыаем дату от, дату до, и выбор группировки


    switch($this->filter['view_mode'])
      { case 1: // показываем последнй месяц, группировка по дням
                  $tm=getdate();
                  $time_from=mktime(0,0,0,$tm['mon']-1,$tm['mday'],$tm['year']) ;
                  $time_to=mktime(0,0,0,$tm['mon'],$tm['mday']+1,$tm['year'])-1 ;
                  $this->filter['group_type']='1d' ;
                  break ;
        case 2: // показываем последнй месяц, группировка по кварталу
                      $tm=getdate();
                      $time_from=mktime(0,0,0,$tm['mon']-3,$tm['mday'],$tm['year']) ;
                      $time_to=mktime(0,0,0,$tm['mon'],$tm['mday']+1,$tm['year'])-1 ;
                      $this->filter['group_type']='1d' ;
                      break ;
        case 3: // показываем последнй месяц, группировка по году
                      $tm=getdate();
                      $time_from=mktime(0,0,0,$tm['mon'],$tm['mday'],$tm['year']-1) ;
                      $time_to=mktime(0,0,0,$tm['mon'],$tm['mday']+1,$tm['year'])-1 ;
                      $this->filter['group_type']='1m' ;
                      break ;

    }


    $result=array() ;$result2=array() ; $all_reason=array() ; $all_reason2=array() ;

    if ($this->section_id) $this->filter['theme_id']=$this->section_id ;


    $_usl=array() ;
    if ($this->personal_id)    $_usl[]='personal_id='.$this->personal_id ;
    if ($this->event_id)       $_usl[]='event_id='.$this->event_id ;
    if ($this->filter['theme_id'])
    {   $questions_ids=TREE('view_poll_tree')->get_child_ids_all($this->filter['theme_id'],['clss'=>'573']) ;
        if (_sizeof($questions_ids)) $_usl[]='question_id in ('.implode(',',$questions_ids).')';
    }
    if (_sizeof($this->filter['org_ids']))    $_usl[]='_org_id in ('.implode(',',array_keys($this->filter['org_ids'])).')' ;
    if (_sizeof($this->filter['otdel_ids']))  $_usl[]='_otdel_id in ('.implode(',',array_keys($this->filter['otdel_ids'])).')' ;
    //if ($this->filter['group_id'] and isset(ACCOUNTS()->tree[$this->filter['group_id']]))  $_usl[]='group_id in ('.ACCOUNTS()->tree[$this->filter['group_id']]->get_list_child().')' ;
    //damp_array($_usl,1,-1);
    $dop_usl=(_sizeof($_usl))? ' and '.implode(' and ',$_usl):'' ;
    //echo '$dop_usl='.$dop_usl.'<br>' ;
    //echo 'time_from='.date('d.m.Y H:i:s',$time_from).'<br>' ;
    //echo 'time_to='.date('d.m.Y H:i:s',$time_to).'<br>' ;


    $t=$time_from ;
    while($t<=$time_to)
    {   $ts=getdate($t) ;   $t1=$t ;
        $cur_month=mktime(0,0,0,$ts['mon'],1,$ts['year']) ;
        $arr_month[$cur_month]=get_month_year($cur_month,'month year') ;
        switch($this->filter['group_type'])
        { case '1d': $t=mktime(0,0,0,$ts['mon'],$ts['mday']+1,$ts['year']) ; $t2=$t-1; $i=get_month_year($t1,'day month') ; ; break  ;
          case '1w': $t=mktime(0,0,0,$ts['mon'],$ts['mday']+7,$ts['year']) ; $t2=$t-1; $i=date('d.m.Y',$t1).'-'.date('d.m.Y',$t2) ; break  ;
          case '1m': $t=mktime(0,0,0,$ts['mon']+1,1,$ts['year']) ; $t2=$t-1; $i=get_month_year($t1,'month year') ; break ;
        }

        $result2[$i]['count_session_kz']=execSQL_value('select count(distinct(poll_id)) from view_poll_result where poll_с_data>='.$t1.' and poll_с_data<='.$t2.$dop_usl) ;
        $result2[$i]['count_personals']=execSQL_value('select count(distinct(personal_id)) from view_poll_result where poll_с_data>='.$t1.' and poll_с_data<='.$t2.$dop_usl) ;
        $result2[$i]['count_question']=execSQL_value('select count(question_id) from view_poll_result where poll_с_data>='.$t1.' and poll_с_data<='.$t2.$dop_usl) ;
        //$result2[$i]['count_correct']=execSQL_value('select count(correct) from view_poll_result where poll_с_data>='.$t1.' and poll_с_data<='.$t2.' and correct=1'.$dop_usl) ;
        $result2[$i]['k1']=($result2[$i]['count_question'])? round($result2[$i]['count_correct']/$result2[$i]['count_question']*100):0 ;


    }

    //print_2x_arr($result2);

    return($result2) ;
}


function report_graf($result)
   {   //print_2x_arr($result);
       $caption='График оценки знаний' ;
       $t_now=time() ;

       $arr_month=array_keys($result) ;
       ?><div id="chart-container">Подождите, идет построение графика</div>
         <script type="text/javascript">
         $j(document).ready(function(){
          FusionCharts.ready(function(){
         var revenueChart2 = new FusionCharts({
               type: 'mscombidy2d',
               renderAt: 'chart-container',
               width: '1000',
               height: '400',
               dataFormat: 'json',
               dataSource: {
                   "chart": {
                       "caption": "<?echo $caption?>",
                       "xAxisname": "Время",
                       "pYAxisName": "Кол-во вопросов/ответов",
                       "sYAxisName": "Уровень знаний, %",
                       //"numberPrefix": "",
                       //"sNumberSuffix" : "",
                       //"sYAxisMaxValue" : "50",
                       //"sYAxisMaxValue" : "15",

                       //Cosmetics
                       "paletteColors" : "#0075c2,#1aaf5d,#f2c500",
                       "baseFontColor" : "#333333",
                       "baseFont" : "Helvetica Neue,Arial",
                       "captionFontSize" : "14",
                       "subcaptionFontSize" : "14",
                       "subcaptionFontBold" : "0",
                       "showBorder" : "0",
                       "bgColor" : "#ffffff",
                       "showShadow" : "0",
                       "canvasBgColor" : "#ffffff",
                       "canvasBorderAlpha" : "0",
                       "divlineAlpha" : "100",
                       "divlineColor" : "#999999",
                       "divlineThickness" : "1",
                       "divLineIsDashed" : "1",
                       "divLineDashLen" : "1",
                       "divLineGapLen" : "1",
                       "usePlotGradientColor" : "0",
                       "showplotborder" : "0",
                       "showXAxisLine" : "1",
                       "xAxisLineThickness" : "1",
                       "xAxisLineColor" : "#999999",
                       "showAlternateHGridColor" : "0",
                       "showAlternateVGridColor" : "0",
                       "legendBgAlpha" : "0",
                       "legendBorderAlpha" : "0",
                       "legendShadow" : "0",
                       "legendItemFontSize" : "10",
                       "legendItemFontColor" : "#666666"
                   },
                   "categories":
                   [{
                       "category": [ <?foreach($arr_month as $date) echo '{ "label": "'.$date.'" },' ; ?>]
                   }],
                   "dataset":
                   [
                       {
                            "seriesName": "Задано вопросов",
                           "showValues": "1",
                            //"renderAs": "line",
                            "data": [ <?foreach($result as $t=>$res)if ($res['time']<$t_now) echo '{ "value" : "'.$res['count_question'].'" },'?>]
                        },
                       {
                          "seriesName": "правильных ответов",
                          //"parentYAxis": "S",
                          //"renderAs": "line",
                          "showValues": "1",
                          "divlineThickness" : "1",
                          "data": [ <?foreach($result as $t=>$res) if ($res['time']<$t_now) echo '{ "value" : "'.$res['count_correct'].'" },'?>]
                      },

                       {      "seriesName": "Уровень знаний, %",
                              "parentYAxis": "S",
                              "renderAs": "line",
                              "showValues": "1",
                              "divlineThickness" : "1",
                              "data": [ <?foreach($result as $t=>$res) if ($res['time']<$t_now) echo '{ "value" : "'.$res['k1'].'" },'?>]
                       },



                   ]
               }
           });

           revenueChart2.render();
       });
         }) ;
            </script>
            <style type="text/css">#chart-container{margin:0 auto;width:1000px;}</style>
          <?


       $this->view_graf_source_in_table($result) ;



   }

    function view_graf_source_in_table($table)
    { //print_2x_arr($table);
      ?><table class="basic fz_small full auto">
          <tr><th></th>
              <?if (_sizeof($table)) foreach($table as $date=>$rec){?><th><?echo $date?></th><?}?>
          </tr>
          <tr>
              <td><strong>Количество заданных вопросов</strong></td>
              <?if (_sizeof($table)) foreach($table as $date=>$rec){?><td><?echo ($rec['count_question'])? $rec['count_question']:'-'?></td><?}?>
          </tr>
          <tr>
              <td><strong>Количество правильных ответов</strong></td>
              <?if (_sizeof($table)) foreach($table as $date=>$rec){?><td><?echo ($rec['count_correct'])? $rec['count_correct']:'-'?></td><?}?>
          </tr>
          <tr>
              <td><strong>Количество сотрудников, прошедших опроса</strong></td>
              <?if (_sizeof($table)) foreach($table as $date=>$rec){?><td><?echo ($rec['count_personals'])? $rec['count_personals']:'-'?></td><?}?>
          </tr>
          <tr>
              <td><strong>Оценка знаний</strong></td>
              <?if (_sizeof($table)) foreach($table as $date=>$rec){?><td><?echo ($rec['k1'])? $rec['k1'].'%':'-'?></td><?}?>
          </tr>

        </table>
        <style type="text/css">
            div#reports_itog2{}
            div#reports_itog2 table{width:100%;table-layout:auto;border-collapse:collapse;}
            div#reports_itog2 th{background:#dddddd;color:black;font-weight:bold;border:1px solid #aaaaaa;}
            div#reports_itog2 td{padding:5px;border:1px solid #aaaaaa;text-align:center;}
            div#reports_itog2 td.left{text-align:left;}
            div#reports_itog2 tr.subitog td{font-weight:bold;}
            div#reports_itog2 tr.itog td{font-weight:bold;background:#dddddd;}
         </style><?
    }

}

?>
