<?
// вниамение!!!
// во всех фильтрах:
// data_from, data_to - дата в текстовом формате
// time_from, time_to - дата в UNIX формате

class report_alcotester_error extends c_report
{
 var $title='Отчет по ложным срабатываниям алкотестера' ;
 var $view_only_model=1 ;
 var $mo_sort='pkey' ;
 var $dop_usl='';
// var $allow_export_to_csv=1 ;
// var $allow_export_to_excel=1 ;

 function setting()
{

  $arr_accounts=ACCOUNTS()->get_list_members(array('group_id'=>MEMBER()->cur_group_id,'rol'=>'2,3')) ;
  $arr_groups=ACCOUNTS()->get_arr_groups_to_cur_account() ;
  list($arr_orgs_ids,$arr_otdel_ids,$arr_workd_ids)=PERSONAL()->get_org_otdels_works_to_cur_account($this->filter) ;

  $arr_terminals=ESMO()->get_list_terminals(MEMBER()->cur_group_id) ;

  ?><div id="panel_filter">
       <form id="sky-form" class="sky-form"><input type="hidden" name="filter_dir" value="<?echo _CUR_REPORT_DIR?>">
            <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) ;
                       $this->filter_section_input_text('data_from','От:',2,array('class'=>'datetimepicker')) ;
                       $this->filter_section_input_text('data_to','До:',2,array('class'=>'datetimepicker')) ;
                                ?>
                </div>
                <div class="row">
                    <?
                    $this->filter_section_input_text('name','ФИО:',4,array('auto_complete'=>"autocomplette_personal_name")) ;
                    if (MEMBER()->rol!=2) $this->filter_section_select('doctor_id','Фельдшер:',2,$arr_accounts,array('space_element'=>1)) ;
                    $this->filter_section_select('terminal_id','Терминал:',2,$arr_terminals,array('key_fname'=>'id')) ;
                    ?>

                </div>
            </fieldset>
            <?$this->panel_buttons();?>
        </form>
     </div>
  <?
}

