<?
include_once(_DIR_EXT.'/HTML/c_page_XML_AJAX.php') ;
class c_page_ajax extends c_page_XML_AJAX
{
    function add_order_type() {
        $order_types=(int) execSQL_value('select max(type) from '.PRINT_ORDER()->type_table);
        ?>
        <form class="sky-form" style="margin: 10px; box-shadow: none;">
            <div class="row">
                <section class="col col-4">
                    <label class="label">Номер:</label>
                </section>
                <section class="col col-8">
                    <label class="input">
                        <input type="text" name="order_type" id="input_order_type" data-required value="<?echo ($order_types+1)?>">
                    </label>
                </section>
            </div>
            <div class="row">
                <section class="col col-4">
                    <label class="label">Наименование:</label>
                </section>
                <section class="col col-8">
                    <label class="input">
                        <input type="text" name="order_name" data-required value="">
                    </label>
                </section>
            </div>
            <div id="panel_buttons" class="center"><input type="submit" class="button v2" cmd="print_order/add_order_type_apply" validate="form" NoSubmitFormOnEnter="1" value="Добавить"><button class="button cancel">Отмена</button></div>
        </form>
        <script type="text/javascript">
            $j(document).ready(function(){
                $j('#input_order_type').keypress(validateNumber);

                function validateNumber(event) {
                    var key = window.event ? event.keyCode : event.which;
                    if (event.keyCode === 8 || event.keyCode === 46) {
                        return true;
                    } else if ( key < 48 || key > 57 ) {
                        return false;
                    } else {
                        return true;
                    }
                };
            });
        </script>
        <?
        $this->add_element('show_modal_window','HTML',array('title'=>'Добавить тип наряда для печати')) ;
    }

    function add_order_type_apply() {
        damp_array($_POST);
        $errors=[]; $data=[];
        if (!is_numeric($_POST['order_type'])) $errors[]='Не правильно указан номер типа наряда';
        if (!$_POST['order_name']) $errors[]='Не указано наименование типа наряда';
        if (_sizeof($errors)) {
            foreach ($errors as $error) {
                $this->add_element('show_notife',$error,['color'=>'red']);
            }
        } else {
            $data['obj_name']=htmlspecialchars($_POST['order_name']);
            $data['type']=(int) $_POST['order_type'];
            $data['ext_info']['consider_time']=1;
            $data['ext_info']['type_of_get_PDF']='common';
            adding_rec_to_table(PRINT_ORDER()->type_table,$data);
            $this->update_page=1;
        }
    }

    function print_order_view_details() {

    }

    function print_order_delete() {
        if ((int) $_POST['type_order_key']) {
            $print_order=execSQL_van('select * from '.PRINT_ORDER()->type_table.' where pkey='.$_POST['type_order_key']);
            ?>
            <p class="center">Вы действительно хотите удалить тип печати наряда?</p>
            <p class="center"><strong><?echo $print_order['obj_name']?></strong> id:<strong><? echo $print_order['type']?></strong></p>
            <br>
            <p class="center"><button class="v2" cmd="print_order/print_order_delete_apply" type_order_key="<?echo $_POST['type_order_key']?>">Удалить</button>&nbsp;&nbsp;&nbsp;<button class="cancel">Отмена</button></p>
            <?
            $this->add_element('show_modal_window','HTML',array('title'=>'Удаление типа наряда')) ;
        }
    }

    function print_order_delete_apply() {
        if ((int) $_POST['type_order_key']) execSQL_update('delete from '.PRINT_ORDER()->type_table.' where pkey='.$_POST['type_order_key']);
        $this->update_page=1;
    }

