<?
include_once(_DIR_EXT . '/HTML/c_page_XML_AJAX.php');

class c_page_ajax extends c_page_XML_AJAX
{
    function update_report_list()
    {
        $result = send_report()->update_report_list();

        damp_array($result);

        $this->add_element('show_modal_window', 'HTML', ['title' => 'sdsd']);
    }

    function print_order_apply()
    {
        if (is_numeric($_POST['send_report_id'])) {
            include_once(_DIR_EXT . '/send_report/panel_send_report_td.php');
            $send_report = SEND_REPORT()->get_send_report_by_id($_POST['send_report_id']);

            if ($send_report['status'] == 0) {
                $cnt = execSQL_update('update ' . SEND_REPORT()->main_table . ' set status=1 where pkey=' . $send_report['pkey']);
                if ($cnt) {
                    $send_report = SEND_REPORT()->get_send_report_by_id($_POST['send_report_id']);
                    ob_start();
                    panel_send_report_td($send_report);
                    $html_tr = ob_get_clean();

                    $this->add_element('send_report_' . $send_report['pkey'] . '.HTML', $html_tr);
                }
            }
        }
    }

    function create_new_sender()
    {
        if (is_numeric($_POST['send_report_id'])) {
            $sender_id = SEND_REPORT()->create_new_sender($_POST['send_report_id']);
            if ($sender_id) $this->go_url = '/cab/send_report/sender/' . $sender_id . '/';
        }
    }

