<?php
class report_personal_messages extends c_report
{
 var $title='Сообщения сотрудникам' ;
 var $view_by_space_filter=1 ;
 var $allow_org_ids=1 ;
 var $usl_select_org='' ;
 public $use_datepicker=1 ;
 public $arr_autors=[] ;
 var $allow_export_to_csv=1 ;
 var $report_script=__FILE__ ;

 var $arr_props=array('not_block'=>'Без ограничений по МО') ;

 function setting($options=array())
    {   //if ($this->filter['personal_id'] and !$this->filter['name']) $this->filter['name']=PERSONAL()->get_name_by_id($this->filter['personal_id']) ;
        $usl=[] ;
        $usl[]='account_id>0' ;
        if (MEMBER()->personal_viewer_name) $usl['account_personal_filter']='personal_id in (select pkey from '.MEMBER()->personal_viewer_name.')' ;

        $usl_select_accunts=(_sizeof($usl))? 'where '.implode(' and ',$usl):'' ;

        $this->arr_autors=execSQL_row('select distinct(account_id),account_name from view_personals_messages '.$usl_select_accunts) ;
        ?><div id="panel_filter">
                <form id="sky-form" class="sky-form"><input type="hidden" name="filter_dir" value="<?echo _CUR_REPORT_DIR?>">
                     <fieldset>
                         <?
                         $this->filter_section_input_text('name','ФИО сотрудника:',2,array('auto_complete'=>"autocomplette_personal_name")) ;
                         $this->filter_section_input_text('personal_id','ID сотрудника:',2) ;
                         $this->filter_section_input_text('propusk','Пропуск:',2) ;
                         $this->filter_section_select('status','Статус сообщения',2,$_SESSION['ARR_mess_status']) ;
                         $this->filter_section_select_multiple('props','Отбор сообщений',2,$this->arr_props) ;
                         $this->filter_section_select_multiple('account_ids','Автор сообщений',2,$this->arr_autors) ;
                         ?>
                     </fieldset>
                     <?$this->panel_buttons();?>
                 </form>
          </div><br>
        <?
     }


    function setting_small($options=array())
    {   //if ($this->filter['personal_id'] and !$this->filter['name']) $this->filter['name']=PERSONAL()->get_name_by_id($this->filter['personal_id']) ;
        ?><div id="panel_filter">
                <form id="sky-form" class="sky-form"><input type="hidden" name="filter_dir" value="<?echo _CUR_REPORT_DIR?>">
                     <fieldset>
                         <?
                         $this->filter_section_select('status','Статус сообщения',2,$_SESSION['ARR_mess_status']) ;
                         ?>
                     </fieldset>
                     <?$this->panel_button_apply();?>
                 </form>
          </div><br>
        <?
     }