function panel_info_filter()
 { $_str=array() ; $info=array() ; $title='' ;
   if ($this->filter['data_from'])                       $info['c']=$this->filter['data_from'] ;
   if ($this->filter['data_to'])                         $info['по']=$this->filter['data_to'] ;
   if ($this->filter['group_id'])                        $info['Группа']=ACCOUNTS()->get_member_name_by_id($this->filter['group_id'])  ;
   if ($this->filter['dep_id'])                          $info['Подразделение']=PERSONAL()->get_full_dep_name_by_dep_id($this->filter['dep_id'])  ;
   if ($this->filter['org_id'])                          $info['организация']=PERSONAL()->get_name_by_id($this->filter['org_id']) ;
   if ($this->filter['org_ids'])                         $info['Организации']=PERSONAL()->get_org_names_by_ids(array_keys($this->filter['org_ids']))  ;
   if ($this->filter['otdel_ids'])                       $info['Подразделения']=PERSONAL()->get_org_names_by_ids(array_keys($this->filter['otdel_ids']))  ;
   if ($this->filter['otdel_id'])                        $info['подразделение']=PERSONAL()->get_name_by_id($this->filter['otdel_id']) ;
   if ($this->filter['name'])                            $info['ФИО']='"'.$this->filter['name'].'"' ;
   if ($this->filter['doctor_id'])                       $info['Доктор']=ACCOUNTS()->get_member_name_by_id($this->filter['doctor_id'])  ;

   if ($this->filter['terminal_id'])                       $info['Терминал']=$this->filter['terminal_id']  ;

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

 }

    function create_usl_select_obj($_params,&$options)
    {

        $_usl=[] ; $_usl2=[] ;

        $_usl[]='t1.mo_type in (1,2) and t1.alko=1';
        $_usl2[]='model in (5,7)';
        if ($this->filter['group_id'])  $_usl[]='t1.group_id in ('.$this->filter['group_id'].')' ;
        if ($options['member_id']) $_usl[]='t1.member_id='.$this->filter['member_id'] ;
        if ($this->filter['doctor_id'])  {
            $_usl[]='(t1.doctor_id='.$this->filter['doctor_id'].' or t1.dopusk_user_id='.$this->filter['doctor_id'].' or t1.hand_check_user_id='.$this->filter['doctor_id'].')' ;
            $_usl2[]='(doctor_id='.$this->filter['doctor_id'].' or dopusk_user_id='.$this->filter['doctor_id'].' or hand_check_user_id='.$this->filter['doctor_id'].')' ;
        }
        if ($this->filter['terminal_id'])  $_usl[]='(t1.terminal_id in ('.$this->filter['terminal_id'].') or t1.terminal_id is null)' ;
        if ($this->filter['time_from'])     {
           $_usl[]='t1.c_data>='.$this->filter['time_from'] ;
           $_usl2[]='c_data>='.$this->filter['time_from'] ;
        }
        if ($this->filter['time_to'])       {
           $_usl[]='t1.c_data<='.$this->filter['time_to'] ;
           $_usl2[]='c_data<='.$this->filter['time_to'] ;
        }
        if ($this->filter['data_from'])     {
           $_usl[]='t1.c_data>='.strtotime($this->filter['data_from']) ;
           $_usl2[]='c_data>='.strtotime($this->filter['data_from']) ;
        }
        if ($this->filter['data_to'])       {
           $arr=explode(' ',trim($this->filter['data_to'])) ;
            $time_to=(!$arr[1])? strtotime($this->filter['data_to'].' 23:59:59'):strtotime($this->filter['data_to']) ;
            $_usl[]='t1.c_data<='.$time_to ;
            $_usl2[]='c_data<='.$time_to ;
        }
        if ($this->filter['org_id'])        $_usl[]='t1.personal_parent2="'.$this->filter['org_id'].'"' ;
        if ($this->filter['otdel_id'])      $_usl[]='t1.personal_parent3="'.$this->filter['otdel_id'].'"' ;

        // check_filter_array - проверяет где находится организации - в ключе или в значениях
        // организации или отделы сотрудника
        if ($this->filter['org_ids']) {
            if (is_array($this->filter['org_ids'])) {
                if (_sizeof($this->filter['org_ids'])) $_usl[] = 't1.personal_parent2 in (' . implode(',', $this->check_filter_array($this->filter['org_ids'])) . ')';
            } else {
                $_usl[] = 't1.personal_parent2 in (' . $this->filter['org_ids'] . ')';
            }
        }
        if ($this->filter['otdel_ids']) {
            if (is_array($this->filter['otdel_ids'])) {
                if (_sizeof($this->filter['otdel_ids'])) $_usl[] = 't1.personal_parent3 in (' . implode(',', $this->check_filter_array($this->filter['otdel_ids'])) . ')';
            } else {
                $_usl[] = 't1.personal_parent3 in (' . $this->filter['otdel_ids'] . ')';
            }
        }
        if ($this->filter['name']) {
            $arr_ids = execSQL_line('select pkey from obj_site_personals where clss=211 and obj_name like "%' . addslashes($this->filter['name']) . '%"');
            if (_sizeof($arr_ids)) $_usl[] = 't1.member_id in (' . implode(',', $arr_ids) . ')';
            else                   $_usl[] = 't1.member_id=-1';
        }
        if ($this->filter['terminal_id'])  $_usl[]='(t1.terminal_id in ('.$this->filter['terminal_id'].') or t1.terminal_id is null)' ;

        if (_sizeof($_usl)) $usl_res=implode(' and ',$_usl) ;
        if (_sizeof($_usl2)) $this->dop_usl=implode(' and ',$_usl2) ;

        return($usl_res) ;
    }

    function check_filter_array($arr)
    {
        list($id,$value)=each($arr) ;
        if (!$id) return($arr) ;
        else return(array_keys($arr)) ;
    }

    function get_cnt_items($usl, $options = array())
    {
//        $options['debug'] = 2;
        $this->cnt_items = execSQL_value('
                select count(t2.pkey)
                    from ' . ESMO()->view_mo_session . ' t1
                    inner join (
                      select pkey,member_id,doctor_id,mo_type,mo1_id,c_data
                        from ' . ESMO()->table_mo_sessions . '
                        where ' . $this->dop_usl . '
                    ) t2
                    on t1.pkey=t2.mo1_id
                    where ' . $usl, $options);
        return ($this->cnt_items);
    }

    function get_items($usl, $options = array())
    {
//        $options['debug']=2;
        $limit = ($options['limit']) ? ' ' . $options['limit'] : '';
//        $order=($options['order'])? ' order by '.$options['order']:' order by '.$this->mo_sort ;
        $order = ' order by t2.pkey desc';

        $recs = execSQL('
                select t2.pkey,t2.mo1_id,t1.group_id,t1.group_name,t2.doctor_id as hand_check_doctor_id,t1.terminal_id,t1.doctor_id as terminal_doctor_id,t2.member_id,t2.c_data as hand_check_time,t1.c_data as terminal_alko_time,t1.member_name
                    from ' . ESMO()->view_mo_session . ' t1
                    inner join (
                      select pkey,member_id,doctor_id,mo_type,mo1_id,c_data
                        from ' . ESMO()->table_mo_sessions . '
                        where ' . $this->dop_usl . '
                    ) t2
                    on t1.pkey=t2.mo1_id
                    where ' . $usl . $order . $limit, $options);
        return ($recs);
    }

 // шаблон - вывод ссылками без разделитея
    function print_template_HTML($list_recs,$options=array())
    {
        $id=($options['id'])? 'id='.$options['id']:'' ;
        ?>
        <div id="reports_mo">
          <div class=list_mo_sessions_report <?echo $id?>>
              <table class="basic fz_small" >
                <tr>
                    <th rowspan="2">№</th>
                    <th rowspan="2">Сотрудник</th>
                    <th rowspan="2">Группа</th>
                    <th colspan="4">Положительный алкоголь на терминале</th>
                    <th colspan="3">Отрицательный алкогорль на ручном осмотре</th>
                </tr>
                <tr>
                    <th>ID MO</th>
                    <th>Дата</th>
                    <th>Терминал</th>
                    <th>Фельдшер</th>
                    <th>ID MO</th>
                    <th>Дата</th>
                    <th>Фельдшер</th>
                </tr>
                <?
                $i=$this->first_obj ;
                if (_sizeof($list_recs)) foreach($list_recs as $rec)
                {
                    if (!isset($recs_doctor[$rec['hand_check_doctor_id']])) $recs_doctor[$rec['hand_check_doctor_id']]=ACCOUNTS()->get_member_by_id($rec['hand_check_doctor_id']) ;
                    if (!isset($recs_doctor[$rec['terminal_doctor_id']])) $recs_doctor[$rec['terminal_doctor_id']]=ACCOUNTS()->get_member_by_id($rec['terminal_doctor_id']) ;
        //                    $rec_doctor=$recs_doctor[$rec['doctor_id']] ;
                    ?>
                    <tr class=item>
                        <td><?echo $i; $i++;?></td>
                        <td><?echo $rec['member_name']?></td>
                        <td><?echo $rec['group_name']?></td>
                        <td><?echo '<a href="/cab/mo/'.$rec['mo1_id'].'/" target=_blank>'.$rec['mo1_id'].'</a>'?></td>
                        <td><?echo date('d.m.Y',$rec['terminal_alko_time']).'<br>'.date('H:i',$rec['terminal_alko_time'])?></td>
                        <td><?echo $rec['terminal_id']?></td>
                        <td><?echo $recs_doctor[$rec['terminal_doctor_id']]['obj_name']?></td>
                        <td><?echo '<a href="/cab/mo/'.$rec['pkey'].'/" target=_blank>'.$rec['pkey'].'</a>'?></td>
                        <td><?echo date('d.m.Y',$rec['hand_check_time']).'<br>'.date('H:i',$rec['hand_check_time'])?></td>
                        <td><?echo $recs_doctor[$rec['hand_check_doctor_id']]['obj_name']?></td>
                    </tr>
                    <?
                }
                ?>
              </table>
          </div>
        </div>
        <style type="text/css">
            div.list_mo_sessions_report table th {border-color: #aaaaaa;}
        </style>
        <?
    }

    function print_template_CSV($list_recs, $options = array())
    {
        $i = $options['from'];
        if (_sizeof($list_recs)) foreach ($list_recs as $rec) {
            $rec_doctor = _IL('ARR_accounts')->recs[$rec['doctor_id']];

            $data = array();
            // обязательные поля в каждой выгрузке
            $data['MO ID'] = $rec['pkey'];
            $data['Дата'] = date('d.m.Y', $rec['c_data']);
            $data['Время'] = date('H:i:s', $rec['c_data']);
            $data[$GLOBALS['LS_person_group_title'] . ' МО'] = ACCOUNTS()->tree[$rec['group_id']]->name;
            $data['UID сотрудника'] = $rec['member_uid'];
            $data['ФИО сотрудника'] = $rec['member_name'];
            $data['Организация'] = $rec['_org_name'];
            $data['Подразделение'] = $rec['_otdel_name'];
            $data['Должность'] = _IL('IL_works')->recs[$rec['working']]['obj_name'];
            $data['Пол'] = ($rec['member_pol']) ? 'Женский' : 'Мужской';
            $data['ДатаРожд'] = $rec['member_dr'];

            $data['Жалобы'] = ($rec['status'] == 2 or $rec['status'] == 3) ? ($rec['question']) ? 'Есть' : 'Нет' : '-';
            if ($rec['question_comment']) $data['Жалобы'] .= ' ' . $rec['question_comment'];
            $data['Давление систолическое'] = $rec['_systolic'];
            $data['Давление диастолическое'] = $rec['_diastolic'];
            $data['Пульс'] = $rec['_pulse'];
            $data['Температура'] = $rec['_temperature_csv'];
            $data['Алкоголь'] = ($rec['alko'] > 0) ? 'Есть ' . (($rec['alko_value'] > 0) ? ' (' . $rec['alko_value'] . ')' : '') : ($rec['alcotester'] ? 'Нет' : '-');
            $pzipr = '';
            if ($rec['status'] >= 2 and $rec['status'] <= 3) $pzipr = ($rec['simptoms']) ? _IL('IL_diagnoz')->recs[$rec['simptoms']]['obj_name'] : 'Не выявлено'; else echo '-';
            //if ($rec['comment']) $pzipr.=' '.$rec['comment']  ;
            //if ($rec['status']==2) $pzipr.=' '.$rec['_status_name'] ;
            $data['ПЗиПР'] = $pzipr;
            $data['Допуск'] = $rec['_dopusk_name'];
            $data['Врач'] = $rec_doctor['obj_name'];
            $data['Длительность сеанса'] = $rec['__dlit_mo'];

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

            $i++;
        }

    }

}
?>
