<?
$__functions['boot_site'][] ='_send_report_site_boot' ;
$__functions['main_menu'][] ='_send_report_main_menu' ;

function _send_report_site_boot($options)
{
}

function _send_report_main_menu($page)
{
    $page->menu['/cab/send_report/']['title']='<i class="fa fa-envelope"></i>Отправка отчетов';
}

function SEND_REPORT()
{
    if (is_object($GLOBALS['send_report_plugin'])) return ($GLOBALS['send_report_plugin']);
    $GLOBALS['send_report_plugin'] = new i_send_report();
    return ($GLOBALS['send_report_plugin']);
}

class i_send_report
{

    public $main_table = 'send_report_list';
    public $sender_table = 'send_report_sender';
    public $queue_table = 'send_report_queue';
    public $journal_table = 'send_report_journal';
    public $report_status = [
        0 => 'Новый отчет',
        1 => 'Готов',
        2 => 'Отключен',
        3 => 'Неотображаемый',
    ];
    public $sender_status = [
        0 => 'Не настроен',
        1 => 'Ожидает отправки',
        2 => 'Отчет формируется',
//        3 => 'Отключен'
    ];

    function install()
    {
        $descr_class[710]['name'] = 'Список отчетов для отправки';
        $descr_class[710]['parent'] = 0;
        $descr_class[710]['fields']['class_name'] = array('type' => 'varchar(255)', 'index' => 'class_name');
        $descr_class[710]['fields']['script_dir'] = array('type' => 'varchar(255)', 'index' => 'script_dir');
        $descr_class[710]['fields']['section_title'] = array('type' => 'varchar(255)', 'default' => '');
        $descr_class[710]['fields']['status'] = array('type' => 'tinyint(1)', 'index' => 'status');

        $descr_class[711]['name'] = 'Формирование отправки отчета';
        $descr_class[711]['parent'] = 0;
        $descr_class[711]['fields']['send_report_id'] = array('type' => 'int(11)', 'index' => 'send_report_id'); //id отчета для которого фомируется отправка
        $descr_class[711]['fields']['send_email'] = array('type' => 'varchar(255)', 'default' => '');
        $descr_class[711]['fields']['send_status'] = array('type' => 'tinyint(1)', 'index' => 'send_status', 'default' => 0);
        $descr_class[711]['fields']['send_type'] = array('type' => 'tinyint(1)', 'default' => 0); //период цикла (день/неделя/месяц)
        $descr_class[711]['fields']['filters'] = array('type' => 'serialize', 'default' => ''); //массив фильтров
        $descr_class[711]['fields']['send_on'] = array('type' => 'tinyint(1)', 'index' => 'send_status', 'default' => 0); // отправка отключена = 0
        $descr_class[711]['fields']['send_name'] = array('type' => 'varchar(255)', 'default' => ''); //Пользовательское название/описание отправки

        $descr_class[712]['name'] = 'Очередь отправки отчетов';
        $descr_class[712]['parent'] = 0;
        $descr_class[712]['fields']['send_parent_id'] = array('type' => 'int(11)', 'index' => 'send_parent_id'); // id "Формирование отправки отчета"
        $descr_class[712]['fields']['time_h_m'] = array('type' => 'int(11)', 'index' => 'time_h_m');
//        $descr_class[712]['fields']['week_num'] = array('type' => 'tinyint(1)', 'default' => 0);
//        $descr_class[712]['fields']['month_num'] = array('type' => 'tinyint(2)', 'default' => 0);
        $descr_class[712]['fields']['send_days'] = array('type' => 'serialize', 'default' => ''); //массив дней
        $descr_class[712]['fields']['outputfile'] = array('type' => 'varchar(255)', 'default' => '');
        $descr_class[712]['fields']['file'] = array('type' => 'varchar(255)', 'default' => '');

        $descr_class[713]['name'] = 'Журнал отправки отчетов';
        $descr_class[713]['parent'] = 0;
        $descr_class[713]['fields']['obj_name'] = array('type' => 'varchar(255)', 'default' => '');
        $descr_class[713]['fields']['send_name'] = array('type' => 'varchar(255)', 'default' => '');
        $descr_class[713]['fields']['date']=array('type'=>'datetime');
        $descr_class[713]['fields']['send_email'] = array('type' => 'varchar(255)', 'default' => '');
        $descr_class[713]['fields']['send_type'] = array('type' => 'tinyint(1)', 'default' => 0); //период цикла (день/неделя/месяц)

        SETUP()->reg_class($descr_class);

        ENGINE()->reg_cron('Обработка очереди отправки отчетов','SEND_REPORT/exec_send_report','*/1 * * * *',['enabled'=>1]) ;

        $pattern = array();
        $pattern['table_title'] = 'Список отчетов для отправки';
        $pattern['use_clss'] = '710';
        $pattern['table_name'] = $this->main_table;
        $pattern['table_clss'] = 101;
        create_table_by_pattern($pattern);

        $pattern = array();
        $pattern['table_title'] = 'Формирование отправки отчета';
        $pattern['use_clss'] = '711';
        $pattern['table_name'] = $this->sender_table;
        $pattern['table_clss'] = 101;
        create_table_by_pattern($pattern);

        $pattern = array();
        $pattern['table_title'] = 'Очередь отправки отчетов';
        $pattern['use_clss'] = '712';
        $pattern['table_name'] = $this->queue_table;
        $pattern['table_clss'] = 101;
        create_table_by_pattern($pattern);

        $pattern = array();
        $pattern['table_title'] = 'Журнал отправки отчетов';
        $pattern['use_clss'] = '713';
        $pattern['table_name'] = $this->journal_table;
        $pattern['table_clss'] = 101;
        create_table_by_pattern($pattern);

        SETUP()->reg_ext('send_report','send_report') ;
    }

