<?php
class report_personals_score extends c_report
{
 var $title='Сердечно-сосудистый риск у сотрудников (SCORE)' ;
 var $view_by_space_filter=1 ;
 var $allow_org_ids=1 ;
 var $usl_select_org='' ;
    var $allow_export_to_csv=1 ;
    var $group_ids=0 ;

    function init($options=array())
    {
       // if (!$this->filter['group_id']) $this->filter['group_id']=MEMBER()->cur_group_id ;
    }

 function setting($options=array())
 {   if (!is_array($options['disabled_filter'])) $options['disabled_filter']=array() ;
     //$usl_groups=(MEMBER()->rol>2 and MEMBER()->cur_group_id!=113)? ' and group_id in ('.ACCOUNTS()->tree[MEMBER()->cur_group_id]->get_list_child().') ':'';
     //$recs_orgs=execSQL('select * from obj_site_personals where parent=1 and clss=207 '.$usl_groups.' order by obj_name') ;

     $arr_groups=ACCOUNTS()->get_arr_groups_to_cur_account() ;
     $arr_orgs_ids=PERSONAL()->get_arr_orgs_to_cur_account('',array('view_disabled'=>$this->filter['status'])) ;
     $arr_otdel_ids=(_sizeof($this->filter['org_ids']))? PERSONAL()->get_arr_otdels_to_cur_account($this->filter['org_ids']):array() ;


     ?><div id="panel_filter">
             <form id="sky-form" class="sky-form"><input type="hidden" name="filter_dir" value="<?echo _CUR_REPORT_DIR?>">
                 <?if ($this->filter['ids']){?><input type=hidden name=filter[ids] value="(<?echo implode(';',array_keys($this->filter['ids']))?>)"><?}?>
                 <?if ($this->filter['client_ids']){?><input type=hidden name=filter[client_ids] value="(<?echo implode(';',array_keys($this->filter['client_ids']))?>)"><?}?>
                 <?if ($this->filter['client_id']){?><input type=hidden name=filter[client_id] value="<?echo $this->filter['client_id']?>"><?}?>
                  <fieldset>
                      <div class="row">
                          <? $this->filter_section_select('group_id',$GLOBALS['LS_person_group_title'].':',2,$arr_groups) ;
                             $this->filter_section_select_multiple('org_ids','Организация:',2,$arr_orgs_ids) ;
                             $this->filter_section_select_multiple('otdel_ids','Подразделение:',2,$arr_otdel_ids) ;
                          ?>
                      </div>
                      <div class="row">
                          <? $this->filter_section_input_text('name','ФИО:',4,array('auto_complete'=>"autocomplette_personal_name")) ;
                             $this->filter_section_input_text('propusk','Пропуск:',2) ;
                             $this->filter_section_input_text('tab_number','Таб.номер:',2) ;
                             $this->filter_section_input_text('score_from','Мин.значение SCORE:',2) ;
                          ?>
                        </div>
                  </fieldset>
                  <?$this->panel_buttons();?>
              </form>
       </div><br>
     <?
  }