    function save_print_order() {
//        damp_array($_POST);
//        damp_array($_FILES);
        $errors=[]; $data=[]; $update_test_file=false; $test_file_path=''; $old_data=[];
        $print_order_id=(int) $_POST['print_order_id'];
        if (!is_numeric($_POST['order_type'])) $errors[]='Не правильно указан ID печати';
        else {
            $cnt = execSQL_value('select count(pkey) from '.PRINT_ORDER()->type_table.' where type='.$_POST['order_type'].' and pkey!='.$print_order_id);
            if ($cnt>0) $errors[]='ID уже занят';
        }
        if (_sizeof($_FILES)) {
            if (!_sizeof($errors)) {
                if (is_uploaded_file($_FILES['test_file']['tmp_name'])) {
                    $test_file_path=PRINT_ORDER()->test_file_folder.'file_order_'.$_POST['print_order_id'];
                    $test_file_dir=_DIR_TO_ROOT.$test_file_path;
                    echo $test_file_dir.'<br>';
                    if (move_uploaded_file($_FILES['test_file']['tmp_name'],$test_file_dir)) {
                        $update_test_file=true;
                    } else {
                        $errors[]='Не удалось сохранить файл';
                    }
                } else {
                    $errors[]='Не удалось загрузить файл';
                }
            } else {
                $errors[]='Не удалось загрузить файл';
            }
        }


        if (!$_POST['obj_name']) $errors[]='Не указано наименование';
        if (_sizeof($errors)) {
            foreach ($errors as $error) {
                $this->add_element('show_notife',$error,['color'=>'red']);
            }
        } else {
            $old_data['ext_info']=execSQL_value('select ext_info from '.PRINT_ORDER()->type_table.' where pkey='.$print_order_id);
            $old_data['_ext_info']=unserialize($old_data['ext_info']);

            $data['obj_name']=$_POST['obj_name'];
            $data['type']=$_POST['order_type'];
            $data['ext_info']=$_POST['ext_info'];
            if ($data['ext_info']['type_of_get_PDF']=='own') unset($data['ext_info']['common_URL']);
            $data['ext_info']['stamp_on_page']=((int) $_POST['ext_info']['stamp_on_page']);
            $data['ext_info']['stamp_X']=(int) $_POST['ext_info']['stamp_X'];
            $data['ext_info']['stamp_Y']=(int) $_POST['ext_info']['stamp_Y'];
            $data['ext_info']['stamp_resize']=$_POST['ext_info']['stamp_resize'];
            $data['ext_info']['stamp_rotate_degrees']=(int) $_POST['ext_info']['stamp_rotate_degrees'];
            if ($update_test_file) $data['ext_info']['test_file_path']=$test_file_path; else $data['ext_info']['test_file_path']=$old_data['_ext_info']['test_file_path'];
            if (!$data['ext_info']['enable_stamp']) $data['ext_info']['enable_stamp']=0;
            update_rec_in_table(PRINT_ORDER()->type_table,$data,'pkey='.$print_order_id,['no_append_serialize_data'=>1]);
            $this->update_page=1;
        }
//        $this->add_element('show_modal_window','HTML',['title'=>'sdsd']);
    }

    function change_test_order_param() {
        $data=[]; $print_order_data=[];

        //файл с настройками печати наряда
        $json_data_file=_DIR_TO_ROOT.PRINT_ORDER()->test_file_folder.'file_order_'.$_POST['print_order_id'].'.json';

        //изменившийся параметр
        $input_field=$_POST['input_name'];
        if (stripos($input_field, 'ext_info') !== false) {
            $input_field=preg_replace([0=>'/ext_info/',1=>'/\[/',2=>'/\]/'],'',$input_field);
        }

        //получаем старые данные для печати штампа
        $print_order_data=json_decode(file_get_contents($json_data_file),true);

        //сохраняем старое значение, перезаписываем новое
        $old_field_value=$print_order_data[$input_field];
        $print_order_data[$input_field]=$_POST['value'];

        //обновление данных для печати штампа
        file_put_contents($json_data_file,json_encode($print_order_data));

        $this->copy_order_image($print_order_data['stamp_on_page'],$_POST['print_order_id'],['data_for_stamp'=>$print_order_data]);

        if ($input_field=='stamp_on_page') {
            $this->copy_order_image($old_field_value,$_POST['print_order_id']);
        }
    }

    function copy_order_image($page_number,$order_pkey,$options=[]) {
        $file='file_order_'.$order_pkey.'_page_'.$page_number.'.jpg';
        $file_to=_DIR_TO_ROOT.'/temp/'.$file;
        $file_from=_DIR_TO_ROOT.PRINT_ORDER()->test_file_folder.$file;
        //копируем исходный файл jpg листа в temp директорию
        copy($file_from,$file_to);

        //ставим штамп на чистый файл
        if ($options['data_for_stamp']) {
            $rec_mo=execSQL_van('select * from '.ESMO()->view_mo_session.' where dopusk=1 order by pkey desc limit 1');
            PRINT_ORDER()->put_stamp_on_image($file_to,$rec_mo,$options['data_for_stamp']);
        }

        //обновляем файл
        $this->add_element('order_page_'.$page_number.'.SRC','/temp/'.$file.'?'.microtime());
    }

}
