<?php
// отчет используется
/// главная страница отчетов /poll/ - без фильтров
class report_poll_question_result extends c_report
{
 var $title='Результаты опросов' ;
 var $personal_id=0 ;
 var $event_id=0 ;
 var $section_id=0 ;
 var $answer_id=0 ;
 var $usl_time ;
 var $time_from ;
 var $usl_poll_result ;
 var $rec_section=[] ;



 function init($crete_options=array())
 {    if ($this->section_id)
      { $this->filter['theme_id']=$this->section_id  ;
        $this->rec_section=POLL()->get_theme_by_id($this->section_id) ;
      }
      if ($this->answer_id)
      { $this->filter['theme_id']=$this->answer_id  ;
        $this->rec_section=POLL()->get_answer_by_id($this->answer_id) ;
      }
 }

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

         $this->form_open() ;
         $this->row_open() ;
         $this->fieldset_open() ;
         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','Подразделение:',6,$arr_otdel_ids) ;
         $this->row_close() ;
         $this->panel_buttons();
         $this->fieldset_close() ;
         $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->time_from)                                 $info['Анализ данных']='от '.date('d.m.Y',$this->time_from) ;
   else                                                  $info['Анализ данных']='за все время' ;
   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 get_cnt_items($usl,$options=array()){return(1) ;}

 function get_items($usl,$options=array()){return(array()) ;}

 function print_template_HTML($list_recs,$options=array())
  { $id=($options['id'])? 'id='.$options['id']:'' ;
    //$personal_id=($this->personal_id)? $this->personal_id:$this->filter['personal_id'] ;

    // получаем список всех ТЕМ вопросов, которые задавались сотруднику
    // получаем список тем и подтем текущего раздела

    //$childs_sections=TREE('poll_themes')->get_list_child($this->section_id) ;
    //$childs_sections[$this->section_id]=1 ;
    //$section_ids=array_keys($childs_sections) ;
    //print_r($section_ids) ;
    // получаем список разделов текущего и следующего уровня
    //$rec_subsections=[] ; $rec_subsections_by_section=[] ;
    //$rec_sections=execSQL('select pkey as id,obj_name,clss from poll_themes where parent='.$this->rec_section['pkey']) ;
    //if (_sizeof($rec_sections)) $rec_subsections=execSQL('select pkey as id,obj_name,parent,clss from poll_themes where parent in ('.implode(',',array_keys($rec_sections)).')') ;

    $recs_questions=execSQL('select * from view_poll_questions where parent'.$this->rec_section['level'].'='.$this->rec_section['pkey'].' order by indx') ;
    // предварительно заполнение массива вопросами, так как результаты могут выбть не по всем вопросам
    $stats=[] ;
    if (_sizeof($recs_questions)) foreach($recs_questions as $rec)
    { $stats2[$rec['parent']][$rec['pkey']]['question_text']=$rec['obj_name'] ;
      $stats2[$rec['parent']][$rec['pkey']]['avg_answer_ball']=0 ;
      $stats2[$rec['parent']][$rec['pkey']]['avg_answer_proc']=0 ;
      $stats2[$rec['parent']][$rec['pkey']]['cnt']=0 ;
    }

    //$viewer_name=PERSONALS_FILTER()->get_personals_viewer_name_to_item($this->rec_section['_reffer']) ;
    //$viewer_name=PERSONALS_FILTER()->get_personals_viewer_name_to_item($this->rec_section['view_personals_poll_section_2']) ;
    //$cnt_persons_all=execSQL('select * from view_personals_poll_section_2',2) ;
    if ($this->rec_section['viewer_name']) $cnt_persons_all=execSQL_value('select count(distinct(pkey)) from '.$this->rec_section['viewer_name']) ;
    else $cnt_persons_all=0 ;

    //damp_array($this->filter);

    $_usl=[] ;
    $_usl[]='t1.parent'.$this->rec_section['level'].'='.$this->rec_section['pkey'] ; // все вопросы в текущем разделе
    $_usl[]='not MPS.pkey is null' ; // только сотрудники, которые видны текущему аккаунту
    if (_sizeof($this->filter['org_ids']))
    {  $level_info=execSQL_row('select pkey,level from obj_site_personals where pkey in ('.implode(',',array_keys($this->filter['org_ids'])).')') ;
       $_usl_org=[] ;
       if (_sizeof($level_info))
       { foreach($level_info as $id=>$level) $_usl_org[]='fl.parent'.$level.'='.$id ;
         $_usl[]='('.implode(' or ',$_usl_org).')' ;
       }
    }
    if (_sizeof($this->filter['otdel_ids']))
    {  $level_info=execSQL_row('select pkey,level from obj_site_personals where pkey in ('.implode(',',array_keys($this->filter['otdel_ids'])).')') ;
       $_usl_org=[] ;
       if (_sizeof($level_info))
       { foreach($level_info as $id=>$level) $_usl_org[]='fl.parent'.$level.'='.$id ;
         $_usl[]='('.implode(' or ',$_usl_org).')' ;
       }
    }

    $usl=implode(' and ',$_usl) ;

    // статистика для вопросов с баллами
    $recs1=execSQL(
          'select t1.pkey as question_id,t3.answer_ball,
           count(t3.pkey) as cnt,count(t3.personal_id) as cnt_persons,
           t1.obj_name as question_name,t1.indx as question_indx,t1.parent
           from poll_result t3
           left join view_poll_questions t1 on t1.pkey=t3.question_id 
           left join '.MEMBER()->personal_viewer_name.' MPS on MPS.pkey=t3.personal_id 
           left join obj_site_personals fl on fl.pkey=t3.personal_id 
           where '.$usl.' and t1.answer_type=1
           group by t1.pkey,t3.answer_ball
           order by t1.pkey,t3.answer_ball
          ',0,1) ;

    // статистика для вопросов с ответами - тут уклонистов не видно
    /*$recs2=execSQL(
          'select t1.pkey as question_id,t2.pkey as answer_id,count(t3.pkey) as cnt,count(t3.personal_id) as cnt_persons,
           t1.obj_name as question_name,t1.indx as question_indx,t1.parent,t1.parent2,t1.parent3,t2.obj_name as answer_text,t1.is_second
           from view_poll_questions t1
           left join poll_answers t2  on t2.question_id=t1.pkey
           left join poll_result t3 on t3.question_id=t1.pkey and t3.answer_id=t2.pkey
           left join '.MEMBER()->personal_viewer_name.' MPS on MPS.pkey=t3.personal_id
           left join obj_site_personals fl on fl.pkey=t3.personal_id
           where '.$usl.' and t1.answer_type=2
           group by t1.pkey,t1.answer_type,t2.pkey
           order by t1.pkey,t1.answer_type,t2.pkey
          ',0,1) ;*/

    // времено убираем join по obj_site_workers так как из-за того идет задвоении результатов при совмещении
    //left join obj_site_workers so on so.personal_id=t3.personal_id

    $recs2=execSQL(
              'select t1.pkey as question_id,t2.pkey as answer_id,count(t3.pkey) as cnt,count(t3.personal_id) as cnt_persons,
               t1.obj_name as question_name,t1.indx as question_indx,t1.parent,t1.parent2,t1.parent3,t2.obj_name as answer_text,t1.is_second
               from poll_result t3
               left join view_poll_questions t1  on t1.pkey=t3.question_id 
               left join poll_answers t2 on t2.question_id=t1.pkey and t2.pkey=t3.answer_id
               left join '.MEMBER()->personal_viewer_name.' MPS on MPS.pkey=t3.personal_id
               left join obj_site_personals fl on fl.pkey=t3.personal_id 
               where '.$usl.' and t1.answer_type=2 and t3.personal_id>0
               group by t1.pkey,t2.pkey
               order by t1.pkey,t2.pkey
              ',0,1) ;


    $arr_answers_cnt=[] ; $arr_answers_ball_cnt=[] ;
    if (_sizeof($recs1)) foreach($recs1 as $rec)
        { if (!$rec['answer_ball']) $rec['answer_ball']=-1 ;
          //$stats2[$rec['parent']][$rec['question_id']]['avg_answer_ball']=$rec['avg_answer_ball'] ;
          //$stats2[$rec['parent']][$rec['question_id']]['avg_answer_proc']=round($rec['avg_answer_ball']*100/5,2) ;
          //$stats2[$rec['parent']][$rec['question_id']]['answers'][0]['answer_text']=$rec['answer_ball'].' балл ' ;
          //$stats2[$rec['parent']][$rec['question_id']]['answers'][0]['cnt']=$rec['cnt'] ;
          $arr_answers_ball_cnt[$rec['question_id']][$rec['answer_ball']]+=$rec['cnt_persons'] ;
          if ($rec['is_second']) $use_cnt_persons_all=$arr_answers_cnt[$rec['parent']] ;
          $stats2[$rec['parent']][$rec['question_id']]['parent']=$rec['parent'] ;
          $stats2[$rec['parent']][$rec['question_id']]['parent2']=$rec['parent2'] ;
          $stats2[$rec['parent']][$rec['question_id']]['parent3']=$rec['parent3'] ;
          $stats2[$rec['parent']][$rec['question_id']]['answers'][$rec['answer_ball']]['answer_text']=($rec['answer_ball']>0)? $rec['answer_ball'].' '.get_case_by_count_1_2_5($rec['answer_ball'],'балл,балла,баллов'):'Уклонился от ответа' ;
          $stats2[$rec['parent']][$rec['question_id']]['answers'][$rec['answer_ball']]['cnt']=$rec['cnt'] ;
          $stats2[$rec['parent']][$rec['question_id']]['cnt_persons']+=$rec['cnt_persons'] ;
          $stats2[$rec['parent']][$rec['question_id']]['cnt_person_proc']=($cnt_persons_all)? round($stats2[$rec['parent']][$rec['question_id']]['cnt_persons']*100/$cnt_persons_all):0 ;
          $stats2[$rec['parent']][$rec['question_id']]['cnt_person_info']=$stats2[$rec['parent']][$rec['question_id']]['cnt_persons'].' из '.$cnt_persons_all ;
          $stats2[$rec['parent']][$rec['question_id']]['cnt_persons_all']=$cnt_persons_all ;
          $stats2[$rec['parent']][$rec['question_id']]['cnt_answers']++ ;
          $stats2[$rec['parent']][$rec['question_id']]['cnt']+=$rec['cnt'] ;
          $stats2[$rec['parent']][$rec['question_id']]['answer_type']=1 ;
        }
    //damp_array($arr_answers_ball_cnt);

    if (_sizeof($recs2)) foreach($recs2 as $rec)
        { $use_cnt_persons_all=$cnt_persons_all ;
          if (!$rec['answer_id']) { $rec['answer_id']=-1 ; $rec['answer_text']='Уклонился от ответа' ; }
          $arr_answers_cnt[$rec['answer_id']]+=$rec['cnt_persons'] ;
          if ($rec['is_second']) $use_cnt_persons_all=$arr_answers_cnt[$rec['parent']] ;
          $stats2[$rec['parent']][$rec['question_id']]['parent']=$rec['parent'] ;
          $stats2[$rec['parent']][$rec['question_id']]['parent2']=$rec['parent2'] ;
          $stats2[$rec['parent']][$rec['question_id']]['parent3']=$rec['parent3'] ;
          $stats2[$rec['parent']][$rec['question_id']]['answers'][$rec['answer_id']]['answer_text']=$rec['answer_text'] ;
          $stats2[$rec['parent']][$rec['question_id']]['answers'][$rec['answer_id']]['cnt']=$rec['cnt'] ;
          $stats2[$rec['parent']][$rec['question_id']]['cnt_persons']+=$rec['cnt_persons'] ;
          $stats2[$rec['parent']][$rec['question_id']]['cnt_person_proc']=($use_cnt_persons_all)? round($stats2[$rec['parent']][$rec['question_id']]['cnt_persons']*100/$use_cnt_persons_all):0 ;
          $stats2[$rec['parent']][$rec['question_id']]['cnt_person_info']=$stats2[$rec['parent']][$rec['question_id']]['cnt_persons'].' из '.$use_cnt_persons_all ;
          $stats2[$rec['parent']][$rec['question_id']]['cnt_persons_all']=$use_cnt_persons_all ;
          $stats2[$rec['parent']][$rec['question_id']]['cnt_answers']++ ;
          $stats2[$rec['parent']][$rec['question_id']]['cnt']+=$rec['cnt'] ;
          $stats2[$rec['parent']][$rec['question_id']]['answer_type']=2 ;
        }
   // damp_array($stats2,1,-1);
    //execSQL('select * from poll_result',2) ;
    TREE('view_poll_tree')->upload_tree_objects();
    TREE('view_poll_tree')->create_model();
    //echo TREE('view_poll_tree')->tree[4]->get_name_patch_span(0).'<br>';
    //echo TREE('view_poll_tree')->tree[8]->get_name_patch_span(0).'<br>';
    //damp_array(TREE('view_poll_tree'));

    $stats=$stats2[$this->section_id] ;
    $this->stats2=$stats2 ;
    //$this->table_stats_old($stats) ;
    $this->table_stats_new($stats,$arr_answers_ball_cnt) ;

    ?><script type="text/javascript">
                $j('div.myProgress').each(function()
                  {   var value=$j(this).attr('value') ; //value=30 ;
                      $j(this).append('<div class=myBar></div>') ;
                      $j(this).find('div.myBar').css('width',value+'%') ;
                      $j(this).find('div.myBar').text(value+'%') ;

                      console.log('procent: '+value) ;
                      console.log('color: '+getColorForPercentage(value)) ;
                      $j(this).find('div.myBar').css('background-color',getColorForPercentage(value)) ;

                  })


                function getColorForPercentage(pct) {

                    var percentColors = [
                                   { pct: 0, color: { r: 0xff, g: 0x00, b: 0 } },
                                   { pct: 50, color: { r: 0xff, g: 0xff, b: 0 } },
                                   { pct: 100, color: { r: 0x00, g: 0xff, b: 0 } } ];



                    for (var i = 1; i < percentColors.length - 1; i++) {
                        if (pct < percentColors[i].pct) {
                            break;
                        }
                    }
                    var lower = percentColors[i - 1];
                    var upper = percentColors[i];
                    var range = upper.pct - lower.pct;
                    var rangePct = (pct - lower.pct) / range;
                    var pctLower = 1 - rangePct;
                    var pctUpper = rangePct;
                    var color = {
                        r: Math.floor(lower.color.r * pctLower + upper.color.r * pctUpper),
                        g: Math.floor(lower.color.g * pctLower + upper.color.g * pctUpper),
                        b: Math.floor(lower.color.b * pctLower + upper.color.b * pctUpper)
                    };
                    return 'rgb(' + [color.r, color.g, color.b].join(',') + ')';
                    // or output as hex if preferred
                };
            </script>
      <style type="text/css">
            .myProgress {
              width: 100%;
              background-color: grey;
            }

            .myBar {
              width: 1%;
              height: 23px;
              background-color: green;
                padding-top:7px;
                font-size:10px;
            }
        </style>
    <?
   }

   function table_stats_old($stats)
   {
     ?><table class="basic fz_small full auto">
             <tr><th>!ID вопроса</th>
                 <th>Число сессий</th>
                 <th>Охват участников<br>(опрошено участников)</th>
                 <th>Текст вопроса</th>
                 <th>Текст ответа</th>
                 <th>Число ответов</th>
                 <th>Результат</th>
                 </tr><?
             if (_sizeof($stats)) foreach($stats as $question_id=>$rec_question)
             {   ?><tr class=item>
                     <td rowspan="<?echo _sizeof($rec_question['answers'])?>"><?echo $question_id?></td>
                     <td rowspan="<?echo _sizeof($rec_question['answers'])?>"><?echo ($rec_question['cnt'])? $rec_question['cnt']:'-'?>/td>
                     <td rowspan="<?echo _sizeof($rec_question['answers'])?>"><?echo $rec_question['cnt_person_proc']?>% <div class="comment"><?echo $rec_question['cnt_person_info']?></div></td>
                     <td class="left" rowspan="<?echo _sizeof($rec_question['answers'])?>">
                       <?
                             echo '<i class="fas fa-question-circle"></i>'. $rec_question['question_text']?></td>

                     <? $i=0 ;
                        if (_sizeof($rec_question['answers'])) foreach($rec_question['answers'] as $answers_id=>$rec_answer)
                         {   if ($i) echo '<tr>' ;
                             ?><td><? echo '<i class="fas fa-ellipsis-h"></i> '.$rec_answer['answer_text'] ;?></td>
                               <td><?echo $rec_answer['cnt']?></td>
                               <td><? switch($rec_question['answer_type'])
                                      { case 1: ?><div class="myProgress" value="<?echo round($rec_question['avg_answer_proc'])?>"></div><?
                                                break ;
                                        case 2: $proc=($rec_question['cnt_persons'])? $rec_answer['cnt']/$rec_question['cnt_persons']*100:0 ;
                                                echo round($proc).'%'  ;
                                                break ;
             						 }
                                    ?>
                               </td>
                             <?
                             $i++ ;
                             echo '</tr>' ;
                         }
                        else
                        {?><td colspan="2">Балл от 1 до 5</td>
                           <td></td>
                         <?
                        }
                     ?>
                 </tr>
                 <?
             }
           ?></table><?
   }

   function table_stats_new($stats,$arr_answers_ball_cnt)
   {
     ?><table class="basic fz_small full auto" style="margin-top:0;"><?
             if (_sizeof($stats)) foreach($stats as $question_id=>$rec_question)
             {   ?><tr class=item>
                     <th class="left" style="text-align:left;">
                       <?
                       //echo '<i class="fas fa-question-circle green"></i> <strong>'.$rec_question['question_text'].'</strong><br>' ;
                       echo '<i class="fas fa-question-circle green"></i> '.TREE('view_poll_tree')->tree[$question_id]->get_name_patch_span(1).'<br>';
                       ?>
                     </th>
                     <th style="width:150px;"><?echo ($rec_question['cnt'])? '<strong>'.$rec_question['cnt'].'</strong> сессий опросов':'-'?></th>
                     <th style="width:150px;"><?echo $rec_question['cnt_person_proc']?>% <div class="comment"><?echo $rec_question['cnt_person_info']?></div></th>
                     <th></th>
                   </tr>

                     <? $i=0 ;
                        // в вопросах с ответами перемещаем уклонистов в конец списка
                        if ($rec_question['answer_type']==2 and _sizeof($rec_question['answers']) and isset($rec_question['answers'][-1]))
                        { $tt=$rec_question['answers'][-1] ;
                          unset($rec_question['answers'][-1]) ;
                          $rec_question['answers'][-1]=$tt ;
						}
                        // в вопросам с баллам просто сортируем баллы по убыванию
                        if ($rec_question['answer_type']==1 and _sizeof($rec_question['answers']))
                        {
                          krsort($rec_question['answers']) ;
						}

                        include_once(_DIR_EXT.'/poll/report_poll_section_stats_pie2d.php');
                        include_once(_DIR_EXT.'/poll/report_poll_section_stats_angulargauge.php');

                        /*if ($rec_question['answer_type']==1)
                        { $sum=0 ; $cnt2=0 ;
                          if (_sizeof($arr_answers_ball_cnt[$question_id])) foreach($arr_answers_ball_cnt[$question_id] as $ball=>$cnt) if ($ball>0) { $sum+=$ball*$cnt ; $cnt2+=$cnt ; }
                          $av_ball=$sum/$cnt2 ;
                          $avg_answer_proc=round($av_ball*100/5,2) ;
                          ?><tr><td class="right">Средний балл:</td><td colspan="2"><div class="myProgress" value="<?echo $avg_answer_proc?>"></div></td>
                                <td rowspan="<?echo _sizeof($rec_question['answers'])+1?>">
                                    <?
                                    $report_obj=new report_poll_section_stats_angulargauge();
                                    $report_obj->no_view_title=1;
                                    $report_obj->filter['question_id']=$question_id;
                                    $report_obj->view_as_HTML();
                                    ?>
                                </td>
                            </tr><?
						}*/

                        $row=0 ;
                        if (_sizeof($rec_question['answers'])) foreach($rec_question['answers'] as $answers_id=>$rec_answer)
                         {   $url='' ;
                             if ($rec_question['answer_type']==1) $url='/frame/poll/question/card/'.$question_id.'/stats/[answer_balls=('.$answers_id.')]/' ;
                             if ($rec_question['answer_type']==2) $url='/frame/poll/question/card/'.$question_id.'/stats/[answer_ids=('.$answers_id.')]/' ;

                             echo '<tr>' ;
                             ?><td style="width:auto;" class="left"><? if ($answers_id>0) echo '<i class="far fa-dot-circle blue size14"></i> ' ; echo $rec_answer['answer_text'] ;
                             //damp_array($rec_question['answers']);

                             ?></td>
                               <td style="width:200px;"><a href="<?echo $url?>" target="_blank"><?echo $rec_answer['cnt']?></a></td>
                               <td style="width:200px;"><? $proc=($rec_question['cnt_persons'])? $rec_answer['cnt']/$rec_question['cnt_persons']*100:0 ;
                                                           echo round($proc,2).'%'  ;
                                    ?>
                               </td>
                             <?
                             if (!$row)
                                {?><td rowspan="<?echo _sizeof($rec_question['answers'])?>">
                                    <? $report_obj=($rec_question['answer_type']==2)? new report_poll_section_stats_pie2d():new report_poll_section_stats_angulargauge();;
                                       $report_obj->no_view_title=1;
                                       $report_obj->filter['question_id']=$question_id;
                                       $report_obj->view_as_HTML();
                                    ?>
                                   </td><?
                                }
                             $i++ ; $row++ ;
                             echo '</tr>' ;
                             if (_sizeof($this->stats2[$answers_id])) {?><tr><td colspan="3"><?$this->table_stats_new($this->stats2[$answers_id],$arr_answers_ball_cnt) ;?></td></tr><?}
                         }
                     ?>
                 <?
             }
           ?></table><?
     //damp_array($stats);
   }


}