  function create_usl_select_obj($_params=array(),&$options=array())
  {  //damp_array($this->filter,1,-1) ;
     $usl=array() ;
     $usl[]='clss=211' ;
     if ($this->filter['group_id'])
     { $rec_group=ACCOUNTS()->get_workgroup_by_id($this->filter['group_id']) ;
       if (_sizeof($rec_group['_settings']['personal']['filter']))  $usl['group_personal_filter']=$rec_group['_settings']['personal']['usl_select'] ;
     }
     if (MEMBER()->personal_viewer_name) $usl[]='pkey in (select pkey from '.MEMBER()->personal_viewer_name.')' ;


     if ($this->filter['name'])              $usl[]='obj_name like "'.$this->filter['name'].'%"' ;
     if ($this->filter['tab_number'])              $usl[]='tab_number="'.$this->filter['tab_number'].'"' ;
     if ($this->filter['client_id'])         $usl[]='client_id="'.$this->filter['client_id'].'"' ;
     if ($this->filter['client_ids'])         $usl[]='client_id in ('.$this->filter['client_ids'].')' ;

     if ($this->filter['org_ids'])          $usl[]='parent2 in ('.implode(',',array_keys($this->filter['org_ids'])).')' ;
     if ($this->filter['otdel_ids'])        $usl[]='parent3 in ('.implode(',',array_keys($this->filter['otdel_ids'])).')' ;

     if ($this->filter['dep_id'])
     {  $cur_level=execSQL_value('select level from obj_site_personals where pkey='.$this->filter['dep_id']) ;
        $usl[]='parent'.$cur_level.'='.$this->filter['dep_id'] ;
     }
     if ($this->filter['dep_ids'])       $usl[]='parent2 in ('.implode(',',array_keys($this->filter['dep_ids'])).')' ;
     if ($this->filter['org_id'])        $usl[]='_org_id="'.$this->filter['org_id'].'"' ;
     if ($this->filter['otdel_id'])      $usl[]='_otdel_id in ('.$this->filter['otdel_id'].')' ;
     if ($this->filter['org_ids'])       $_usl[]='personal_parent2 in ('.implode(',',array_keys($this->filter['org_ids'])).')' ;
     if ($this->filter['otdel_ids'])     $_usl[]='personal_parent3 in ('.implode(',',array_keys($this->filter['otdel_ids'])).')' ;
     if ($this->filter['uid'])           $usl[]='uid='.$this->filter['uid'] ;
     if ($this->filter['ids'])           $usl[]='pkey in ('.implode(',',array_keys($this->filter['ids'])).')' ;
     if ($this->filter['propusk'])          $usl[]='propusk="'.$this->filter['propusk'].'"' ;
     if ($this->filter['working_id'])          $usl[]='working="'.$this->filter['working_id'].'"' ;
     if ($this->filter['working'])          $usl[]='working="'.$this->filter['working'].'"' ;
     if (!$this->filter['status'])          $usl[]='enabled=1' ;
     else if ($this->filter['status']==1)   $usl[]='(enabled=0 or enabled is null)' ;
     if ($this->filter['ext']==1)          $usl[]='ext=1' ; else $usl[]='(ext=0 or ext is null)' ;
     // выбор сотрудников по ID группы
     if ($this->filter['personal_ids'])    $usl[]='pkey in ('.$this->filter['personal_ids'].')' ;
     if ($this->filter['score_from'])      $usl[]='score>='.$this->filter['score_from'] ;

     //if ($this->filter['fired'])           $_usl[]='enabled=0'; else  $_usl[]='enabled=1';

     if ($this->filter['smena']=='cur')
     {   $_usl_smena=array() ;
         $_usl_smena[]='c_data>='.$this->smena_interval['cur']['from'] ;
         $_usl_smena[]='c_data<='.$this->smena_interval['cur']['to'] ;
         if ($this->mo_terminal_group) $_usl_smena[]='group_id in ('.ACCOUNTS()->tree[$this->mo_terminal_group]->get_list_child().')' ;
         if ($this->mo_otdel_ids) $_usl_smena[]='member_parent in ('.implode(',',$this->mo_otdel_ids).')' ;
         $usl_smena=implode(' and ',$_usl_smena) ;
         $personal_ids=execSQL_line('select distinct(member_id) from '.ESMO()->view_mo_session.' where '.$usl_smena) ;
         if (_sizeof($personal_ids)) $usl[]='pkey in ('.implode(',',$personal_ids).')' ;
         else                       $usl[]='pkey=0' ; // чтобы нечего не было показано если сотрудников в смене нет


     }
    //damp_array($this->smena_interval) ;

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

 function get_arr_info_filters()
 { $info=parent::get_arr_info_filters() ;
   if ($this->filter['status']==1)                      $info['статус']='"уволенные"' ;
   else if ($this->filter['status']==2)                 $info['статус']='"все"' ;
   if ($this->filter['ext']==1)                         $info['Доп.списки']='Да' ;
   if ($this->filter['score_from'])                     $info['Мин.значение SCORE']=$this->filter['score_from'] ;
   if (MEMBER()->setting['personal']['usl_select'])     $info[MEMBER()->setting['personal']['name']]=strip_tags(MEMBER()->setting['personal']['info_filter']);
   //damp_array(MEMBER()->setting['personal']) ;
   return $info ;
 }

  function get_cnt_items($usl,$options=array())
  {  // !!! использовать  PERSONAL()->table_personal так как вьювер жутко тупит
     $cnt=execSQL_value('select count(pkey)
                        from  '.PERSONAL()->table_personal.'
                        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 obj_name' ;
    //echo $usl ;
 	$list_rec=execSQL('select *,(select round(avg(systolic)) from obj_site_mo_session t2 where t2.member_id=t1.pkey and t2.model>0) as systolic
                       from  view_personals t1
                       where '.$usl.$order.$limit,$options) ;
    //if (_sizeof($list_rec)) foreach($list_rec as $id=>$rec) PERSONAL()->prepare_public_info_to_personal($list_rec[$id],$options) ;
    return($list_rec) ;
  }


// шаблон - вывод ссылками без разделитея
  function print_template_HTML($list_recs,$options=array())
  { $id=($options['id'])? 'id='.$options['id']:'' ;
    ?><table class="list_personal_table_img basic fz_small full auto"<?echo $id?>>
        <colgroup><col id="c1"><col id="c2"><col id="c3"><col id="c4"></colgroup>
        <tr><th>UID</th><th>Пол</th><th>ФИО</th><th>Дата рождения</th><th>Возраст</th><th>Курит</th><th>Холестерин</th><th>Ср.давление</th><th>Организация</th><th>Подразделение</th><th>Должность</th><th>SCORE</th>
        </tr><? ;
        if (_sizeof($list_recs)) foreach($list_recs as $rec)
        {   $rec['__href_window']='/window/personal/person/'.$rec['pkey'].'/' ;
            ?><tr class=item>
                <td><?echo ($rec['uid'])? $rec['uid']:$rec['pkey']?></td>
                <td><?echo ($rec['pol'])? 'Ж':'М'?></td>
                <td class="left"><a href="<?echo $rec['__href_window']?>" class="new_window" target="_blank" title="win_second"><?echo $rec['obj_name']?></a>
                    <br><?echo '<span class="nowrap small">'.$rec['uid'].'</span>'?>
                    <?if (!$rec['enabled'])echo '<br><br><span class="red bold">УВОЛЕН</span> ('.date('d.m.Y H:i',$rec['fired_data']).')'?>
                </td>
                <td class="dr"><?echo $rec['dr']?></td>
                <td class="age"><?echo $rec['age']?></td>
                <td><?echo ($rec['smoking'])? 'Да':'-'?></td>
                <td><?echo ($rec['hol'])? $rec['hol']:'-'?></td>
                <td><?echo ($rec['systolic'])? $rec['systolic']:'-'?></td>
                <td class="left"><?echo $rec['_org_name']?></td>
                <td class="left"><?echo $rec['_otdel_name']?></td>
                <td class="left"><?echo _IL('IL_works')->recs[$rec['working']]['obj_name']?></td>
                <td><?echo $rec['score']?></td>
            </tr><?
        }
      ?></table><?
      //damp_array($rec) ;
  }


  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['Пропуск']=$rec['propusk']  ;
            $data['GUID']=$rec['uid']  ;
    	    $data['ФИО']=$rec['obj_name']  ;
            $data['Дата рождения']=$rec['dr']  ;
            $data['Возраст']=$rec['age']  ;
    	    $data['Организация']=$rec['_org_name'] ;
    	    $data['Подразделение']=$rec['_otdel_name'] ;
    	    $data['Должность']= _IL('IL_works')->recs[$rec['working']]['obj_name'] ;
            $data['Уволен']=($rec['enabled'])? '':'Да' ;
            // вносим данные в csv
            $this->put_data_to_CSV($data,$i) ;
    	    $i++ ;
	}

     }



    function print_template_XML($list_recs,$options=array())
    { if (_sizeof($list_recs)) foreach($list_recs as $rec)
      {   $item=add_element($this->xml_doc,$this->xml,'item','',array('id'=>$rec['pkey'])) ;
          add_element($this->xml_doc,$item,'propusk',$rec['propusk']) ;
          add_element($this->xml_doc,$item,'tabnumber',$rec['tabnumber']) ;
          add_element($this->xml_doc,$item,'photo',($rec['_image_name'])? img_clone($rec,'source'):'') ;
          add_element($this->xml_doc,$item,'fio',$rec['obj_name']) ;
          add_element($this->xml_doc,$item,'uid',$rec['uid']) ;
          add_element($this->xml_doc,$item,'enabled',($rec['enabled'])? 1:0) ;
          add_element($this->xml_doc,$item,'dr',$rec['dr']) ;
          add_element($this->xml_doc,$item,'age',$rec['age']) ;
          add_element($this->xml_doc,$item,'phone',$rec['phone']) ;
          add_element($this->xml_doc,$item,'org_name',$rec['_org_name']) ;
          add_element($this->xml_doc,$item,'otdel_name',$rec['_otdel_name']) ;
          //add_element($this->xml_doc,$item,'org_id',$rec['_org_id']) ;
          //add_element($this->xml_doc,$item,'otdel_id',$rec['_otdel_id']) ;
          add_element($this->xml_doc,$item,'working',_IL('IL_works')->recs[$rec['working']]['obj_name']) ;
      }
    }

    function print_template_JSON($list_recs,$options=array())
       { $result=array() ;
         if (_sizeof($list_recs)) foreach($list_recs as $rec)
           $result[]=array('propusk'=>$rec['propusk'],
                           'photo'=>($rec['_image_name'])? img_clone($rec,'source'):'',
                           'fio'=>$rec['obj_name'],
                           'uid'=>$rec['uid'],
                           'enabled'=>($rec['enabled'])? 1:0,
                           'dr'=>$rec['dr'],
                           'age'=>$rec['age'],
                           'org_name'=>$rec['_org_name'],
                           'otdel_name'=>$rec['_otdel_name'],
                           'org_id'=>$rec['_org_id'],
                           'otdel_id'=>$rec['_otdel_id'],
                           'working'=>_IL('IL_works')->recs[$rec['working']]['obj_name']
                          ) ;
           $text_json_out=json_encode($result) ;
           // возвращает ответ устройству
           echo $text_json_out ;

       }

    function manual_tags_in()
    {
        ?><table class="basic fz_normal left">
                    <tr><td>uid</td><td>Уникальный идентификатор сотрудника</td></tr>
                    <tr><td>name</td><td>ФИО</td></tr>
                    <tr><td>org_id</td><td>ID организации</td></tr>
                    <tr><td>otdel_id</td><td>ID отдела</td></tr>
                    <tr><td>propusk</td><td>Номер пропуска</td></tr>
                    <tr><td>status</td><td>по умолчанию - только активные, 1 - уволенные, 2 - все</td></tr>
        </table><?
    }

    function manual_tags_out()
    {
        ?><table class="basic fz_normal left">
                    <tr><td>photo</td><td>url фото</td></tr>
                    <tr><td>fio</td><td>ФИО сотрудника</td></tr>
                    <tr><td>uid</td><td>Ваш уникальный идентификатор сотрудника.</td></tr>
                    <tr><td>fio</td><td>ФИО сотрудника</td></tr>
                    <tr><td>phone</td><td>Телефон сотрудника</td></tr>
                    <tr><td>propusk</td><td>Номер пропуска</td></tr>
                    <tr><td>tabnumber</td><td>Табельный номер</td></tr>
                    <tr><td>enabled</td><td>Состояние, 0 - заблокирован, 1-активный</td></tr>
                    <tr><td>dr</td><td>Дата рождения сотрудника, формат ДД.ММ.ГГГГ</td></tr>
                    <tr><td>pol</td><td>Пол сотрудника, 0=М, 1=Ж</td></tr>
                    <tr><td>org_name</td><td>Название организации сотрудника</td></tr>
                    <tr><td>otdel_name</td><td>Название подразделения организации</td></tr>
                    <tr><td>working</td><td>Должность</td></tr>
          </table><?
    }




}

?>
