<?php
class report_poll_results extends c_report
{
 var $title='Прохождение опроса' ;
 var $view_by_space_filter=1 ;
 var $event_id=0 ;
 var $personal_id=0 ;
 var $rec_lession=array() ;
 var $rec_event=array() ;
 var $event_ext=array() ;
 var $allow_export_to_csv=1 ;
 var $section_id=0 ;
 var $question_id=0 ;
 var $rec_question=[] ;
 var $rec_section=[] ;
 var $arr_poll_themes=[] ;

 function init()
 {
     if ($this->section_id) $this->rec_section=POLL()->get_theme_by_id($this->section_id) ;
     if ($this->question_id) $this->rec_question=POLL()->get_question_by_id($this->question_id) ;
     $this->arr_poll_themes=TREE('poll_themes')->get_list_strukture('clss in (1,572)',null,1,['parent_id'=>1]);
 }

 function setting($options=array())
 {

       if ($this->personal_id)   $usl_select_results='t1.personal_id='.$this->personal_id ;
      else if ($this->event_id) $usl_select_results='t1.event_id='.$this->event_id ;
      else                      $usl_select_results=1 ;
      /*$arr_events=execSQL('select distinct(t1.event_id) as event_id,t2.pkey as event_pkey,t2.obj_name
                           from poll_result t1
                           left join obj_site_events_schedule t2 on t2.pkey=t1.event_id
                           where not t2.pkey is null and '.$usl_select_results) ;
       */
      $_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 ;
     $usl_theme_select=(_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_tree t2 on t2.pkey=t1.question_id
                          left join view_poll_tree t3 on t3.pkey=t2.parent
                          left join poll_themes t4 on t4.pkey=t3.parent2
                          where '.$usl_theme_select.'
                          group by t4.pkey,t3.pkey
                          order by t4.indx,t3.pkey
                          ',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'] ;
      }
     */
      //$arr_groups=ACCOUNTS()->get_arr_groups_to_cur_account() ;
      //echo _CUR_REPORT_DIR ;

    $this->form_open() ;

    if (!$this->personal_id)
    { $this->row_open() ;

      list($arr_orgs_ids,$arr_otdel_ids,$arr_works_ids)=PERSONAL()->get_org_otdels_works_to_cur_account($this->filter,['filter_reffer'=>$this->rec_event['_reffer']]) ;

      $this->filter_section_input_text('name','ФИО:',2,array('auto_complete'=>"autocomplette_personal_name")) ;
      $this->filter_section_select_multiple('org_ids','Организация:',4,$arr_orgs_ids) ;
      $this->filter_section_select_multiple('otdel_ids','Подразделение:',4,$arr_otdel_ids) ;
      $this->filter_section_select_multiple('working_ids','Должность:',2,$arr_works_ids) ;
      $this->row_close() ;
    }

