<?php
$__functions['init'][]      ='_notify_site_vars' ;
$__functions['boot_site'][] ='_notify_site_boot' ;

function NOTIFY() {
    if (isset($_SESSION['NOTIFY_system'])) {
        return($_SESSION['NOTIFY_system']);
    } else {
        $_SESSION['NOTIFY_system']=new c_notify_system();
        return($_SESSION['NOTIFY_system']);
    }
}

function _notify_site_vars() //
{
}

function _notify_site_boot($options)
{
    create_system_modul_obj('notify',$options) ;
}

class c_notify_system
{

    function __construct()
    {
        ENGINE()->reg_ext('notify','Плагин для отправки писем') ;
    }

    function declare_menu_items_5($page)
    {
        $count = execSQL_value('select count(pkey) from error_messages where new=1');
        $page->menu['/cab/log/events/']['items']['/cab/notify/'] = array('title'=>'Неисправности','info_value'=>$count);
        if (MEMBER()->rol==1 or ACCOUNTS()->get_right_rol(MEMBER()->id,'report_error_messages'))
            $page->menu['/cab/log/events/']['info_value'] = $count;
    }

    function cron_checking_for_errors()
    {
        $date_from = date('d.m.Y H:i',time()-60*60);
        $date_to = date('d.m.Y H:i');
        $count_mo = execSQL('select terminal_id,count(pkey) as count from obj_site_mo_session where c_data>="'.strtotime($date_from).'" and c_data<="'.strtotime($date_to).'" group by terminal_id');
        //было выявленно [количество] ... в работе оборудования
        foreach ($count_mo as $item=>$terminal) {
            $reasons = ['equipmentFailure'=>'отказов','equipmentError'=>'ошибок','cancelTimeout'=>'завершений по таймауту'];
            foreach ($reasons as $key=>$value) {
                $this->search_error_for_reasons($date_from,$date_to,$terminal['count'],$terminal['terminal_id'],$key,$value);
            }
        }
    }

    function search_error_for_reasons($date_from,$date_to,$count_mo,$terminal_id,$reason,$reason_name)
    {
        $equipments=['alcotester'=>'алкотестера','thermometer'=>'термометра','tonometer'=>'тонометра'];
        $sql = 'select equipment,count(pkey) as count from obj_site_mo_session where c_data>="'.strtotime($date_from).'" and c_data<="'.strtotime($date_to).'" and reason="'.$reason.'" and terminal_id='.$terminal_id.' group by equipment';
        $count_for_reason = execSQL($sql);
        foreach ($equipments as $key=>$value) {
            if ($count_for_reason[$key] and (100*($count_for_reason[$key]['count']/$count_mo))>=1) {
                $terminal_info = ESMO()->get_terminal_by_id($terminal_id);
                $data=[
                    'new'=>1,
                    'type_error' => 'Проблема на терминале',
                    'brief_desc' => 'equipments: '.$key.'; reasons: '.$reason.';',
                    'title_message' => 'Автоматическое уведомление о неисправности',
                    'text_message'  => 'На терминале "'.$terminal_info['obj_name'].'", в промежутке времени с '.$date_from.' по '.$date_to.', было выявлено '.$count_for_reason[$key]['count'].' '.$reason_name.' в работе '.$value.'.'
                ];
                ENGINE()->on_event('send_message_server_problem',$data) ;
            }
        }
    }

    function on_event_send_message($data)
    {
        if (!isset($data['new'])) $data['new'] = 1;
        //добавить запись в таблицу
        adding_rec_to_table('error_messages',$data);
        //если нужно, отправить сообщение на почту
        if ($GLOBALS['LS_notify_send_message_to_email']) {
            ob_start();
            echo $data['text_message'];
            $text = ob_get_clean();

            $arr_emails = explode(',', $GLOBALS['LS_notify_email_from']);
            if ($data['title_message']) $title = $data['title_message'];
            else $title = 'Автоматическое уведомление о выявлении неисправности';
            if (_sizeof($arr_emails)) {
                $email = trim($arr_emails[0]);
                unset($arr_emails[0]);
                $mail_options['cc'] = array();
                $mail_options['debug'] = 1;
                $mail_options['no_asyns_send_mail'] = 1;
                if (_sizeof($arr_emails)) foreach ($arr_emails as $cc_email) if (trim($cc_email)) $mail_options['cc'][trim($cc_email)] = trim($cc_email);
                MAILS()->send_mail($email, $title, $text, $mail_options);
            }
            $text = ob_get_clean();
            echo $text;
            $name = LOGS()->reg_file_log('send_message_about_problems', $text);
            LOGS()->reg_log('Автоматическое уведомление о выявлении неисправности', '<a target=_blank href="' . $name . '">Отчет</a>' . $text);
            LOG_JSON('send_message')->reg('Автоматическое уведомление о выявлении неисправности', '<a target=_blank href="' . $name . '">Отчет</a>' . $text);
        }
    }

    function get_type_errors()
    {
        $type_errors = execSQL_row('select type_error,type_error from error_messages group by type_error');
        return $type_errors;
    }

    function update_status_messages()
    {
        execSQL_update('update error_messages set new=0 where new=1');
    }
}
