<?php
include_once('report_personals.php') ;
class report_personals_dublicate extends report_personals
{
 var $title='Дубликаты сотрудников' ;
 var $view_by_space_filter=1 ;
 var $allow_org_ids=1 ;
 var $usl_select_org='' ;
 var $allow_export_to_csv=0 ;

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

       ?><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','Организация:',4,$arr_orgs_ids) ;
                               //$this->filter_section_select_multiple('otdel_ids','Подразделение:',4,$arr_otdel_ids) ;
                               //$this->filter_section_select_multiple('working_ids','Должность:',2,$arr_workd_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('uid','UID:',2) ;
                               //$this->filter_section_select('person_status','Дополнительный признак',2,$this->dop_props) ;
                            ?>
                          </div>
                    </fieldset>
                    <?$this->panel_buttons();?>
                </form>
         </div><br>
       <?
    }

function create_usl_select_obj($_params,&$options)
  {  //damp_array($this->filter,1,-1) ;
     $usl=array() ;
     $usl[]='clss=211' ;
     $usl[]='enabled=1' ;
     //$usl[]='concat(obj_name,dr) in (select concat(obj_name,dr)  from obj_site_personals group by concat(obj_name,dr) having count(pkey)>1)' ;

     if ($this->filter['name'])              $usl[]='obj_name like "'.$this->filter['name'].'%"' ;
     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['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['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' ;
     //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['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 panel_info_filter()
 { $_str=array() ; $info=array() ; $title='' ;
   //damp_array($this->filter) ;
   if ($this->filter['name'])                            $info['ФИО']='"'.$this->filter['name'].'"' ;
   if ($this->filter['client_id'])                       $info['клиент']=ACCOUNTS()->get_member_name_by_id($this->filter['client_id']) ;
   if ($this->filter['client_ids'])
   {   $arr=array() ;
       $recs_account=ACCOUNTS()->get_members_by_ids($this->filter['client_ids']) ;
       if (_sizeof($recs_account)) foreach($recs_account as $rec_account) $arr[]=$rec_account['obj_name'] ;
       $info['клиенты']=implode(', ',$arr) ;
   }
   if ($this->filter['org_id'])                          $info['организация']=PERSONAL()->get_name_by_id($this->filter['org_id']) ;
   //if ($this->filter['otdel_id'])                        $info['отдел']=PERSONAL()->get_name_by_id($this->filter['otdel_id']) ;
   if ($this->filter['otdel_id'])
   {   $arr=explode(',',$this->filter['otdel_id']) ;
       $arr2=array() ;
       foreach($arr as $otdel_id) $arr2[]=PERSONAL()->get_name_by_id($otdel_id) ;
       $info['отдел']=implode(', ',$arr2);
   }
   if ($this->filter['dep_id'])                          $info['Подразделение']=PERSONAL()->get_full_dep_name_by_dep_id($this->filter['dep_id'])  ;
   if ($this->filter['dep_ids'])                          $info['Подразделениz']=PERSONAL()->get_org_names_by_ids(array_keys($this->filter['dep_ids']))  ;
   if ($this->filter['working'])                         $info['должность']=_IL('IL_works')->recs[$this->filter['working']]['obj_name'];
   if ($this->filter['working_id'])                         $info['должность']=_IL('IL_works')->recs[$this->filter['working_id']]['obj_name'];
   if ($this->filter['uid'])                             $info['UID сотрудника']='"'.$this->filter['uid'].'"' ;
   if ($this->filter['propusk'])                         $info['номер пропуска']='"'.$this->filter['propusk'].'"' ;
   if ($this->filter['status']==1)                       $info['статус']='"уволенные"' ;
   else if ($this->filter['status']==2)                  $info['статус']='"все"' ;
   if ($this->filter['ext']==1)                          $info['Доп.списки']='Да' ;
   if ($this->filter['smena']=='cur')                    $info['Смена']='Текущяя' ;
   if ($this->filter['smena']=='prev')                   $info['Смена']='Предыдущая' ;

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


  function get_cnt_items($usl,$options=array())
  {  // !!! использовать  PERSONAL()->table_personal так как вьювер жутко тупит
      $options['debug']=2 ;
     /*$cnt=execSQL_value('select count(pkey)
                        from  '.PERSONAL()->table_personal.'
                        where '.$usl,$options) ;
       */
      // удяляем пробелмы в начале и конце ФИО
      //execSQL_update('UPDATE obj_site_personals SET obj_name=ltrim(obj_name)') ;
      //execSQL_update('UPDATE obj_site_personals SET obj_name=rtrim(obj_name)') ;
      //execSQL_update('ALTER TABLE obj_site_personals ADD INDEX name_dr (obj_name(128), dr(10))') ;

      /*execSQL_update('drop table temp11') ;
      execSQL_update('create table temp11 select obj_name,dr,count(pkey) as cnt
                     from obj_site_personals
                     group by concat(obj_name,dr)
                     having count(pkey)>1
                     ',2) ;

      execSQL('select t1.*
               from obj_site_personals t1,temp11 tmp
               where tmp.obj_name=t1.obj_name and tmp.dr=t1.dr
               order by obj_name,dr
               ',2) ;
        */

      execSQL_update('drop IF EXISTS table temp11') ;
      execSQL_update('create table temp11 select propusk,count(pkey) as cnt  
                     from obj_site_personals 
                     group by propusk 
                     having count(pkey)>1 
                     ',2) ;

      execSQL('select t1.* 
               from obj_site_personals t1,temp11 tmp
               where tmp.propusk=t1.propusk
               order by propusk,obj_name,dr 
               ',2) ;

      foreach($recs as $rec)
      {
        //  $dubl=execSQL()
      }
      /*
       *
       *
      $recs=execSQL('select pkey,c_data,obj_name,dr,propusk,uid
                     from obj_site_personals
                     where concat(obj_name,dr) in (select concat(obj_name,dr)
                                                   from obj_site_personals
                                                   group by concat(obj_name,dr)
                                                   having count(pkey)>1)
                     order by obj_name,dr desc',2) ;

      $recs=execSQL('select * from obj_site_personals where obj_name="Сотрудник 10006"',2) ;
       */

    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 ;
      $options['debug']=2 ;
 	$list_rec=execSQL('select *
                       from  view_personal_mo
                       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><?if ($options['chech_check']){?><th>Выбор</th><?}?><th>Пропуск</th><th>Фото</th><th>ФИО</th><th>Дата рождения</th><th>Возраст</th><th>Организация<br>Подразделение<br>Должность</th><th>Дата добавления</th><th>Первый МО</th><th>Последний МО</th><th>Число МО</th></tr><? ;
        if (_sizeof($list_recs)) foreach($list_recs as $rec)
        { ?><tr class=item>
                <?if ($options['chech_check']){?><td><input type="checkbox" name="_check[]" value="<?echo $rec['_reffer']?>"></td><?}?>
                <td class="id"><?echo $rec['propusk']?><?if ($rec['demo_access']){?><div class="demo_access" title="Сотрудник может проходить неограниченное число МО"></div><?}?></td>
                <td class="img"><a  href="<?echo $rec['__href_window']?>" class="new_window" target="_blank" title="win_second"><img src="<?echo img_clone($rec,'small')?>"></a></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 class="left"><?echo $rec['_org_name']?><br><?echo $rec['_otdel_name']?><br><?echo _IL('IL_works')->recs[$rec['working']]['obj_name']?></td>
                <td><?echo date('d.m.Y H:i',$rec['c_data'])?></td>
                <td><?echo ($rec['first_mo'])? date('d.m.Y',$rec['first_mo']):'-'?></td>
                <td><?echo ($rec['last_mo'])? date('d.m.Y',$rec['last_mo']):'-'?></td>
                <td><?echo ($rec['cnt_mo'])? $rec['cnt_mo']:'-'?></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['Табельный номер']=$rec['tabnumber']  ;
    	    $data['ФИО']=$rec['obj_name']  ;
            $data['UID']=$rec['uid']  ;
            $data['Дата рождения']=$rec['dr']  ;

            $data['Возраст']=$rec['age']  ;
    	    $data['Организация']=$rec['_org_name'] ;
    	    $data['Подразделение']=$rec['_otdel_name'] ;
            $data['Должность']=$rec['_work_name'] ;
            // вносим данные в 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><?
    }




}

?>