    $this->row_open() ;
    //if (!$this->event_id) $this->filter_section_select('event_id','Мероприятие:',2,$arr_events) ;
    //$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']]) ;
    $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->panel_buttons() ;
    $this->form_close() ;

  }

	function setting_for_question($options=array())
	{
       //damp_array($this->filter);
       if ($this->filter['dep_id'])
       {  $rec_dep=PERSONAL()->get_org_by_id($this->filter['dep_id']) ;
          $this->filter['org_ids'][$rec_dep['parent2']]=1 ;
          if ($rec_dep['level']>2) $this->filter['otdel_ids'][$rec_dep['pkey']]=1 ;
       //damp_array($rec_dep);
       }
       if ($this->filter['answer_id']>0) $this->filter['answer_ids'][$this->filter['answer_id']]=1 ;
       if ( $this->filter['answer_id']==-1) $this->filter['answer_ids'][-1]=1 ;


	    if ($this->rec_question['answer_type']==2) $arr_answers=execSQL_row('select pkey,obj_name from poll_answers where question_id='.$this->question_id) ;
	    else $arr_answers=[1=>'1 балл',2=>'2 балла',3=>'3 балла',4=>'4 балла',5=>'5 баллов'] ;
        $arr_answers[-1]='Уклонился от ответа' ;
        //$arr_answers[-2]='Еще не проходил опрос' ;

	    // применение _filter_reffer в данном случае некорректно, так как массив IDs сотрудников не содержимся во вьювере мероприятия
	    list($arr_orgs_ids,$arr_otdel_ids,$arr_works_ids)=PERSONAL()->get_org_otdels_works_to_cur_account($this->filter,['_filter_reffer'=>$this->rec_event['_reffer']]);

	    $this->form_open();
		$this->row_open();
		$this->filter_section_input_text('name','ФИО:',2,array('auto_complete'=>"autocomplette_personal_name"));
		$this->filter_section_select_multiple('org_ids','Организация:',4,$arr_orgs_ids);
		$this->filter_section_select_multiple('otdel_ids','Подразделение:',4,$arr_otdel_ids);
		$this->filter_section_select_multiple('working_ids','Должность:',2,$arr_works_ids);
		$this->row_close();
		$this->row_open();
        if ($this->rec_question['answer_type']==2) $this->filter_section_select_multiple('answer_ids','Ответ:',2,$arr_answers);
        else                                       $this->filter_section_select_multiple('answer_balls','Оценка:',2,$arr_answers);
		$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->panel_buttons();
		$this->form_close();
	}

  function create_usl_select_obj($_params,&$options)
  {  //
     $usl=array() ;
     $usl[]='not MPS.pkey is null' ;
     if ($this->event_id) $usl[]='t1.event_id='.$this->event_id ;
     if ($this->personal_id) $usl[]='t1.personal_id='.$this->personal_id ;
      //damp_array($this) ;
     //if ($this->event_id and $this->rec_event['_ext_info']['usl_select']) $usl[]=$this->rec_event['_ext_info']['usl_select'] ;

     if ($this->question_id)               $usl[]='t1.question_id='.$this->question_id ;
     if ($this->section_id)                $usl[]='t3.parent'.$this->rec_section['level'].'='.$this->rec_section['pkey'] ;
     if ($this->filter['personal_id'])     $usl[]='t2.pkey='.$this->filter['personal_id'] ;
     if ($this->filter['name'])            $usl[]='t2.obj_name like "%'.$this->filter['name'].'%"' ;
     if ($this->filter['org_ids'])         $usl[]='t2.parent2 in ('.implode(',',array_keys($this->filter['org_ids'])).')' ;
     if ($this->filter['otdel_ids'])       $usl[]='(t2.parent3 in ('.implode(',',array_keys($this->filter['otdel_ids'])).') or 
                                                    t2.parent4 in ('.implode(',',array_keys($this->filter['otdel_ids'])).') or
                                                    t2.parent5 in ('.implode(',',array_keys($this->filter['otdel_ids'])).') or
                                                    t2.parent6 in ('.implode(',',array_keys($this->filter['otdel_ids'])).') or
                                                    t2.parent7 in ('.implode(',',array_keys($this->filter['otdel_ids'])).') 
                                                    )' ;
     if (_sizeof($this->filter['working_ids'])) $usl[]='working in ('.implode(',',array_keys($this->filter['working_ids'])).')' ;
     if ($this->filter['data_from'])       $usl[]='t1.c_data>='.strtotime($this->filter['data_from']) ;
     if ($this->filter['data_to'])         $usl[]='t1.c_data<='.strtotime($this->filter['data_to']) ;


     if (_sizeof($this->filter['answer_ids']))
      {   $arr2=[] ;
          foreach($this->filter['answer_ids'] as $answer_id=>$tt)
          {  if ($answer_id>0) $arr2[]=$answer_id ;
             else if ($answer_id==-1) $arr2[]=0 ;
          }
          if (_sizeof($arr2)) $usl[]='t1.answer_id in ('.implode(',',$arr2).')' ;
      }
     //damp_array($this->filter);
     if (isset($this->filter['answer_balls'][-1]))
     {
         unset($this->filter['answer_balls'][-1]) ;
       $this->filter['answer_balls'][0]=1 ;
     }
     if (_sizeof($this->filter['answer_balls'])) $usl[]='t1.answer_ball in ('.implode(',',array_keys($this->filter['answer_balls'])).')' ;

      if ($this->filter['theme_id'])
      {   $questions_ids=[] ;
          if (!_sizeof($this->filter['section_ids'])) $section_ids=execSQL_line('select pkey as id from poll_themes where parent2='.$this->filter['theme_id'].' ') ;
          else                                       $section_ids=array_keys($this->filter['section_ids']) ;
          if (_sizeof($section_ids)) $questions_ids=execSQL_line('select pkey as id from poll_questions where parent in ('.implode(',',$section_ids).')') ;
          if (_sizeof($questions_ids)) $usl[]='t1.question_id in ('.implode(',',$questions_ids).')';
      }

      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']) ;




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

 function panel_info_filter()
 { $_str=array() ; $title='' ;
   $info=$this->get_arr_info_filters() ;
   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'])));

   if (_sizeof($this->filter['answer_ids']))
       {   $answers_names=execSQL_line('select obj_name from poll_answers where pkey in ('.implode(',',array_keys($this->filter['answer_ids'])).')') ;
           if (isset($this->filter['answer_ids'][-1])) $answers_names[]='Уклонился от ответа';
           //if ($this->filter['answer_ids'][-2]) $answers_names[]='Еще не отвечал';
           $info['Ответ']=implode(', ',$answers_names) ;
       }


   if (_sizeof($this->filter['answer_balls']))
       {
           $info['Балл  ответа']=implode(', ',array_keys($this->filter['answer_balls'])) ;
       }






   if (_sizeof($info)) foreach($info as $title=>$value) $_str[]=$title.': <strong>'.$value.'</strong>' ;
   if (_sizeof($_str)) $title='<div class=center>'.implode(' ',$_str).'</div>' ;
   return $title ;
   }




  function get_cnt_items($usl,$options=array())
  { //$options['debug']=2 ;
   /* сыро, надо охватить все варианты
   if ($this->filter['answer_ids'][-2]==1)
    { $viewer_name=POLL()->get_personal_viewer_name_to_poll_tree_item($this->rec_question) ;
      $cnt=execSQL_value('select count(t1.pkey)
                          from  '.$viewer_name.' t1
                          left join poll_result t5 on t5.pkey=t1.theme_id
                          left join '.MEMBER()->personal_viewer_name.' MPS on MPS.pkey=t1.pkey
                          where '.$usl.'
                          ',$options) ;
    }


    else*/
    { $cnt=execSQL_value('select count(t1.pkey)
                        from  poll_result t1
                        left join obj_site_personals pvn on pvn.pkey=t1.personal_id
                        left join view_personals t2 on t2.pkey=t1.personal_id 
                        left join view_poll_questions t3 on t3.pkey=t1.question_id 
                        left join '.MEMBER()->personal_viewer_name.' MPS on MPS.pkey=t1.personal_id
                        where '.$usl.'
                        
                        ',$options) ;

      $check=execSQL('select t1.personal_id,t1.question_id,count(t1.pkey) as cnt,t2.obj_name
                     from  poll_result t1
                     left join obj_site_personals pvn on pvn.pkey=t1.personal_id
                     left join view_personals t2 on t2.pkey=t1.personal_id 
                     left join view_poll_questions t3 on t3.pkey=t1.question_id 
                     left join '.MEMBER()->personal_viewer_name.' MPS on MPS.pkey=t1.personal_id
                     where '.$usl.'
                     group by t1.personal_id,t1.question_id
                     having cnt>1
      ') ;
      if (_sizeof($check))
        { echo '<div class=red>Внимание! В результатах запроса есть сотрудники, прошедних опрос несколько раз:</div>' ;
          ?><table class="basic fz_small auto"><tr><th>ID</th><th>ФИО</th><th>Число прохождений</th></tr><?
          foreach($check as $rec_check)
          { ?><tr>
                <td><?echo $rec_check['personal_id']?></td>
                <td><?echo $rec_check['obj_name']?></td>
                <td><?echo $rec_check['cnt']?></td>
              </tr><?
		  }
          ?></table><?

        }


    }
    return($cnt) ;

  }

  function get_items($usl,$options=array())
  { $limit=($options['limit'])? ' '.$options['limit']:'' ;
    //$options['debug']=2 ;
    $options['no_indx']=1 ;
    $order=($options['order'])? ' order by '.$options['order']:' order by t1.pkey desc' ;

    //left join '.MEMBER()->personal_viewer_name.' pvn on pvn.pkey=t1.personal_id
 	$list_recs=execSQL('select  
                        t2.*,
                        t1.pkey as poll_pkey,t1.c_data as poll_data,t1.poll_id,t1.mo_id,t1.event_id,t1.question_id,t1.answer_ball,t1.personal_id,
                        t3.obj_name as question_text,t3.parent as question_section_id,t3.answer_type,
                        t7.obj_name as event_name, 
                        t8.obj_name as answer_text 
                        from  poll_result t1
                        left join obj_site_personals pvn on pvn.pkey=t1.personal_id    
                        left join view_personals t2 on t2.pkey=t1.personal_id
                        left join view_poll_questions t3 on t3.pkey=t1.question_id 
                        left join obj_site_events_schedule t7 on t7.pkey=t1.event_id
                        left join poll_answers t8 on t8.pkey=t1.answer_id
                        left join '.MEMBER()->personal_viewer_name.' MPS on MPS.pkey=t1.personal_id
                        where '.$usl.' '.$order.$limit,$options) ;
 	// зачем тут group by t2.pkey????
    //print_2x_arr($list_recs) ;
    return($list_recs) ;
  }


// шаблон - вывод ссылками без разделитея
  function print_template_HTML($list_recs,$options=array())
  { //print_2x_arr($list_recs) ;
    $id=($options['id'])? 'id='.$options['id']:'' ;
    $i=1 ;
    include(_DIR_EXT.'/personal/panel_personal_info.php') ;

    ?><table class="basic fz_small full auto"<?echo $id?>>
        <tr><th>ID</th>
            <th>ID сессии опроса</th>
            <th>ID сессии МО</th>
            <th>Дата/время</th>
            <?if (!$this->event_id){?><th>Мероприятие</th><?}?>
            <?if (!$this->personal_id)
              {?><th>Сотрудник</th>
                 <th>Место работы</th>
                 <th>Должность</th>
               <?
              }?>
            <th>Тема/Раздел</th>
            <th>Вопрос</th>
            <th>Ответ/Оценка</th>
         </tr><?
         if (_sizeof($list_recs)) foreach($list_recs as $rec)
          {  $rec['__href_mo']='/cab/mo/'.$rec['mo_id'].'/' ;
             $rec['__href']='/cab/poll/session/'.$rec['poll_id'].'/' ;
             $rec['__href_window']='/window/personal/person/'.$rec['pkey'].'/' ;
              ?><tr>
                  <td><?echo $rec['pkey']?></td>
                  <td><a class="new_window"  target="_blank" title="win_second" href="<?echo $rec['__href']?>"><?echo $rec['poll_id']?></a></td>
                  <td><?if ($rec['mo_id']){?><a class="new_window"  target="_blank" title="win_second" href="<?echo $rec['__href_mo']?>"><?echo $rec['mo_id']?></a><?}?></td>
                  <td class="nowrap"><?echo date('d.m.Y H:i',$rec['poll_data'])?></td>
                  <?if (!$this->event_id){?><td><?echo $rec['event_name']?></td><?}?>
                  <?if (!$this->personal_id)
                  { ?><td class="left"><?panel_personal_info_small($rec)?></td>
                      <td class="left"><?echo '<strong>'.$rec['_org_name'].'</strong><br><div class="small">'.$rec['_otdel_name'].'</div>'?></td>
                      <td class="left"><?echo _IL('IL_works')->recs[$rec['working']]['obj_name']  ;
                                        if ($rec['working2']) echo '<br><strong>Совмещение: </strong>'._IL('IL_works')->recs[$rec['working2']]['obj_name'] ; ?>
                      </td>
                  <?}
                  ?>
                  <td class="left"><? echo $this->arr_poll_themes[$rec['question_section_id']]  ; ?></td>
                  <td class="left"><? echo $rec['question_text']?></td>
                  <td class="center"><? if ($rec['answer_type']==2) echo $rec['answer_text'] ;
                                        if ($rec['answer_type']==1) echo $rec['answer_ball'].' из 5' ;
                                     ?>
                  </td>
              </tr><?
              $i++;
          }
      ?></table><?
  }

  // шаблон - вывод ссылками без разделитея
  function print_template_HTML_for_question($list_recs,$options=array())
  { //print_2x_arr($list_recs) ;
    $id=($options['id'])? 'id='.$options['id']:'' ;
    $i=1 ;
    include(_DIR_EXT.'/personal/panel_personal_info.php') ;

    ?><table class="basic fz_small full auto"<?echo $id?>>
        <tr><th>ID</th>
            <th>Дата/время</th>
            <th>ID сессии опроса</th>
            <th>ID сессии МО</th>
            <th>Сотрудник</th>
            <th>Место работы</th>
            <th>Должность</th>
            <th>Вопрос</th>
            <th>Ответ/Оценка</th>
         </tr><?
         if (_sizeof($list_recs)) foreach($list_recs as $rec)
          {  $rec['__href_mo']='/cab/mo/'.$rec['mo_id'].'/' ;
             $rec['__href']='/cab/poll/session/'.$rec['poll_id'].'/' ;
             $rec['__href_window']='/window/personal/person/'.$rec['pkey'].'/' ;
              ?><tr>
                  <td><?echo $rec['pkey']?></td>
                  <td class="nowrap"><?echo date('d.m.Y H:i',$rec['poll_data'])?></td>
                  <td><a class="new_window"  target="_blank" title="win_second" href="<?echo $rec['__href']?>"><?echo $rec['poll_id']?></a></td>
                  <td><?if ($rec['mo_id']){?><a class="new_window"  target="_blank" title="win_second" href="<?echo $rec['__href_mo']?>"><?echo $rec['mo_id']?></a><?}?></td>

                 <td class="left"><?panel_personal_info_small($rec)?></td>
                 <td class="left"><?echo '<strong>'.$rec['_org_name'].'</strong><br><div class="small">'.$rec['_otdel_name'].'</div>'?></td>
                 <td class="left"><?echo _IL('IL_works')->recs[$rec['working']]['obj_name']  ;
                                    if ($rec['working2']) echo '<br><strong>Совмещение: </strong>'._IL('IL_works')->recs[$rec['working2']]['obj_name'] ;
                                  ?>
                 </td>
                 <td class="left"><? echo $rec['question_text']?></td>
                 <td class="center"><? if ($rec['answer_type']==2) echo $rec['answer_text'] ;
                                       if ($rec['answer_type']==1) echo $rec['answer_ball'].' из 5' ;
                                    ?>
                 </td>
              </tr><?
              $i++;
          }
      ?></table><?
  }

    function print_template_CSV($list_recs,$options=array())
          { $i=$options['from'] ;
            if (_sizeof($list_recs)) foreach($list_recs as $rec)
            {   $data=array() ;
        	    $data['№']=$i+1 ;
                $data['ID сессии опроса']=$rec['poll_pkey']  ;
                $data['ID сессии МО']=$rec['mo_id'] ;
                $data['Дата/время']=date('d.m.Y H:i',$rec['poll_data'])  ;

                $data['GUID сотрудника']=$rec['uid']  ;
                $data['ФИО сотрудника']=$rec['obj_name']  ;
                $data['Дата рождения']=$rec['dr']  ;
                $data['Возраст']=$rec['age']  ;
                $data['Пол']=($rec['pol'])? 'Женский':'Мужской'  ;
                $data['Организация']=$rec['_org_name'] ;
                $data['Подразделение']=$rec['_otdel_name'] ;
                $data['Должность']= _IL('IL_works')->recs[$rec['working']]['obj_name'] ;

                $data['Тема/Раздел']=$this->arr_poll_themes[$rec['question_section_id']]  ;
                $data['ID вопроса']=$rec['question_id']  ;
                $data['Вопрос']=$rec['question_text']  ;
                $data['Ответ']=($rec['answer_text'])? $rec['answer_text']:''  ;
                $data['Ответ (балл)']=($rec['answer_ball'])? $rec['answer_ball']:'';

                // вносим данные в csv
                $this->put_data_to_CSV($data,$i) ;
        	    $i++ ;
    	}

         }


}

?>