  function create_usl_select_obj($_params,&$options)
  {  //damp_array($this->filter,1,-1) ;
     $usl=array() ;
     $usl[]='clss=217' ;
     $usl[]='source_obj!="esmo_magnit_pmo/i_event_pmo"' ;
     $usl[]='source_obj!="events_opo/i_event_opo"' ;
     if ($this->ids)              $usl[]='pkey in ('.$this->ids.')' ;
     if ($this->filter['name'])              $usl[]='_personal_name like "'.$this->filter['name'].'%"' ;
     if ($this->filter['personal_id'])       $usl[]='personal_id='.$this->filter['personal_id'].'' ;
     if (_sizeof($this->filter['account_ids']))       $usl[]='account_id in ('.implode(',',array_keys($this->filter['account_ids'])).')' ;
     //if ($this->filter['client_id'])         $usl[]='client_id="'.$this->filter['client_id'].'"' ;
     //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['propusk'])          $usl[]='propusk="'.$this->filter['propusk'].'"' ;
     //if ($this->filter['working'])          $usl[]='working="'.$this->filter['working'].'"' ;

     if ($this->filter['status'])
     { if ($this->filter['status']!=4)         $usl[]='(status='.$this->filter['status'].' and enabled=1)' ;
       if ($this->filter['status']==4)         $usl[]='(status='.$this->filter['status'].' or enabled=0)' ;
     }
     else if (!$options['view_all_status'])  $usl[]='(status in (0,1,2,3,5) and enabled=1)' ; //  по умалчанию не показываем закрытые сообщения

     if ($this->filter['props']['not_block']) $usl[]='(block_from=0 and block_to=0)' ;

     //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)' ;
     //if ($this->filter['fired'])           $_usl[]='enabled=0'; else  $_usl[]='enabled=1';
      //damp_array($this->smena_interval) ;

      // применяем фильтры по выборке персонала к вьюверу на сообщения
      if (MEMBER()->personal_viewer_name) $usl['account_personal_filter']='personal_id in (select pkey from '.MEMBER()->personal_viewer_name.')' ;


     $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['personal_id'])                     $info['ФИО']='"'.PERSONAL()->get_name_by_id($this->filter['personal_id']).'"' ;
   //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 (_sizeof($this->filter['account_ids']))
   {
       $arr=ACCOUNTS()->get_names_by_ids(array_keys($this->filter['account_ids'])) ;
       $info['Автор сообщений']=implode(',',$arr) ;

   }
   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['propusk'])                         $info['номер пропуска']='"'.$this->filter['propusk'].'"' ;

   if ($this->filter['props']['not_block'])                 $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())
  { $cnt=execSQL_value('select count(pkey)
                        from  view_personals_messages
                        where '.$usl,$options) ;
    if ($this->filter['personal_id'] and !$cnt) $cnt=1 ;
    return($cnt) ;
  }

  function get_items($usl,$options=array())
  { $limit=($options['limit'])? ' '.$options['limit']:'' ;
    $order=($this->filter['order'])? ' order by '.$this->filter['order']:' order by c_data desc' ;
    //echo $usl ;
    //  $options['debug']=2 ;
 	$list_recs=execSQL('select *
                       from  view_personals_messages
                       where '.$usl.$order.$limit,$options) ;
    if ($this->filter['personal_id']) ENGINE()->on_event_by_pointer('get_active_mess_to_personal',$this->filter['personal_id'],$list_recs,$options) ;
    return($list_recs) ;
  }


    // шаблон - вывод ссылками без разделитея
    function print_template_HTML($list_recs,$options=array())
      { $id=($options['id'])? 'id='.$options['id']:'' ;
        //print_2x_arr($list_recs) ;
        ?><table class="list_personal_table_img basic fz_small full auto"<?echo $id?>>
            <tr><th>ID</th><th>Дата отправки сообщения</th><th>Статус</th><?if (!$options['no_view_person']){?><th>ФИО</th><th>Организация / Подразделение</th><?}?><th>Автор</th><th>Текст сообщения</th><th>Источник</th><th class="nowrap">Параметры уведомления</th><th>Состояние показа</th><th>Операции</th></tr><? ;
            if (_sizeof($list_recs)) foreach($list_recs as $rec)
            {  ?><tr class=item>
                    <td><?echo ($rec['pkey'])?:'-'?></td>
                    <td><?echo date('d.m.Y H:i:s',$rec['c_data'])?></td>
                    <td><?echo $_SESSION['ARR_mess_status'][$rec['status']]?>
                        <?if (!$rec['enabled'] and $rec['status']!=4) echo '<div class="red">Выключено</div>';?>
                        <?if($rec['status']==4 and $rec['close_data']) echo '<br>'.date('d.m.Y H:i:s',$rec['close_data'])?></td>
                    <?if (!$options['no_view_person']){?>
                    <td class="left"><a href="/window/personal/person/<?echo $rec['personal_id']?>/" class="new_window" target="_blank" title="win_second"><?echo $rec['_personal_name']?></a><br><?echo $rec['dr']?><br><?echo $rec['propusk']?></td>
                    <td class="left"><?echo $rec['_org_name'].'<br>'.$rec['_otdel_name']?></td>
                    <?}?>
                    <td class="left"><?echo $rec['account_name']?></td>
                    <td class="left"><?echo $rec['obj_name']?></td>
                    <td><?
                          if ($rec['source_obj'])
                          {   $obj_event=EVENTS()->get_event_obj_by_ext($rec['source_obj']) ;
                              $rec_event=EVENTS()->get_event_by_id($rec['mess_event_id']) ;
                              //damp_array($obj_event) ;
                              echo $obj_event->name ; ?> <a href="<?echo $rec_event['__href']?>" class="new_window"><?echo $rec_event['obj_name']?></a><br><?
                              /*?><a href="/cab/events/pass/<?echo $rec['source_pkey']?>/" class="new_window">Карточка участия</a><?*/

                             // echo $rec['source_obj'].'<br>['.$rec['source_pkey'].']' ;
                          }

                        ?></td>
                    <td><?/*if ($rec['max_cnt']){?><div class="view_cnt blue"><? echo $rec['max_cnt']?></div><?}*/
                          /*if ($rec['max_data']){?><div class="view_data">по <? echo date('d.m.Y H:i',$rec['max_data'])?></div><?}*/
                          if ($rec['view_from'] or $rec['view_to'])
                          { ?><strong>Показ сообщений</strong><?
                            if ($rec['view_from']) {?><div class="small">c <? echo date('d.m.Y H:i',$rec['view_from'])?></div><?}
                            if ($rec['view_to'])   {?><div class="small">по <? echo date('d.m.Y H:i',$rec['view_to'])?></div><?}
                          }
                         if ($rec['block_from'] or $rec['block_to'])
                          { ?><strong>Блокировка</strong><?
                            if ($rec['block_from']) {?><div class="small">c <? echo date('d.m.Y H:i',$rec['block_from'])?></div><?}
                            if ($rec['block_to'])   {?><div class="small">по <? echo date('d.m.Y H:i',$rec['block_to'])?></div><?}
                          }
                         if ($rec['auto_close'])
                          { ?><strong>Автозакрытие</strong><?
                            ?><div class="small"><? echo date('d.m.Y H:i',$rec['auto_close'])?></div><?
                          }
                        /*
                        ?>
                        Показывать на МО - <strong><? echo ($rec['view_mode']==1 or $rec['view_mode']==3)? 'Да':'Нет'?></strong><br>
                        Показывать в ламповой - <strong><? echo ($rec['view_mode']==2 or $rec['view_mode']==3)? 'Да':'Нет'?></strong><br>
                        Запрещать МО - <strong><? echo ($rec['block_mo'])? 'Да':'Нет'?></strong><br>
                        */?>
                    </td>
                    <td><?if ($rec['view_cnt']){?><div class="view_cnt green"><? echo $rec['view_cnt']?></div><?}?>
                        <?if ($rec['view_data']){?><div class="view_data"><? echo date('d.m.Y H:i',$rec['view_data'])?></div><?}?>
                        <?if ($rec['view_mesto']){?><div class="view_mesto"><? echo $rec['view_mesto']?></div><?}?>
                        <? if ($rec['status']==3 and $rec['enabled']==1/* and $rec['block_mo']==1*/) echo  '<div class="mo_alert">Прохождение МО заблокировано</div>'?>
                    </td>
                    <td class="center">
                       <?if (MEMBER()->id==$rec['account_id'] or MEMBER()->rol==1)
                       { if ($rec['status']!=4)
                         {
                           if ($rec['source_obj']=='events_docs/i_event_docs')
                           { ?><button class="v2" cmd="events_docs/personal_pass_close" pass_id="<?echo $rec['source_pkey']?>">Документ сдан</button>
                               <button class="v2" cmd="events_docs/personal_pass_add_day" pass_id="<?echo $rec['source_pkey']?>">Добавить дней</button><br><br>
                             <?
                           }
                           else
                           { if ($rec['pkey']){?><button class="v2" cmd="aspmo_personal/personal_message_close" mess_id="<?echo $rec['pkey']?>">Закрыть</button><br><br><?}
                           }

                         }
                        if ($rec['pkey']){?><a href="/window/personal/message/<?echo $rec['pkey']?>/" class="new_window" target="_blank" title="window_messages">Карточка сообщения</a><?}
                       }?>
                    </td>
                </tr><?
            }
          ?></table>
            <style type="text/css">
                table.list_personal_table_img{}
                table.list_personal_table_img td.cnt_mess{font-size:22px;color:green;}
                table.list_personal_table_img td.cnt_mess a{text-decoration:none;}
                table.list_personal_table_img td.cnt_mess a:hover{text-decoration:underline;}
                table.list_personal_table_img div.view_cnt{font-size:24px;margin:5px 0;}
                table.list_personal_table_img div.view_data{font-size:14px;margin:5px 0;}
                table.list_personal_table_img div.mo_alert{color:white;font-size:15px;margin-top:10px;background:darkred;padding:10px;}
            </style>
          <?
      }


    function print_template_CSV($list_recs,$options=array())
       { $i=$options['from'] ; $arr_source=[] ;
         if (_sizeof($list_recs)) foreach($list_recs as $rec)
           {   $source='' ;
               if ($rec['source_obj'])
                 {   $obj_event=EVENTS()->get_event_obj_by_ext($rec['source_obj']) ;
                     $rec_event=EVENTS()->get_event_by_id($rec['mess_event_id']) ;
                     if (!isset($arr_source[$rec['source_obj']])) $arr_source[$rec['source_obj']]=$obj_event->name.' "'.$rec_event['obj_name'].'"' ;
                     $source=$arr_source[$rec['source_obj']] ;
                 }

               $data=array() ;

               $data['ID']=$rec['pkey'] ;
               $data['Дата отправки сообщения']=date('d.m.Y H:i:s',$rec['c_data']);
               $data['Статус']=$_SESSION['ARR_mess_status'][$rec['status']];
               $data['ФИО']=$rec['_personal_name'];
               $data['Организация']=$rec['_org_name'] ;
               $data['Подразделение']=$rec['_otdel_name'];
               $data['Автор']=$rec['account_name'];
               $data['Текст сообщения']=$rec['obj_name'];
               $data['Источник']=$source;
               $data['Показ сообщений, от ']=($rec['view_from'])? date('d.m.Y H:i',$rec['view_from']):'';
               $data['Показ сообщений, до ']=($rec['view_to'])? date('d.m.Y H:i',$rec['view_to']):'';
               $data['Блокировка МО, от ']=($rec['view_from'])? date('d.m.Y H:i',$rec['block_from']):'';
               $data['Блокировка МО, до ']=($rec['view_to'])? date('d.m.Y H:i',$rec['block_to']):'';
               $data['Автозакрытие']=($rec['auto_close'])? date('d.m.Y H:i',$rec['auto_close']):'';
               $data['Число показов']=($rec['view_cnt'])? $rec['view_cnt']:0;
               $data['Дата последнего показа']=($rec['view_data'])? date('d.m.Y H:i',$rec['view_data']):'';
               $data['Место последнего показа']=($rec['view_mesto'])? $rec['view_mesto']:'';
               $data['Блокировка МО активна']=(($rec['status']==3 and $rec['enabled']==1))? 'Да':'-';

               $this->put_data_to_CSV($data,$i) ;

               $i++ ;
           }

       }
}
?>
