<?
include_once(_DIR_EXT.'/HTML/c_page_XML_AJAX.php') ;
class c_page_ajax extends c_page_XML_AJAX
{
    function check_member()
    { // только в этом ext не проверять авторизацию
        //if (!MEMBER()->id) { $this->add_element('go_url','/cab/') ; return(0) ; }
        return(1) ;
    }

    private function setDefaultTimezone()
    {
        $arm_data=ACCOUNTS()->get_group_id_to_ARM_by_ip(IP);
        if (is_array($arm_data) and $arm_data['group_id']) {
            $group_id=$arm_data['group_id'];
            $group_rec = ACCOUNTS()->get_group_by_id($group_id);
            if ($group_rec['_ext_info']['timezone']) {
                date_default_timezone_set($group_rec['_ext_info']['timezone']);
            }
        }
    }

    public function getMOInfo()
    { $propusk_id=$_POST['passNumber'] ;
      $rec_person=PERSONAL()->get_personal(array('propusk'=>$propusk_id,'tab_number'=>$propusk_id),array('only_enabled'=>1,'set_rules'=>1,'set_QR_code'=>$GLOBALS['LS_person_field_to_qrcode'],'dop_usl'=>'enabled=1')) ;
      if ($rec_person['pkey'])
      {
          $this->setDefaultTimezone();

          ob_start();
          // если включена настройка LS_post_print_tk_1 то передаем опцию no_check_tk - не проверятим тип МО
          $rec_mo=ESMO()->check_active_dopusk($rec_person['pkey'],array('dopusk'=>1,'debug'=>0,'no_check_tk'=>$GLOBALS['LS_post_print_tk_1'])) ;
          $txt=ob_get_clean();
          $rec_account=ACCOUNTS()->get_member_by_id($rec_mo['doctor_id']) ;
          $rec_license=['number'=>$GLOBALS['LS_terminal_ticket_license_number'],'date'=>$GLOBALS['LS_terminal_ticket_license_date']] ;
          $text=($rec_mo['tk']==1)? $GLOBALS['LS_mo_ticket_text_tk1']:$GLOBALS['LS_mo_ticket_text'] ;
          $thermal_message = ($rec_mo['tk']==1)? $GLOBALS['LS_term_ticket_text_tk1']:$GLOBALS['LS_term_ticket_text_tk0'] ;
          if (preg_match_all('/\{(.+?)\}/is',$text,$matches,PREG_SET_ORDER))
              if (_sizeof($matches)) foreach($matches as $match)
              {  $arr=explode('/',$match[1]) ;
                 $type=$arr[0] ; echo 'type='.$type.'<br>' ;
                 switch($type)
                 { case 'mo': $rec=$rec_mo ; break ;
                   case 'doctor': $rec=$rec_account ; break ;
                   case 'license': $rec=$rec_license ; break ;
                   default: $rec=array() ;
                 }
                 $value='' ;
                 if (_sizeof($arr)==2) $value=$rec[$arr[1]] ;
                 else if (_sizeof($arr)==3) $value=$rec[$arr[1]][$arr[2]] ;
                 echo 'value='.$value.'<br>' ;
                 $text=str_replace($match[0],$value,$text) ;
              }
          // \n - нарушает структутра JS
	      $text=str_replace("\n",'',$text) ;

          if($rec_mo['pkey'])
          {

              //если включен модуль печати нарядов, то печатаем наряд, иначе стандартный тикет
              if (function_exists('PRINT_ORDER')) {
                $print_order=false;
                if (!$rec_mo['tk']) {
                    list($print_order,$print_order_errors)=PRINT_ORDER()->check_print_order($rec_person);
                }
                if ($print_order) {
                    $images=PRINT_ORDER()->combine_print_order_images($rec_person,$rec_mo);
                    ob_start();
                    PRINT_ORDER()->view_print_order_images($images['file_name']);
                    $text=ob_get_clean();

                    if ($text) {
                        $this->add_element('printForm.HTML',$text);

                        //отправка на печать обернута в таймаут (при первой отправке на печать не успевал загрузится $text на экран)
                        $this->add_element('JSCODE','<script type="text/javascript">
                                            //$j(".form").addClass("hidden");
                                            $j("#printForm").removeClass("hidden");
                                            let startPrint = function() {
                                            window.print();
                                            resetInput();
                                            };
                                            setTimeout(startPrint, 1000);
                                         </script>') ;
                    } else {
                        $this->add_element('show_notife','Не удалось сформировать файл для печати',['color'=>'red']);
                        $this->add_element('JSCODE','<script type="text/javascript">
                                            resetInput();
                                         </script>') ;
                    }
                } else {
                    foreach ($print_order_errors as $print_order_error) {
                        $this->add_element('show_notife',$print_order_error,['color'=>'red']);
                    }
                    $this->add_element('JSCODE','<script type="text/javascript">
                                            resetInput();
                                         </script>') ;
                }
              } else {
                  if ($GLOBALS['LS_terminal_ticket_license_date']) $license_date = explode(',',$GLOBALS['LS_terminal_ticket_license_date']);
                  else $license_date=[0=>'',1=>''];
                  if (!$_POST['thermal']) {
                      $this->add_element('JSCODE','<script type="text/javascript">
                                            $j("#printForm").html("'.addslashes($text).'") ;
                                            //$j(".form").addClass("hidden");
                                            $j("#printForm").removeClass("hidden");
                                            window.print();
                                            resetInput();
                                         </script>') ;
                  } else {
                      $this->add_element('JSCODE','
                                        <script type="text/javascript">
                                            printArr = {"created_at": '.$rec_mo['dopusk_time'].',
                                                "organisation_name": "'.(($GLOBALS['LS_terminal_ticket_org_name']) ? addslashes($rec_mo['_org_name']) : addslashes($GLOBALS['LS_mo_org_name'])).'",
                                                "lic_info": "'.(($GLOBALS['LS_terminal_ticket_license_number'])? addslashes($GLOBALS['LS_terminal_ticket_license_number'].' '.$GLOBALS['LS_terminal_ticket_license_date']):'').'",
                                                "message": "'.addslashes($thermal_message).'",
                                                "employee_fullname": "'.$rec_mo['member_name'].'",
                                                "user_fullname": "'.$rec_mo['_doctor_name_small'].'",
                                                "cert_thumbprint": "'.addslashes($rec_account['certificate']['sert_id']).'",
                                                "cert_issuer_name": "'.addslashes($rec_account['certificate']['IssuerName']).'",
                                                "medical_organisation_name": "'.(($GLOBALS['LS_terminal_ticket_org_name']) ? addslashes($rec_mo['_org_name']) : addslashes($GLOBALS['LS_mo_org_name'])).'",
                                                "medical_organisation_license_number": "'.$GLOBALS['LS_terminal_ticket_license_number'].'",
                                                "medical_organisation_license_date": "'.$license_date[0].'",
                                                "medical_organisation_license_valid_to":"'.((stripos($license_date[1],'бессрочно')===false)?$license_date[1]:null).'",
                                                "user_position": "'.addslashes($rec_account['working']).'",
                                            }
                                            $j.post(\'http://localhost:9001/api/v1/label\', JSON.stringify(printArr));
                                            resetInput();
                                         </script>') ;
                  }
              }
          }
          else
          { $this->add_element('gettingData.HTML','Допуск отсутствует') ;
            $this->add_element('JSCODE','<script type="text/javascript">resetInput(1500);</script>') ;
          }
      }
      else
      { $this->add_element('gettingData.HTML','Пропуск не найден') ;
        $this->add_element('JSCODE','<script type="text/javascript">resetInput(1500);</script>') ;
      }


    }
}
?>