    function create_new_queue()
    {
        if (isset($_POST['send_type'])) {
            $send_type = $_POST['send_type'];
//            damp_array($_POST);

            switch ($send_type) {
                case 0:
                    ((count($_POST['period_day_time'])) == 0) ?
                        $this->add_element('show_notife', 'Не добавлено время', array('color' => 'red'))
//                        : ($this->checkEmail($_POST['send_email'])) ? $this->create_new_queue_day($_POST['day_time'], $_POST['sender_id'], $send_type, $_POST['send_email']) : false;
                        : ($this->checkEmail($_POST['send_email'])) ? $this->create_new_period_queue($_POST) : false;
                    break;
                case 1:
                    ((count($_POST['period_week_time'])) == 0) ?
                        $this->add_element('show_notife', 'Не добавлено время', array('color' => 'red'))
//                        : ($this->checkEmail($_POST['send_email'])) ? $this->create_new_queue_day($_POST['day_time'], $_POST['sender_id'], $send_type, $_POST['send_email']) : false;
                        : ($this->checkEmail($_POST['send_email'])) ? $this->create_new_period_queue($_POST) : false;
                    break;
                case 2:
                    ((count($_POST['period_month_time'])) == 0) ?
                        $this->add_element('show_notife', 'Не добавлено время', array('color' => 'red'))
//                        : ($this->checkEmail($_POST['send_email'])) ? $this->create_new_queue_day($_POST['day_time'], $_POST['sender_id'], $send_type, $_POST['send_email']) : false;
                        : ($this->checkEmail($_POST['send_email'])) ? $this->create_new_period_queue($_POST) : false;
                    break;
                case 3:
                    ((count($_POST['day_time'])) == 0) ?
                        $this->add_element('show_notife', 'Не добавлено время', array('color' => 'red'))
//                        : ($this->checkEmail($_POST['send_email'])) ? $this->create_new_queue_day($_POST['day_time'], $_POST['sender_id'], $send_type, $_POST['send_email']) : false;
                        : ($this->checkEmail($_POST['send_email'])) ? $this->create_new_queue_day($_POST) : false;
                    break;
                case 4:
                    if (count($_POST['week_days']) == 0) {
                        $this->add_element('show_notife', 'Не выбран день', array('color' => 'red'));
                    } else {
                        ($_POST['week_time'][0] == '') ?
                            $this->add_element('show_notife', 'Не выбрано время', array('color' => 'red'))
//                            : ($this->checkEmail($_POST['send_email'])) ? $this->create_new_queue_week_month($_POST['week_time'], $_POST['week_days'], $_POST['sender_id'], $send_type, $_POST['send_email']) : false;
                            : ($this->checkEmail($_POST['send_email'])) ? $this->create_new_queue_week_month($_POST) : false;

                    }
                    break;
                case 5:
                    if (count($_POST['month_days']) == 0) {
                        $this->add_element('show_notife', 'Не выбран день', array('color' => 'red'));
                    } else {
                        ($_POST['month_time'][0] == '') ?
                            $this->add_element('show_notife', 'Не выбрано время', array('color' => 'red'))
//                            : ($this->checkEmail($_POST['send_email'])) ? $this->create_new_queue_week_month($_POST['month_time'], $_POST['month_days'], $_POST['sender_id'], $send_type, $_POST['send_email']) : false;
                            : ($this->checkEmail($_POST['send_email'])) ? $this->create_new_queue_week_month($_POST) : false;
                    }
                    break;
            }
        }
//        adding_rec_to_table(SEND_REPORT()->queue_table,$data);
//                    $this->add_element('show_modal_window','HTML',array('title'=>'')) ;
    }


//    function create_new_queue_day($arr_time, $send_parent_id, $send_type, $email){
    function create_new_queue_day($data){
        $filters = isset($data['filter']) ? $data['filter'] : '';
        damp_array($data);
//        echo $filters;
        // проверяем кол-во записей с таким $send_parent_id
        $count_rec = execSQL('select * from '.SEND_REPORT()->queue_table.' where send_parent_id='.$data['sender_id']);
        //  если записи есть, то удаляем их (перезапишем на новые)
        if (count($count_rec) > 0) {
            execSQL_update('delete from '.SEND_REPORT()->queue_table.' where send_parent_id='.$data['sender_id']);
        }
        // добавляем новые записи для дня (1 запись => 1 время)
        foreach ($data['day_time'] as $time){
            $arr=explode(':',$time); //переводим время в минуты от начала дня
            $ts = $arr[0]*60 + $arr[1];
            adding_rec_to_table(SEND_REPORT()->queue_table,['send_parent_id'=>$data['sender_id'],'time_h_m'=>$ts]);
        }
        // Обновляем send_type (период цикла) в send_report_sender
        update_rec_in_table(SEND_REPORT()->sender_table,['send_type'=>$data['send_type'], 'send_email'=> $data['send_email'], 'send_status'=>1, 'filters'=>$filters, 'send_name' => $data['send_name']],'pkey='.$data['sender_id'],['no_append_serialize_data'=>1]) ;
        $this->add_element('show_notife','Сохранено',array('color'=>'green'));
        $this->update_page=1;
    }

//    function create_new_queue_week_month($arr_time, $arr_days, $send_parent_id, $send_type, $email){
    function create_new_queue_week_month($data){
        $filters = isset($data['filter']) ? $data['filter'] : '';
        $arr_days = ($data['send_type'] == 4) ? $data['week_days'] : $data['month_days'];
        $arr_time = ($data['send_type'] == 4) ? $data['week_time'] : $data['month_time'];
        // проверяем кол-во записей с таким $send_parent_id
        $count_rec = execSQL('select * from '.SEND_REPORT()->queue_table.' where send_parent_id='.$data['sender_id']);
        //  если записи есть, то удаляем их (перезапишем на новые)
        if (count($count_rec) > 0) {
            execSQL_update('delete from '.SEND_REPORT()->queue_table.' where send_parent_id='.$data['sender_id']);
        }
//        $data['send_type'] = $send_type;
        $ts='';
        foreach ($arr_days as $week_day){
            $data['send_days'][] = $week_day;
        }
        foreach ($arr_time as $time){
            $arr=explode(':',$time); //переводим время в минуты от начала дня
            $ts = $arr[0]*60 + $arr[1];
        }
        // добавляем новые записи для недели/месяца
        adding_rec_to_table(SEND_REPORT()->queue_table,['send_parent_id'=>$data['sender_id'],'time_h_m'=>$ts,'send_days'=>$data['send_days']]);
        // Обновляем send_type (период цикла) в send_report_sender
        update_rec_in_table(SEND_REPORT()->sender_table,['send_type'=>$data['send_type'], 'send_email'=> $data['send_email'], 'send_status'=>1, 'filters'=>$filters, 'send_name' => $data['send_name']],'pkey='.$data['sender_id'],['no_append_serialize_data'=>1]) ;
        $this->add_element('show_notife','Сохранено',array('color'=>'green'));
        $this->update_page=1;
    }

    function create_new_period_queue($data){
        $filters = isset($data['filter']) ? $data['filter'] : '';
//        damp_array($data);
////        echo $filters;
        // проверяем кол-во записей с таким $send_parent_id
        $count_rec = execSQL('select * from '.SEND_REPORT()->queue_table.' where send_parent_id='.$data['sender_id']);
        //  если записи есть, то удаляем их (перезапишем на новые)
        if (count($count_rec) > 0) {
            execSQL_update('delete from '.SEND_REPORT()->queue_table.' where send_parent_id='.$data['sender_id']);
        }
//        // добавляем новые записи для дня (1 запись => 1 время)

        switch ($data['send_type']){
            case 0:
                $arr=explode(':',$data['period_day_time'][0]); //переводим время в минуты от начала дня
                $ts = $arr[0]*60 + $arr[1];
                adding_rec_to_table(SEND_REPORT()->queue_table,['send_parent_id'=>$data['sender_id'],'time_h_m'=>$ts]);
                break;
            case 1:
                $arr=explode(':',$data['period_week_time'][0]); //переводим время в минуты от начала дня
                $ts = $arr[0]*60 + $arr[1];
                adding_rec_to_table(SEND_REPORT()->queue_table,['send_parent_id'=>$data['sender_id'],'time_h_m'=>$ts]);
                break;
            case 2:
                $arr=explode(':',$data['period_month_time'][0]); //переводим время в минуты от начала дня
                $ts = $arr[0]*60 + $arr[1];
                adding_rec_to_table(SEND_REPORT()->queue_table,['send_parent_id'=>$data['sender_id'],'time_h_m'=>$ts]);
                break;
        }
        update_rec_in_table(SEND_REPORT()->sender_table,['send_type'=>$data['send_type'], 'send_email'=> $data['send_email'], 'send_status'=>1, 'filters'=>$filters, 'send_name' => $data['send_name']],'pkey='.$data['sender_id'],['no_append_serialize_data'=>1]) ;
        $this->add_element('show_notife','Сохранено',array('color'=>'green'));
        $this->update_page=1;
    }