    function get_send_report_by_id($id)
    {
        $rec = execSQL_van('select * from ' . $this->main_table . ' where pkey=' . $id);
        return $rec;
    }

    function get_sender_by_id($id)
    {
        $rec = execSQL_van('select * from ' . $this->sender_table . ' where pkey=' . $id);
        return $rec;
    }

    function get_senders_by_send_report_id($id)
    {
        $recs = execSQL('select t1.*,t2.cnt_queue 
                                from ' . $this->sender_table . ' t1 
                                    left join (
                                        select send_parent_id,count(pkey) as cnt_queue
                                            from '.$this->queue_table.'
                                            where enabled=1 group by send_parent_id
                                    ) t2
                                    on t1.pkey=t2.send_parent_id
                                where t1.send_report_id=' . $id);
        return $recs;
    }

    function get_queue_by_sender_id($id)
    {
        $recs = execSQL('select * from ' . $this->queue_table . ' where send_parent_id=' . $id);
        return $recs;
    }

    function update_report_list()
    {
        $report_lists = $this->get_send_report_list(['all' => 1]);
        $system_report_lists = $this->get_exist_report_list();
        $count = [];

        foreach ($system_report_lists as $class_name => $system_report_list) {
            if ($report_lists[$class_name]) {
                if ($this->update_send_report($system_report_list, $report_lists[$class_name])) {
                    //данные обновлены
                    $count['update'][$report_lists[$class_name]['status']]++;
                } else {
                    $count['skip'][$report_lists[$class_name]['status']]++;
                }
//                $report_lists[$class_name]['viewed'] = true;
                unset($report_lists[$class_name]);
            } else {
                if ($this->add_new_send_report($system_report_list)) $count['add_new']++;
            }
        }

        //оставшиеся записи отсутствуют в отчетах
        foreach ($report_lists as $report_list) {
            update_rec_in_table($this->main_table, ['status' => 2], 'pkey=' . $report_list['pkey']);
            $count['for_delete']++;
        }
        return $count;
    }

    function get_send_report_list($options = [])
    {
        $_usl = [];
        $usl = '';
        if (!$options['all']) {
            $_usl[] = 'enabled=1';
//            $_usl[] = 'status!=0';
        }
        if (_sizeof($_usl)) $usl = ' where ' . implode(' and ', $_usl);
        $recs = execSQL('select * from ' . $this->main_table . $usl, ['use_fname_indx' => 'class_name']);
        return $recs;
    }

    function get_exist_report_list()
    {
        $recs = REPORTS()->reports_list;

        //убираем из списка отчеты не для отображения на главной странице
        foreach ($recs as $key => $rec) {
            if ($this->include_report($rec['script_dir'])) {
                $report = new $rec['class_name']();
                if (!$report->show_on_page_peports) unset($recs[$key]);
            }
            unset($report);
        }
        return $recs;
    }

    function get_send_report_journal(){
        $recs = execSQL('select * from '.$this->journal_table);
        return $recs;
    }
    function include_report($script)
    {
        if (file_exists(_DIR_EXT . '/' . $script)) {
            include_once(_DIR_EXT . '/' . $script);
            return true;
        }
        if (file_exists(_DIR_EXT_LOCAL . '/' . $script)) {
            include_once(_DIR_EXT_LOCAL . '/' . $script);
            return true;
        }
        return false;
    }

    function update_send_report($new_data, $old_data)
    {
        if ($this->check_report_update($new_data, $old_data)) {
            $data = [];
            $data['script_dir'] = $new_data['script_dir'];
            $data['obj_name'] = $new_data['name'];
            $data['section_title'] = $new_data['section_title'];
            $update_result = update_rec_in_table($this->main_table, $data, 'pkey=' . $old_data['pkey']);
            if (is_array($update_result)) return true;
        }
        return false;
    }

    function check_report_update($new_data, $data)
    {
        try {
            if ($data['script_dir'] != $new_data['script_dir']) throw new Exception('Изменена дериктория');
            if ($data['obj_name'] != $new_data['name']) throw new Exception('Изменено наименование отчета');
            if ($data['section_title'] != $new_data['section_title']) throw new Exception('Изменена секция отчета');
        } catch (Exception $exception) {
            return true;
        }
        return false;
    }

    function add_new_send_report($new_data)
    {
        $data = [];
        $data['status'] = 0;
        $data['class_name'] = $new_data['class_name'];
        $data['script_dir'] = $new_data['script_dir'];
        $data['obj_name'] = $new_data['name'];
        $data['section_title'] = $new_data['section_title'];

        return adding_rec_to_table($this->main_table, $data);
    }

    function create_new_sender($send_report_id)
    {
        $id=0;
        if (is_numeric($send_report_id)) {
            $id=adding_rec_to_table($this->sender_table,['send_report_id'=>$send_report_id]);
        }
        return $id;
    }

    function exec_send_report(){
        $this->check_send_report_queue();
        $this->check_file_report();
    }


    function check_send_report_queue(){
        $t = time();
//        $t = strtotime('29.02.2020 12:00');
        $time_now = date('H:i',$t);
        $arr=explode(':',$time_now);
        $ts = $arr[0]*60 + $arr[1]; // текущее время от начала дня в минутах

        $recs = execSQL('select t1.pkey,t1.time_h_m,t1.send_days,t1.send_parent_id,t2.send_report_id,t2.filters,t2.send_type,t3.class_name,t3.obj_name
                    from '.$this->queue_table.' t1 
                        left join '.$this->sender_table.' t2
                        on t1.send_parent_id=t2.pkey
                            left join '.$this->main_table.' t3
                            on t2.send_report_id=t3.pkey
                    where t1.time_h_m='.$ts.' and t1.enabled=1 and t2.send_status=1 and t2.send_on=1',2,1);

        $get_date=getdate($t);
        $week_day=($get_date['wday'] == 0) ? 7 : $get_date['wday']; //текущий день недели
        $month_day=$get_date['mday']; // текущий день месяца
        $array_week = [1=>'ПН',2=>'ВТ',3=>'СР',4=>'ЧТ',5=>'ПТ',6=>'СБ',7=>'ВС'];

        foreach ($recs as $rec) {
            if ($rec['time_h_m'] == $ts){
                $send_days = unserialize($rec['send_days']); // массив дней
                $filters = unserialize($rec['filters']); // массив фильтров
                $time = date('i:s',$rec['time_h_m']); // время отправки отчета
                switch ($rec['send_type']){
                    case '0':
                        LOGS()->reg_log('send_report',$rec['send_parent_id'].'Период день - отправка отчета №'.$rec['send_report_id'].' "'.$rec['obj_name'].'" в '.$time.'. Статус изменен на "Отчет формируется"');
                        $this->create_PDF_file($t,$rec['time_h_m'],$rec['send_report_id'],$filters, $rec['pkey'], $rec['send_parent_id'],3);
                        break;
                    case '1':
                        LOGS()->reg_log('send_report',$rec['send_parent_id'].'Период неделя - отправка отчета №'.$rec['send_report_id'].' "'.$rec['obj_name'].'" в '.$time.'. Статус изменен на "Отчет формируется"');
                        $this->create_PDF_file($t,$rec['time_h_m'],$rec['send_report_id'],$filters, $rec['pkey'], $rec['send_parent_id'],4);
                        break;
                    case '2':
                        LOGS()->reg_log('send_report',$rec['send_parent_id'].'Период неделя - отправка отчета №'.$rec['send_report_id'].' "'.$rec['obj_name'].'" в '.$time.'. Статус изменен на "Отчет формируется"');
                        $this->create_PDF_file($t,$rec['time_h_m'],$rec['send_report_id'],$filters, $rec['pkey'], $rec['send_parent_id'],5);
                        break;
                    case '3':
                        LOGS()->reg_log('send_report',$rec['send_parent_id'].' Ежедневная отправка отчета №'.$rec['send_report_id'].' "'.$rec['obj_name'].'" в '.$time.'. Статус изменен на "Отчет формируется"');
                        $this->create_PDF_file($t,$rec['time_h_m'],$rec['send_report_id'],$filters, $rec['pkey'], $rec['send_parent_id'],0);
                        break;
                    case '4':
                        if (array_search($week_day, $send_days) > -1) {
                            LOGS()->reg_log('send_report',$rec['send_parent_id'].' Недельная отправка отчета №'.$rec['send_report_id'].' "'.$rec['obj_name'].'" в '.$time.'по '.$array_week[$week_day].'. Статус изменен на "Отчет формируется"');
                            $this->create_PDF_file($t,$rec['time_h_m'],$rec['send_report_id'],$filters, $rec['pkey'], $rec['send_parent_id'],1);
                        }
                        break;
                    case '5':
                        $count_d = date('t', $t); //кол-во дней в этом месяце
                        if (array_search($month_day, $send_days) > -1 || ($count_d == $month_day && $count_d < $send_days[count($send_days)-1])) {
                            LOGS()->reg_log('send_report',$rec['send_parent_id'].' Месячная отправка отчета №'.$rec['send_report_id'].' "'.$rec['obj_name'].'" '.$month_day.'-го в '.$time.'. Статус изменен на "Отчет формируется"');
                            $this->create_PDF_file($t,$rec['time_h_m'],$rec['send_report_id'],$filters, $rec['pkey'], $rec['send_parent_id'],2);
                        }
                        break;
                }
            }
        }
    }

    function create_PDF_file($time,$time_h_m,$send_report_id,$filters,$pkey_queue,$send_parent_id, $send_type)
    {
        /**
         * @var $report_obj c_report
         */
        update_rec_in_table(SEND_REPORT()->sender_table,['send_status'=>2],'pkey='.$send_parent_id) ;
        LOGS()->reg_log('send_report','Статус изменен на "Отчет формируется"');

        $send_report = SEND_REPORT()->get_send_report_by_id($send_report_id);
        $class_name = $send_report['class_name'];
        $script_dir=$send_report['script_dir'] ;
        $date_from_to = ($send_type > 2) ? $this->date_from_to($time,$time_h_m,$send_parent_id, $send_type) : $this->period_date_from_to($time,$time_h_m,$send_type); // формирует data_from, data_to
        $result = '';
        if (file_exists(_DIR_EXT.'/'.$script_dir))
        { include_once(_DIR_EXT.'/'.$script_dir) ;
            if (class_exists($class_name))
            {
                $report_obj=new $class_name ;
                $report_obj->filter=$filters;
                $report_obj->filter['data_from']=date('d.m.Y H:i:s',$date_from_to['start']);
                $report_obj->filter['data_to']=date('d.m.Y H:i:s',$date_from_to['stop']);
                foreach ($filters as $key=>$filter){
                    if (is_array($filter)){
                        $array = [];
                        foreach ($filter as $item){
                            $array[$item] = 1;
                        }
                        $report_obj->filter[$key] = $array;
                    }
                }
                $result = $report_obj->prepare_and_convert_to_PDF();
            }
        }
        update_rec_in_table(SEND_REPORT()->queue_table,['file'=>$result['to'], 'outputfile'=>$result['outputfile']],'pkey='.$pkey_queue,['no_append_serialize_data'=>1]) ;
    }

    function date_from_to($time,$time_h_m,$send_parent_id, $send_type){
        $arr_time = []; //массив часов для текущей отправки
        $recs = execSQL('select time_h_m from '.$this->queue_table.' where send_parent_id='.$send_parent_id,2);

        $index = 0;
        $key = 0; //индекс текущего времени отправки в массиве
        foreach ($recs as $rec) {
            array_push($arr_time, $rec);
            if ($rec['time_h_m'] == $time_h_m) {
                $key = $index;
            }
            $index++;
        }
//        $time = strtotime('29.02.2020');
        $ts = getdate($time);
        LOGS()->reg_log('send_report','$ts - '.date('d:m:Y H:i:s',$time));

        //если в кол-во элементов в массиве = 1 или время отправки это 0й элемент => $yesterday = вчера или дальше
        if (count($arr_time) == 1 || (($key == 0) && ($send_type == 0))) $yesterday = $this->date_from_to_yesterday($time,$send_parent_id,$send_type);
        else $yesterday = mktime(0,0,0,$ts['mon'],$ts['mday'],$ts['year']);
        LOGS()->reg_log('send_report','$yesterday - '.date('d.m.Y H:i:s',$yesterday));

        $today = mktime(0,0,0,$ts['mon'],$ts['mday'],$ts['year']);
        LOGS()->reg_log('send_report','$today - '.date('d:m:Y H:i:s',$today));

        if ($key == 0) { //первая отправка
            $start_time_h = date('i', $arr_time[count($arr_time)-1]['time_h_m']);
            $start_time_m = date('s', $arr_time[count($arr_time)-1]['time_h_m']);
            $start = $yesterday + $start_time_h*60*60 + $start_time_m*60;
            $stop_time_h = date('i', $arr_time[$key]['time_h_m']);
            $stop_time_m = date('s', $arr_time[$key]['time_h_m']);
            $stop = $today + $stop_time_h*60*60 + $stop_time_m*60 - 1;
        } else if ($key == (count($arr_time) - 1)) { //последняя отправка
            $start_time_h = date('i', $arr_time[count($arr_time) - 2]['time_h_m']);
            $start_time_m = date('s', $arr_time[count($arr_time) - 2]['time_h_m']);
            $start = $yesterday + $start_time_h*60*60 + $start_time_m*60;
            $stop_time_h = date('i', $arr_time[count($arr_time) - 1]['time_h_m']);
            $stop_time_m = date('s', $arr_time[count($arr_time) - 1]['time_h_m']);
            $stop = $today + $stop_time_h*60*60 + $stop_time_m*60 - 1;
        } else { //средняя отправка
            $start_time_h = date('i', $arr_time[$key - 1]['time_h_m']);
            $start_time_m = date('s', $arr_time[$key - 1]['time_h_m']);
            $start = $yesterday + $start_time_h*60*60 + $start_time_m*60;
            $stop_time_h = date('i', $arr_time[$key]['time_h_m'] - 1);
            $stop_time_m = date('s', $arr_time[$key]['time_h_m']);
            $stop = $today + $stop_time_h*60*60 + $stop_time_m*60 - 1;
        }
        LOGS()->reg_log('send_report',$key.' Отчет будет сформирован с '.date('d.m.Y H:i:s',$start).' по '.date('d.m.Y H:i:s',$stop));
        return ['start'=>$start, 'stop'=>$stop];
    }

    function date_from_to_yesterday($time,$send_parent_id,$send_type){
        $rec = execSQL_van('select send_days from '.$this->queue_table.' where send_parent_id='.$send_parent_id,2);
        $send_days = unserialize($rec[send_days]);
        $ts = getdate($time);

        if ($send_type == 3){
            $yesterday = mktime(0,0,0,$ts['mon'],$ts['mday'],$ts['year'])-24*60*60;
        }else {
            switch ($send_type) {
                case '4':
                    $today_w = (date('w', $time) == 0) ? 7 : date('w', $time);
                    if (count($send_days)==1) { //для отчета раз в неделю вчера - 7 дней назад
                        $yesterday = mktime(0,0,0,$ts['mon'],$ts['mday'],$ts['year'])-(7-$send_days[0] + $today_w)*24*60*60;
                    } else {
                        $key = array_search($today_w,$send_days);
                        if($key === 0) {//первый в массиве
                            $yesterday_wd = ($send_days[$key]) + (7 - $send_days[count($send_days)-1]);
                            $yesterday = mktime(0,0,0,$ts['mon'],$ts['mday'],$ts['year'])-$yesterday_wd*24*60*60;
                        } else if($key === false) {//нет в массиве
                            $w = 8;
                            $w_key = 8;
                            foreach ($send_days as $index=>$day){
                                if(abs($day - $today_w) < abs($w - $today_w)) {$w = $day; $w_key=$index;}
                            }
                            if ($w < $today_w) {
                                $yesterday = mktime(0,0,0,$ts['mon'],$ts['mday'],$ts['year'])-($today_w-$w)*24*60*60;
                            }else ($w_key == 0) ? $yesterday = mktime(0,0,0,$ts['mon'],$ts['mday'],$ts['year'])-(7 - $send_days[count($send_days)-1]+$today_w)*24*60*60
                                : $yesterday = mktime(0,0,0,$ts['mon'],$ts['mday'],$ts['year']) - ($w-$send_days[$w_key-1])*24*60*60;
                        } else {
                            $yesterday_wd = $send_days[$key] - $send_days[$key-1];
                            $yesterday = mktime(0,0,0,$ts['mon'],$ts['mday'],$ts['year']) - $yesterday_wd*24*60*60;
                        }
                    }
                    break;
                case  '5':
                    $today_d = date('d', $time);
                    $prev_count_d = date('d', $time - $today_d * 24 * 60 * 60); //кол-во дней в прошлом месяце
                    LOGS()->reg_log('send_report',' Количество дней в прошлом месяце '.$prev_count_d);
                    if (count($send_days)==1){ //для отчета раз в месяц
                        $yesterday_day = ($prev_count_d < $send_days[0]) ? $prev_count_d : $send_days[0]; //определяем день начала формирования отчета
                        $yesterday = mktime(0,0,0,$ts['mon']-1,$yesterday_day,$ts['year']);
                    } else {
                        $key = array_search($today_d, $send_days);
                        if ($key === 0) {//первый отчет в месяце
                            //кол-во дней за которое будет сформирован отчет
                            $count_d_report = ($prev_count_d < $send_days[count($send_days) - 1]) ? $send_days[$key] :  $send_days[$key] + $prev_count_d - $send_days[count($send_days) - 1];
                            $yesterday = mktime(0,0,0,$ts['mon'],$ts['mday'],$ts['year']) - $count_d_report*24*60*60;
                        } else if ($key === false) { //нет сегодняшнего дня в отчете => ищем ближайший
                            $day_month = 310;
                            $d_key = 32;
                            foreach ($send_days as $index => $day) {
                                if (abs($day - $today_d) < abs($today_d - $day_month)) $day_month = $day; $d_key = $index-1;
                            }
                            LOGS()->reg_log('send_report',' Ближайший день '.$day_month.' с индексом '.$d_key);
                            if ($day_month < $today_d) { //ближайший отчетный день слева от сегодня
                                $yesterday = mktime(0,0,0,$ts['mon'],$ts['mday'],$ts['year']) - ($today_d-$day_month)*24*60*60;
                            } else if ($d_key == 0) { //ближайший отчетный день справа и первый в массиве
                                $yesterday_day = ($prev_count_d < $send_days[count($send_days)-1]) ? $today_d : $today_d + $prev_count_d - $send_days[count($send_days) - 1]; //определяем день начала формирования отчета
                                $yesterday = mktime(0,0,0,$ts['mon'],$ts['mday'],$ts['year']) - $yesterday_day*24*60*60;
                            }// ближайший отчетный день справа и не первый в массиве => берем слева
                            else $yesterday = mktime(0,0,0,$ts['mon'],$ts['mday'],$ts['year']) - ($today_d-$send_days[$d_key-1])*24*60*60;
                        } else {// день есть в массиве, но он не первый по порядку => берем слева
                            $yesterday = mktime(0,0,0,$ts['mon'],$ts['mday'],$ts['year']) - ($today_d-$send_days[$key-1])*24*60*60;
                        }
                    }
                    break;
            }
        }
        return $yesterday;
    }

    function period_date_from_to($time,$time_h_m, $send_type){
        $ts = getdate($time);
        $time = date('i:s', $time_h_m);
        $arr=explode(':',$time);
        $day_w = ($ts['wday'] == 0) ? 7 : $ts['wday'];
        switch ($send_type){
            case '0':
                $start = mktime($arr[0],$arr[1],0,$ts['mon'],$ts['mday']-1,$ts['year']);
                $stop = mktime($arr[0],$arr[1]-1,59,$ts['mon'],$ts['mday'],$ts['year']);
                break;
            case '1':
                $start = mktime($arr[0],$arr[1],0,$ts['mon'],$ts['mday']-$day_w-6,$ts['year']);
                $stop = mktime($arr[0],$arr[1]-1,59,$ts['mon'],$ts['mday']-$day_w+1,$ts['year']);
                break;
            case '2':
                $start = mktime($arr[0],$arr[1],0,$ts['mon']-1,1,$ts['year']);
                $stop = mktime($arr[0],$arr[1]-1,59,$ts['mon'],1,$ts['year']);
                break;
        }
        return ['start'=>$start, 'stop'=>$stop];

    }


    function check_file_report(){
        $recs = execSQL('select t1.pkey,t1.send_parent_id,t1.file,t1.outputfile,t2.send_report_id,t2.send_email,t2.send_name,t2.send_status,t2.send_type,t3.obj_name
                    from ' . SEND_REPORT()->queue_table . ' t1 
                        left join ' . SEND_REPORT()->sender_table . ' t2
                        on t1.send_parent_id=t2.pkey
                        left join ' . SEND_REPORT()->main_table . ' t3
                            on t2.send_report_id=t3.pkey
                            where t2.send_status=2', 2, 1);
        foreach ($recs as $rec) {
            ob_start() ;
            $outputfile = $rec['outputfile'];
            if (file_exists($outputfile)) echo file_get_contents($outputfile) ;
            $text=ob_get_clean() ;
            if (strpos($text,'Done')!==false and strpos($text,'100%')!==false){
                LOGS()->reg_log('send_report',$rec['pkey'].' Отчет готов к отправке.<br><a target="_blank" href="'._PATH_TO_SITE.hide_server_dir($rec['file']).'">'.$rec['obj_name'].'</a><br> Статус изменен на "Ожидает отправки"');
                update_rec_in_table(SEND_REPORT()->sender_table,['send_status'=>1],'pkey='.$rec['send_parent_id']) ;
                $this->send_email_report_file($rec);
            } else {
//                LOGS()->reg_log('send_report',$rec['pkey'].' Отчет не сформирован');
            }
        }
    }

    function test_check_file_report($pkey_queue, $option=[]){
        $t1 = fixed_time();
        do{
            $rec = execSQL_van('select t1.pkey,t1.send_parent_id,t1.file,t1.outputfile,t2.send_report_id,t2.send_email,t2.send_name,t2.send_status,t2.send_type,t3.obj_name
                    from '.SEND_REPORT()->queue_table.' t1 
                        left join '.SEND_REPORT()->sender_table.' t2
                        on t1.send_parent_id=t2.pkey
                        left join '.SEND_REPORT()->main_table.' t3
                            on t2.send_report_id=t3.pkey
                            where t1.pkey='.$pkey_queue,2);
            ob_start();
            $outputfile = $rec['outputfile'];
            if (file_exists($outputfile)) echo file_get_contents($outputfile) ;
            $text=ob_get_clean();
//            sleep(20);
            $t2 = fixed_time();
            $diff = round($t2-$t1,2);
            if ($diff >= 20) break;
        }while (strpos($text,'Done')===false or strpos($text, '100%')===false);
        if (strpos($text,'Done')!==false and strpos($text,'100%')!==false){
            update_rec_in_table(SEND_REPORT()->sender_table,['send_status'=>1],'pkey='.$rec['send_parent_id']) ;
            $this->send_email_report_file($rec, $option);
//            LOGS()->reg_log('send_report','Генерация отчета "'.$rec['obj_name'].'" - '.$diff.'сек. файл - '.$rec['file']);
            return '<p>Генерация отчета - '.$diff.'сек.<br>Отчет направлен на почту</p>';
        } else {
            update_rec_in_table(SEND_REPORT()->sender_table,['send_status'=>1],'pkey='.$rec['send_parent_id']) ;
            return '<p>Долгая генерация отчета - '.$diff.'сек.<br>Отчет не отправлен</p>';
        }
    }

    function send_email_report_file($rec, $option=[]){
        LOGS()->reg_log('send_report',$rec['file']);
        ob_start();
            ?><strong>Добрый день!</strong><br>Отчет: <? echo '"'.$rec['obj_name'].'"';
            $text = ob_get_clean();
            $send_email = '';
            if((int)$option['type_send']){
                switch ($option['type_send']){
                    case 0:
                        $send_email = $rec['send_email'];
                        break;
                    case 1:
                        $send_email = MEMBER()->info['email'];
                        break;
                    case 2:
                        $send_email = $option['email'];
                        break;
                }
            } else {
                $send_email = $rec['send_email'];
            }
        $arr_emails=explode(',',$send_email) ;


        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;
                $mail_options['files'][] = $rec['file'];
                if (_sizeof($arr_emails)) foreach($arr_emails as $cc_email) if (trim($cc_email)) $mail_options['cc'][trim($cc_email)]=trim($cc_email) ;
                $m = MAILS()->send_mail($email,'Отчет: "'.$rec['obj_name'].'"',$text,$mail_options);
//                MAILS()->send_mail($arr_emails,'Отчет: "'.$rec['obj_name'].'"',$text,$mail_options);
            }
        adding_rec_to_table(SEND_REPORT()->journal_table,['obj_name'=>$rec['obj_name'],'send_name'=>$rec['send_name'],'send_email'=>$send_email,'send_type'=>$rec['send_type'],'date'=>date('Y-m-d H:i:s',time())]);
        LOGS()->reg_log('send_report','<a target=_blank href="'._PATH_TO_SITE.hide_server_dir($rec['file']).'">Отчет</a> направлен на почту<br>'.$m);

    }

    function breadcrumbs($href, $title){
        ?>
        <a href="<? echo $href; ?>" title="<? echo $title ?>" class="breadcrumbs">
            <span class="prev_rec">
                <i class="fa fa-chevron-left"></i>Назад</span>
        </a>
        <?
    }

    function next_sender($sender_rec){
        // если отправка настроена, ищем ближайшую
        if ($sender_rec['send_status'] != 0) {
            $time = time();
//            $time = strtotime('01.06.2020 15:03');
            $ts = getdate($time);
            $tnow = date('H', $time)*60 + date('i', $time);//кол-во минут от начала текущего дня
            $today_w = (date('w', $time) == 0) ? 7 : date('w', $time);
            $today_d = date('d', $time);
            switch ($sender_rec['send_type']){
                case '0':
                    $queue = execSQL_van('select * from '.SEND_REPORT()->queue_table.' where send_parent_id='.$sender_rec['pkey']);
                    $cnt_d = ($tnow < $queue['time_h_m']) ? 0 : 1;
                    $day = mktime(0,0,0,$ts['mon'],$ts['mday']+$cnt_d,$ts['year']) + $queue['time_h_m']*60;
                    break;
                case '1':
                    $queue = execSQL_van('select * from '.SEND_REPORT()->queue_table.' where send_parent_id='.$sender_rec['pkey']);
                    $cnt_d = ($today_w == 1 && $tnow < $queue['time_h_m']) ? 0 : 8-$today_w;
                    $day = mktime(0,0,0,$ts['mon'],$ts['mday']+$cnt_d,$ts['year']) + $queue['time_h_m']*60;
                    break;
                case '2':
                    $queue = execSQL_van('select * from '.SEND_REPORT()->queue_table.' where send_parent_id='.$sender_rec['pkey']);
                    $cnt_m = ($today_d == 1 && $tnow < $queue['time_h_m']) ? 0 : 1;
                    $day = mktime(0,0,0,$ts['mon']+$cnt_m,1,$ts['year']) + $queue['time_h_m']*60;
                    break;
                case '3': //день
                    $queue = execSQL('select * from '.SEND_REPORT()->queue_table.' where send_parent_id='.$sender_rec['pkey'],0,1);
                    $key = -1; $d = 1500;
                    foreach ($queue as $i => $item){ //ищем ближайшее время справа
                        if (abs($tnow - $item['time_h_m']) < $d && $item['time_h_m'] > $tnow) {$key = $i; $d = abs($tnow - $item['time_h_m']);}
                    }
                    //если справа время есть => к сегодня добавляем его, если нет => берем завтра и первое время в массиве
                    if ($key >= 0) $day = mktime(0,0,0,$ts['mon'],$ts['mday'],$ts['year']) + $queue[$key]['time_h_m']*60;
                    else $day = mktime(0,0,0,$ts['mon'],$ts['mday']+1,$ts['year']) + $queue[0]['time_h_m']*60;
                    break;
                case '4'://неделя
                    $queue = execSQL_van('select * from '.SEND_REPORT()->queue_table.' where send_parent_id='.$sender_rec['pkey']);
                    $send_days = unserialize($queue['send_days']);
                    $d = 8; $key = 8;
                    if ( $today_w >= $send_days[count($send_days)-1])// если на этой неделе уже не будет отправок, ближайшая след неделя
                        $day = mktime(0,0,0,$ts['mon'],$ts['mday'],$ts['year']) + (7-$today_w+$send_days[0])*24*60*60 + $queue['time_h_m']*60;
                    else {// иначе ищем ближайшИй день недели справа
                        foreach ($send_days as $i => $item){
                            if ((abs($today_w-$item) < $d) && ($item > $today_w)) {$d = $item; $key = $i;}
                        }
                        $day =  mktime(0,0,0,$ts['mon'],$ts['mday']+($send_days[$key]-$today_w),$ts['year']) + $queue['time_h_m']*60;
                    }
                    break;
                case '5'://месяц
                    $next_count_d = date('t', mktime(0,0,0,$ts['mon']+1,1,$ts['year'])); //кол-во дней в след месяце
                    $today_count_d = date('t', mktime(0,0,0,$ts['mon'],1,$ts['year'])); //кол-во дней в этом месяце
                    $queue = execSQL_van('select * from '.SEND_REPORT()->queue_table.' where send_parent_id='.$sender_rec['pkey']);
                    $send_days = unserialize($queue['send_days']);
                    if ( $today_d >= $send_days[count($send_days)-1]) //если в этом месяце уже не будет отправок, берем следующий месяц
                        ($next_count_d < $send_days[0]) //если в след месяце кол-во дней меньше первого отчетного дня (31-е число) => отчетный день - последний день месяца
                            ? $day = mktime(0,0,0,$ts['mon'],$ts['mday'],$ts['year']) + ($today_count_d-$today_d+$next_count_d)*24*60*60 + $queue['time_h_m']*60
                            : $day = mktime(0,0,0,$ts['mon'],$ts['mday'],$ts['year']) + ($today_count_d-$today_d+$send_days[0])*24*60*60 + $queue['time_h_m']*60;
                    else { // иначе ищем ближайший день справа в этом месяце
                        $d = 32; $key = 32;
                        foreach ($send_days as $i => $item){
                            if ((abs($today_d-$item) < $d) && ($item > $today_d)) {$d = $item; $key = $i;}
                        } // если ближайший отчетный день больше кол-ва дней в этом месяце => берем последний день этого месяца
                        ($today_count_d < $send_days[$key])
                            ? $day = mktime(0,0,0,$ts['mon'],$today_count_d,$ts['year']) + $queue['time_h_m']*60
                            : $day = mktime(0,0,0,$ts['mon'],$send_days[$key],$ts['year']) + $queue['time_h_m']*60;
                    }
                    break;
            }
//            return '<span class="next_sender">'.date('d.m.Y H:i', $day).'</span>';
            return date('d.m.Y H:i', $day);
        }
    }


    function get_count_active_senders($send_report_id){
        $rec = execSQL('select send_on from '.$this->sender_table.' where send_report_id = '.$send_report_id.' and send_on = 1',0,1);
        return count($rec);
    }

    function get_count_disabled_senders($send_report_id){
        $rec = execSQL('select send_status from '.$this->sender_table.' where send_report_id = '.$send_report_id.' and send_status = 0',0,1);
        return count($rec);
    }

    function get_next_sender($send_report_id){
        $ts = getdate(time());
        $time = mktime(0,0,0,$ts['mon'],$ts['mday'],$ts['year']+1);
        $now = date('d.m.Y H:i', $time);
        $recs = execSQL('select t1.*,t2.cnt_queue 
                                from ' . SEND_REPORT()->sender_table . ' t1 
                                    left join (
                                        select send_parent_id,count(pkey) as cnt_queue
                                            from '.SEND_REPORT()->queue_table.'
                                            where enabled=1 group by send_parent_id
                                    ) t2
                                    on t1.pkey=t2.send_parent_id
                                where t1.send_report_id='.$send_report_id.' and t1.send_on=1');
        foreach ($recs as $rec){
            $next = SEND_REPORT()->next_sender($rec);
            if (strtotime($now) > strtotime($next)) $now = $next;
        }
        return $now;
    }
}

?>