<?php
include_once('i_mo_import.php');
class c_services_autonomous_terminals_upload_mo extends i_mo_import
{
    public $file_data;

    function exec()
    {
        FILE_LOG()->append('VIEW_SOURCE: ' . (($this->view_source) ? 'ON' : 'OFF'));
        FILE_LOG()->append('READ_ONLY: ' . (($this->read_only) ? 'ON' : 'OFF'));
        FILE_LOG()->append('FULL_UPDATE: ' . (($this->full_update) ? 'YES' : 'NO'));

        //проверка API KEY
        $headers = getallheaders();

        //LOGS()->reg_log('test_upload_mo','',array('data'=>$headers)) ;

        $file_ext = $this->type_file($headers['Content-Type']);
        if (!$file_ext) {
            header('HTTP/1.1 400 Bad Request');
            $result['Code'] = 400;
            $result['Comment'] = 'Проверьте наличие Content-Type в заголовках';
            print_r($result) ;
            return;
        }
        $access = AUTONOMOUS_TERMINALS()->check_access($headers['Authorization']);
        if (!$access) {
            header('HTTP/1.0 401 Unauthorized');
            $result['Code'] = 401;
            $result['Comment'] = 'Unauthorized';
            print_r($result) ;
            return;
        }

        ob_start();
        if (!$this->setting['upload_fname']) {
            $XML_cont = file_get_contents("php://input");

            $temp_fdir = hide_server_dir(_TEMP_DIR . $this->session_uid . $file_ext);
            file_put_contents(_DIR_TO_ROOT . $temp_fdir, $XML_cont);
            if ($file_ext == '.xml') {
                $comment[] = 'XML данные сохранены во временном файле: <a target="_blank" href="'._DIR_TO_ROOT.$temp_fdir.'">'.$temp_fdir.'</a>';
            } else {
                $comment[] = 'JSON данные сохранены во временном файле: <a target="_blank" href="'._DIR_TO_ROOT.$temp_fdir.'">'.$temp_fdir.'</a>';
            }
            $this->setting['upload_fname'] = $temp_fdir;
            $this->view_result_mode = 1;
        }

        // переносим данные в массив
        if ($file_ext == '.xml') $this->file_data = AUTONOMOUS_TERMINALS()->import_data_xml($this->setting['upload_fname']);
        else $this->file_data = AUTONOMOUS_TERMINALS()->import_data_json($this->setting['upload_fname']);

        if (!$this->file_data) {
            header('HTTP/1.1 400 Bad Request');

            $result['Code'] = 400;
            $result['Comment'] = 'Формат файла не распознан. Выберите файл с форматом .xml или .json';
            print_r($result) ;
            return;
        }

        header('HTTP/1.1 200 OK');
        $result['Code'] = 200;
        list($terminal_info,$type,$error) = AUTONOMOUS_TERMINALS()->search_terminal($this->file_data[0]);
        if (!$terminal_info) {
            LOGS()->reg_log('add_termianls_upload_mo','Ошибка при создании нового терминала',array('data'=>$error)) ;
            return;
        }
        if ($type == 'new') $comment[] = 'Добавлен терминал с id='.$terminal_info['id'].'; pkey='.$terminal_info['pkey'];
        else $comment[] = 'Найден терминал с id='.$terminal_info['id'].'; pkey='.$terminal_info['pkey'];
        $import_result = $this->import_temp_table_into_db($this->file_data);

        $result['relation_count']=$import_result['relation_count'] ;
        $result['relation_adding']=$import_result['relation_adding'] ;
        $result['comment'] = $comment;
        $result['comment'][] = 'Импорт данных завершен';
        $comment = array_merge($comment, $import_result['comment']);

        adding_rec_to_table('obj_site_post_log',array('obj_name'=>'upload_mo','IP'=>$_SERVER['REMOTE_ADDR'],'result'=>$result,'session_uid'=>$this->session_uid,'clss'=>362),array('debug'=>0)) ;

        print_1x_arr($comment);
        LOGS()->reg_log('upload_mo','<a target=_blank href="'.$this->page_output.'">Отчет</a><br><a href="/temp/full_'.basename($this->log_fname).'" target=_blank>Лог загрузки</a><br><a href="'.$this->log_bash.'" target=_blank>Лог BASH</a>',array()) ;

        $text=ob_get_clean() ;
        $trace_text=ENGINE()->get_html_doc_content($text) ;
        $trace_fname='import_trace_'.$this->session_uid.'.html' ;
        LOGS()->reg_file_log($trace_fname,$trace_text,array('no_append_time'=>1,'return_logfname'=>1)) ;

        $result['comment'] = implode(', ',$result['comment']);
        print_r($result) ;
    }

    function type_file($content_type)
    {
        if ($content_type == 'application/json') return '.json';
        else if ($content_type == 'application/atom+xml' or $content_type == 'application/soap+xml' or
                 $content_type == 'application/xhtml+xml' or $content_type == 'application/xml-dtd' or
                 $content_type == 'application/xop+xml' or $content_type == 'application/xml' or
                 $content_type == 'text/xml') return '.xml';
        else return false;
    }

}