    function checkEmail($str_email){
        $arr_email = explode(',', $str_email);
//        damp_array($arr_email);
        foreach ($arr_email as $address){
            $valid = preg_match('/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!\.)){0,61}[a-zA-Z0-9_-]?\.)+[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!$)){0,61}[a-zA-Z0-9_]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/', $address);
            if ($valid != 0) true;
            else {
                $this->add_element('show_notife','Не корректный email </br>'.$address,array('color'=>'red'));
                return false;
            }
        }
        return true;
    }

//    function delete_sender(){
//        if ((int) $_POST['sender_key']){
//            echo $_POST['sender_key'];
//            $this->add_element('show_modal_window', 'HTML', ['title' => 'test']);
//        }
//    }

    function delete_sender() {
        if ((int) $_POST['sender_key']) {
//            $print_order=execSQL_van('select * from '.PRINT_ORDER()->type_table.' where pkey='.$_POST['type_order_key']);
            $rec = execSQL_van('select t1.send_type,t2.obj_name
                    from '.SEND_REPORT()->sender_table.' t1
                        left join '.SEND_REPORT()->main_table.' t2
                            on t1.send_report_id=t2.pkey
                            where t1.pkey='.$_POST['sender_key']);
            ?>
            <p class="center">Вы действительно хотите удалить отправку № <? echo $_POST['index']?>?</p>
            <p class="center">Отчет "<? echo $rec['obj_name'] ?>"</p>
            <p class="center">Вид: <?
                    switch ($rec['send_type']) {
                        case '0': echo 'Период день'; break;
                        case '1': echo 'Период неделя'; break;
                        case '2': echo 'Период месяц'; break;
                        case '3': echo 'Цикл день'; break;
                        case '4': echo 'Цикл неделя'; break;
                        case '5': echo 'Цикл месяц'; break;
                    }
                    ?></p>
            <br>
            <p class="center"><button class="v2" cmd="send_report/delete_sender_apply" sender_key="<?echo $_POST['sender_key']?>">Удалить</button>&nbsp;&nbsp;&nbsp;<button class="cancel">Отмена</button></p>
            <?
            $this->add_element('show_modal_window','HTML',array('title'=>'Удаление отправки отчета')) ;
        }
    }

    function delete_sender_apply() {
        if ((int) $_POST['sender_key']){
            execSQL_update('delete from '.SEND_REPORT()->sender_table.' where pkey='.$_POST['sender_key']);
            execSQL_update('delete from '.SEND_REPORT()->queue_table.' where send_parent_id='.$_POST['sender_key']);
        }
        $this->update_page=1;
    }

//    function save_filters(){
////        сохраняем фильтр в БД
//        update_rec_in_table(SEND_REPORT()->sender_table,['filters'=>$_POST['filter']],'pkey='.$_POST['send_parent_id'],['no_append_serialize_data'=>1]) ;
//        $this->add_element('show_notife','Сохранено',array('color'=>'green'));
////        data-name
////        damp_array($_POST);
////        $this->add_element('show_modal_window','HTML',array('title'=>'Удаление отправки отчета')) ;
//
//    }

    function test_report(){
        if ((int) $_POST['sender_key']){
            $mail_list = explode(',',$_POST['send_email']);
            ?>
            <div id="test_report" hidden >
                <div id="test_report_result">
                    <img id="load_gif" src="/images/loading17.gif">
                </div>
                <p class="center"><button class="cancel">Закрыть</button></p>
            </div>
            <div id="form_test_report">
                <form >
                    <p class="">Сформировать отчет и отправить: </p>
                    <label class="radio"><input type="radio" name="type_send" value="0" checked><i></i>Всем получателям</label>
                    <div class="email_list">
                        <? foreach ($mail_list as $mail){
                            echo '<div><span>'.$mail.'</span></div>';
                        } ?>
                    </div>
                    <? if(MEMBER()->info['email'] != '') {?>
                        <label class="radio"><input type="radio" name="type_send" value="1" ><i></i>Администратору: <? echo MEMBER()->info['email'] ?></label>
                    <?}?>
                <label class="radio"><input type="radio" name="type_send" value="2" ><i></i>Другой e-mail</label>
                    <input type="text" name="email" placeholder="введите Ваш email" disabled>
                <br>
                <p class="center"><button class="v2" id="btn_test_report" cmd="send_report/test_report_applay" sender_key="<?echo $_POST['sender_key']?>">Отправить</button>&nbsp;&nbsp;&nbsp;<button class="cancel">Отмена</button></p>
                </form>
            </div>
            <script>
                $j('#btn_test_report').on('click',function () {
                    $j('#form_test_report').hide();
                    $j('#test_report').show();
                })

                $j('[type = radio]').on('click', function () {
                    console.log($j(this).val());
                    ($j(this).val() == 2) ? $j('[name = email]').removeAttr('disabled') : $j('[name = email]').attr('disabled', true);
                    ($j(this).val() != 0) ? $j('#form_test_report .email_list').css('opacity', 0.5) : $j('.email_list').css('opacity', 1);
                })
            </script>
            <?
            $this->add_element('show_modal_window','HTML',array('title'=>'Тестовая отправка')) ;
        }
    }


    function test_report_applay(){
        if ((int) $_POST['sender_key']){
            $time = time();
            $time_now = date('H:i',$time);
            $arr=explode(':',$time_now);
            $ts = $arr[0]*60 + $arr[1]; // текущее время от начала дня в минутах
            $send_parent_id = $_POST['sender_key'];
            $recs = execSQL('select t1.pkey,t1.time_h_m,t1.send_days,t2.send_report_id,t2.filters,t2.send_status,t2.send_type
                    from '.SEND_REPORT()->queue_table.' t1
                        left join '.SEND_REPORT()->sender_table.' t2
                        on t1.send_parent_id=t2.pkey
                        where t1.send_parent_id='.$send_parent_id,2);
            if (count($recs) == 0){
                $this->add_element('show_notife','Не настроена отправка',array('color'=>'red'));
                return;
            }
            //ищем ближайшее время отправки, для которого будет расчитыватся отрезок формирования отчета
            $near_queue = ['time_h_m'=>0, 'abs'=>86400];
            foreach ($recs as $rec){
                echo 'ts - time_h_m = '.$ts.' - '.$rec['time_h_m'].' = '.abs($ts - $rec['time_h_m']).'<br>';
                if (abs($ts - $rec['time_h_m']) < $near_queue['abs']) {
                    $near_queue['time_h_m'] = $rec['time_h_m'];
                    $near_queue['abs'] = abs($ts - $rec['time_h_m']);
                    $near_queue['queue_id'] = $rec['pkey'];
                }
                $near_queue['send_type'] = $rec['send_type'];
                $filters = unserialize($rec['filters']);
                $send_report_id = $rec['send_report_id'];
                $send_days = unserialize($rec['send_days']);
            }
            LOGS()->reg_log('send_report','Тип '.$near_queue['send_type'].' Количество дней в отправке - '.count($send_days).' $send_report_id - '.$send_report_id.' $send_parent_id - '.$send_parent_id.
                ' $time - '.$time.' - '.date('d.m.Y', $time));
            SEND_REPORT()->create_PDF_file($time,$near_queue['time_h_m'],$send_report_id,$filters,$near_queue['queue_id'],$send_parent_id,$near_queue['send_type']);
            $diff = SEND_REPORT()->test_check_file_report($near_queue['queue_id'], $_POST);
            $this->add_element('test_report_result.HTML',$diff);
//            $this->add_element('show_notife',$diff,array('color'=>'green'));
        }

    }

    function on_off_sender(){
//        damp_array($_POST);
        if ($_POST['sender_key']){
            update_rec_in_table(SEND_REPORT()->sender_table,['send_on'=>$_POST['send_on']],'pkey='.$_POST['sender_key']) ;
//            $this->update_page=1;
            $send_on = ($_POST['send_on'] != 0) ? SEND_REPORT()->sender_status[$_POST['send_status']]
                .'<br><span class="next_sender">'.SEND_REPORT()->next_sender(array('pkey'=>$_POST['sender_key'],'send_status'=>$_POST['send_status'], 'send_type'=>$_POST['send_type'])).'</span>'
                : 'Отключен';
            $this->add_element('next_sender_'.$_POST['sender_key'].'.HTML', $send_on);
//            $this->add_element('show_modal_window','HTML',array('title'=>'Тестовая отправка')) ;

        }
    }
}