<?
if (_ENGINE_MODE=='site') include (_DIR_TO_ROOT."/vendor/autoload.php") ;
use FG\ASN1\ASNObject;

include_once(_DIR_EXT.'/HTML/c_page_XML_AJAX.php') ;
class c_page_ajax extends c_page_XML_AJAX
{

    function client_save()
    {

        $result=ESMO_FR()->client_save($_POST['client_id'], $_POST['client']) ;
        //
        if ($result['status']=='success') $this->update_page=1 ;
        else
        {   //damp_array($_POST);
            $this->add_element('show_modal_window','HTML','client_save');
            echo $result['text'] ;
            damp_array($result);
        }

    }

    function parse_packet()
    {
        $result=PL()->titul1_packet_parsing($_POST['packet_id'],['debug'=>1]) ;
        damp_array($result,1,-1);
        ?><button class="button cancel">Закрыть</button><?
        $this->add_element('show_modal_window','HTML',['title'=>'Обработка пакета','after_close_update_page'=>1]);
    }

		// проверка наличия МО для титула
    function check_packet_mo()
    {
				$packet_id=(int)$_POST['packet_id'];
				$doctor_id=(int)$_POST['doctor_id'];
			  $_usl=[] ;
				if ($packet_id) $_usl[]='t1.pkey='.$packet_id ;
				if ($doctor_id) $_usl[]='t3.doctor_id='.$doctor_id ;
				$usl_select=(sizeof($_usl))? implode(' and ', $_usl):'false' ;
        $recs_packets=execSQL('select t1.*
															 from pl_packets t1
            									 left join pl_packet_driver t2 on t2.packet_id=t1.pkey
            									 left join obj_site_mo_session_now t3 on t3.pkey=t2.mo_id
            									 where '.$usl_select) ;
        $result=PL()->packet_check_mo_union($recs_packets,['debug'=>1]) ;
        //print_2x_arr($recs_packets);
        damp_array($result);
        ?><button class="button cancel">Закрыть</button><?
        $this->add_element('show_modal_window','HTML',['title'=>'Проверка МО пакета','after_close_update_page'=>1,'width'=>'1000px']);
    }

		// отправка на подпись фельдшеру титулов, которым найдено МО
		function send_to_sing()
		{
			$packet_id=((int)$_POST['packet_id'])?:0;
			$doctor_id=((int)$_POST['doctor_id'])?:0;
			$group_id=((int)$_POST['group_id'])?:0;

			//echo '$doctor_id='.$doctor_id.'<br>' ;
			//echo '$packet_id='.$packet_id.'<br>' ;
			// group_id будет передано со вкладки Мониторинг/Монитор ПЛ/Подписать все титулы группы
			// packet_id будет передано со вкладки Путевой лист/Отчет по пакетам/Подписать титул
			$recs_packets=PL()->get_packets_to_sign(['packet_id'=>$packet_id,'group_id'=>$group_id]) ;
			//print_2x_arr($recs_packets);
			if ($packet_id) $this->add_element('show_modal_window','HTML',['title'=>'Проверка подписи пакета','after_close_update_page'=>1]);

		if (sizeof($recs_packets))
		{ $message_type=($packet_id)? 'data_to_sign':'data_to_sign_pl' ;
			$result=PL()->packet_send_xml_to_sign($recs_packets, ['debug'=>1,'message_type'=>$message_type]);
			/*damp_array($result,1,-1);
			  ?><button class="button cancel">Закрыть</button><?
			  $this->add_element('show_modal_window','HTML',['title'=>'Проверка подписи пакета','after_close_update_page'=>1]);
			  */
			$this->add_element('show_notife', 'Отправлено на подпись: '.sizeof($result).' пакетов', ['color'=>'green']);
		}
		else
		{
			$this->add_element('show_notife', 'Пакеты на подпись отсутствуют', ['color'=>'red']);
		}
	}


	function check_packet_sign()
    {

        $result=PL()->titul_packet_check_sign($_POST['packet_id'],['debug'=>1]) ;
        damp_array($result,1,-1);
        ?><button class="button cancel">Закрыть</button><?
        $this->add_element('show_modal_window','HTML',['title'=>'Проверка подписи пакета','after_close_update_page'=>1]);
    }

		function set_packet_sign_status()
		{
			ob_start() ;
			damp_array($_POST,1,-1);
			$packet_id=(int)$_POST['packet_id'];
			if (!$packet_id) $packet_id=(int)mb_str_replace('packet_xml_', '', $_POST['packet_uid']);
			$result=PL()->titul_packet_check_sign($packet_id,['debug'=>1]) ;
			damp_array($result,1,-1);
			if ($result['error_code'])  $this->add_element('error_code', $result['error_code']);
			else $this->add_element('show_notife', 'Пакет '.$packet_id.' успешно подписан', ['color'=>'green']);
			$text=ob_get_clean() ;
			LOGS()->reg_log('set_packet_sign_status', $text) ;
		}

    function show_packet_xml()
    {
        $rec_packet=PL()->get_packet_by_id($_POST['packet_id']) ;
        $titul2_fname=PL()->get_file_dir_by_packet_id($rec_packet['packet_type'],$rec_packet['pkey'],'xml') ;
        echo 'Файл: <strong>'.hide_server_dir($titul2_fname).'</strong><br>' ;
        $xml_content=file_get_contents($titul2_fname) ;
        ?><link rel="stylesheet" href="/AddOns/EnlighterJS/dist/enlighterjs.min.css"/>
           <script type="text/javascript" src="/AddOns/EnlighterJS/dist/enlighterjs.min.js"></script>
            <script type="text/javascript">
                // INIT CODE - simple page-wide initialization based on css selectors
                // - highlight all pre + code tags (CSS3 selectors)
                // - use javascript as default language
                // - use theme "enlighter" as default theme
                // - replace tabs with 2 spaces
                EnlighterJS.init('pre', 'code', {
                        language : 'javascript',
                        theme: 'enlighter',
                        indent : 2
                });
            </script>
        <pre data-enlighter-language="less"><? echo ENGINE()->htmlentities_open_tag($xml_content) ?></pre>
        <button class="button cancel">Закрыть</button>
        <?
        $this->add_element('show_modal_window','HTML',['title'=>'Содержимое XML-пакета','width'=>'1000px']);
    }

    function show_packet_sign()
    {
        $rec_packet=PL()->get_packet_by_id($_POST['packet_id']) ;
        $titul_sign_fname=PL()->get_file_dir_by_packet_id($rec_packet['packet_type'],$rec_packet['pkey'],'sign') ;
        echo 'Файл: <strong>'.hide_server_dir($titul_sign_fname).'</strong><br>' ;
        $bin_content=file_get_contents(removeBOM($titul_sign_fname)) ;



    //$base64String = ...
    //$binaryData = base64_decode($base64String);
    $asnObject = ASNObject::fromBinary($bin_content);
    $json = json_encode((array)$asnObject) ;
    //print_r($data);

        //$xml_content_utf8=iconv('windows-1251', 'UTF-8', $xml_content) ;
        ?><link rel="stylesheet" href="/AddOns/EnlighterJS/dist/enlighterjs.min.css"/>
           <script type="text/javascript" src="/AddOns/EnlighterJS/dist/enlighterjs.min.js"></script>
            <script type="text/javascript">
                // INIT CODE - simple page-wide initialization based on css selectors
                // - highlight all pre + code tags (CSS3 selectors)
                // - use javascript as default language
                // - use theme "enlighter" as default theme
                // - replace tabs with 2 spaces
                EnlighterJS.init('pre', 'code', {
                        language : 'javascript',
                        theme: 'enlighter',
                        indent : 2
                });
            </script>
        <pre data-enlighter-language="less"><? echo $json ?></pre>
        <button class="button cancel">Закрыть</button>
        <?
        $this->add_element('show_modal_window','HTML',['title'=>'Содержимое XML-пакета','width'=>'1000px']);
    }

	function account_togge_f2()
	{
		$account_id=MEMBER()->id ;
		$checked=($_POST['checked']=='true')? 1:0 ;
		$res = ACCOUNTS()->member_save($account_id,['ext_info'=>['pl_sign_delicate'=>$checked]]);
		$this->add_element('show_notife', 'Сохранено', ['color'=>'green']);
		//$this->add_element('show_modal_window','HTML',['title'=>'account_togge_f2','width'=>'1000px']);
	}

}
