<?php
class i_push_mo
{ public $rec_mo  ;
  public $client ;
  public $sender ;
  public $settings ;
  public $format='json' ;
  public $request='' ;
  public $response='' ;
  public $logtext='' ;
  public $recs_doctor=array() ;
  public $recs_group=array() ;

  function __construct()
  {	  $this->sender=array('server'=>$GLOBALS['LS_mo_push_server'],
	                      'basic_login'=>$GLOBALS['LS_mo_push_login'],
	                      'basic_pass'=>$GLOBALS['LS_mo_push_password'],
	                     ) ;
	  $this->settings=$GLOBALS['LS_mo_push_fields'] ;
	  if (!is_array($this->settings))  $this->settings=unserialize($this->settings) ;
	  $this->format='json' ;
  }

  function prepare_request($rec_mo)
  {	if (!isset($this->recs_doctor[$rec_mo['doctor_id']])) $this->recs_doctor[$rec_mo['doctor_id']]=ACCOUNTS()->get_member_by_id($rec_mo['doctor_id']) ;
    if (!isset($this->recs_group[$rec_mo['group_id']])) $this->recs_group[$rec_mo['group_id']]=ACCOUNTS()->get_workgroup_by_id($rec_mo['group_id']) ;

    //damp_array($this->recs_group,1,-1) ;
	$group_timezone=(isset($this->recs_group[$rec_mo['group_id']]['_settings']['timezone']))? $this->recs_group[$rec_mo['group_id']]['_settings']['timezone']:_DEFAULT_TIMEZONE ;
	//$group_timezone=_DEFAULT_TIMEZONE ;
	$rec=array() ;

	if ($this->settings['mo_id'])         $rec['mo_id']=$rec_mo['pkey'] ;
	//$rec['time']=date('d.m.Y H:i:s',time()) ;
	//$rec['time_l']=date('d.m.Y H:i:s',$this->get_local_time(time(),$group_timezone)) ;
	if ($this->settings['time_now'])      $rec['time_now']=ENGINE()->get_local_time(time(),$group_timezone) ;
	if ($this->settings['time_start'])    $rec['time_start']=ENGINE()->get_local_time($rec_mo['c_data'],$group_timezone) ; ;
	if ($this->settings['time_end'])      $rec['time_end']=ENGINE()->get_local_time($rec_mo['e_data'],$group_timezone) ;
	if ($this->settings['terminal_id'])   $rec['terminal_id']=$rec_mo['terminal_id'] ;
	if ($this->settings['group_name'])    $rec['group_name']=$rec_mo['group_name'] ;
	if ($this->settings['personal_name']) $rec['personal_name']=$rec_mo['member_name'] ;
	if ($this->settings['personal_uid'])  $rec['personal_uid']=$rec_mo['member_uid'] ;
    if ($this->settings['personal_tabnumber'])  $rec['personal_tabnumber']=$rec_mo['member_tabnumber'] ;
	if ($this->settings['doctor_uid'])    $rec['doctor_uid'] =$this->recs_doctor[$rec_mo['doctor_id']]['UID'] ;
	if ($this->settings['doctor_name'])   $rec['doctor_name']=$this->recs_doctor[$rec_mo['doctor_id']]['obj_name'] ;
	if ($this->settings['doctor_sert'])   $rec['doctor_sert']=$this->recs_doctor[$rec_mo['doctor_id']]['certificate']['SerialNumber'] ;
    if ($this->settings['doctor_issuer_name'])   $rec['doctor_issuer_name']=$this->recs_doctor[$rec_mo['doctor_id']]['certificate']['IssuerName'] ;
	if ($this->settings['comment'])       $rec['comment']=strip_tags($rec_mo['_comment']) ;
	if ($this->settings['mo_result'])     $rec['mo_result']=$rec_mo['status'] ;
	//if ($this->settings['mo_result_text'])$rec['mo_result_text']=$rec_mo['_status_name'] ;
	if ($this->settings['dopusk'])        $rec['dopusk']=$rec_mo['dopusk'] ;
	if ($this->settings['dopusk_text'])   $rec['dopusk_text']=$rec_mo['_dopusk_name'] ;
	if ($this->settings['dopusk_user_id'])$rec['dopusk_user_id']=$rec_mo['dopusk_user_id'] ;
	if ($this->settings['dopusk_start'])  $rec['dopusk_start']=ENGINE()->get_local_time($rec_mo['dopusk_time'],$group_timezone) ;
	if ($this->settings['dopusk_end'])    $rec['dopusk_end']=ENGINE()->get_local_time($rec_mo['dopusk_time_end'],$group_timezone) ;
	if ($this->settings['reason'])        $rec['reason']=$rec_mo['reason'] ;
	if ($this->settings['equipment'])     $rec['equipment']=$rec_mo['equipment'] ;
    if ($this->settings['type_mo'])     $rec['type_mo']=($rec_mo['tk'])?$rec_mo['tk']:'0';

	if ($this->settings['stamp'] and !$rec_mo['tk'] and $rec_mo['dopusk']==1) $rec['stamp']='data:image/png;base64,'.$rec_mo['_sertificate_stamp_base64'] ;
	if ($this->settings['group_time_zone'])     $rec['group_time_zone']=$group_timezone ;

	if ($this->settings['pass_number'])     $rec['pass_number']=$rec_mo['propusk'] ;
	if ($this->settings['org_name'])     $rec['org_name']=$rec_mo['_org_name'] ;
	if ($this->settings['otdel_name'])     $rec['otdel_name']=$rec_mo['_otdel_name'] ;



	   /* на потом, при необходиомсти
	   if ($rec_mo['tonometer'])   { $rec['s']=$rec_mo['systolic'] ;     $rec['res_s']=$rec_mo['res_s'] ; }
	   if ($rec_mo['tonometer'])   { $rec['d']=$rec_mo['diastolic'] ;    $rec['res_d']=$rec_mo['res_d'] ; }
	   if ($rec_mo['thermometer']) { $rec['t']=$rec_mo['temperature'] ;  $rec['res_t']=$rec_mo['res_t'] ; }
	   if ($rec_mo['pulsometer'])  { $rec['p']=$rec_mo['pulse'] ;        $rec['res_p']=$rec_mo['res_p'] ; }
	   if ($rec_mo['alcotester'])  { $rec['a']=$rec_mo['alko'] ;         $rec['res_a']=$rec_mo['res_a'] ; }
	   if ($rec_mo['pupilometer']) { $rec['n']=$rec_mo['narko'] ;        $rec['res_n']=$rec_mo['res_n'] ; }

	   $rec['question']=($rec_mo['question'])? $rec_mo['question']:0 ;
	   $rec['question_comment']=$rec_mo['question_comment'] ;
	    */

	   //_member_img	http://dev.kvzrm.ru/images/no-avatar-62.png
	   //_member_img_auth	http://dev.kvzrm.ru/public/mo_photo/211880_auth.jpg
	   //_member_img_alco	http://dev.kvzrm.ru/public/mo_photo/211880_alco.jpg
	   //_member_img_DTW	http://dev.kvzrm.ru/public/mo_photo/211880_DTW.png
	   //if ($rec_mo['_member_img'])      $rec['image_personal']=base64_encode(file_get_contents($rec_mo['_member_img'])) ;
	   //if ($rec_mo['_member_img_auth']) $rec['image_auth']=base64_encode(file_get_contents($rec_mo['_member_img_auth'])) ;
	   //if ($rec_mo['_member_img_alco']) $rec['image_alko']=base64_encode(file_get_contents($rec_mo['_member_img_alco'])) ;
	   //if ($rec_mo['_member_img_DTW'])  $rec['image_DTW']=base64_encode(file_get_contents($rec_mo['_member_img_DTW'])) ;

	  /* if ($rec_mo['_member_img'])      $rec['image_personal']=$rec_mo['_member_img'] ;
	   if ($rec_mo['_member_img_auth']) $rec['image_auth']=$rec_mo['_member_img_auth'] ;
	   if ($rec_mo['_member_img_alco']) $rec['image_alko']=$rec_mo['_member_img_alco'] ;
	   if ($rec_mo['_member_img_DTW'])  $rec['image_DTW']=$rec_mo['_member_img_DTW'] ;
	   */
	  return($rec) ;
  }

  function prepare_request_sync($mo_id)
  {	$options=array() ; if (!$GLOBALS['LS_mo_push_format']) $GLOBALS['LS_mo_push_format']=1 ;
    if ($this->settings['stamp']) $options['view_sertificate_stamp']='image_print_MO_sertificate_stamp' ; // включать показ печати по допуску ;
  	$rec_mo=ESMO()->get_mo_by_id($mo_id,$options) ;
    $rec=$this->prepare_request($rec_mo) ;
	$recs[]=$rec ;   $request=array() ;
    if ($GLOBALS['LS_mo_push_format']==1) $request=$this->get_JSON_by_recs($recs) ;
    if ($GLOBALS['LS_mo_push_format']==2) $request=$this->get_XML_by_recs($recs) ;
	return($request) ;
  }

  function prepare_request_async($mo_ids)
  {	$options=array() ; if (!$GLOBALS['LS_mo_push_format']) $GLOBALS['LS_mo_push_format']=1 ;
    if ($this->settings['stamp']) $options['view_sertificate_stamp']='image_print_MO_sertificate_stamp' ; // включать показ печати по допуску ;
  	$recs_mo=ESMO()->get_mo_by_ids_now($mo_ids,$options) ; //print_2x_arr($recs_mo) ;
	if (sizeof($mo_ids)) foreach ($mo_ids as $mo_id) if (!isset($recs_mo[$mo_id])) $recs_mo[$mo_id]=ESMO()->get_mo_by_id($mo_id,$options) ;
	$recs=array() ;  $request=array() ;
    if (_sizeof($recs_mo)) foreach($recs_mo as $rec_mo)
    {   $recs[]=$this->prepare_request($rec_mo) ;
    }
	if ($GLOBALS['LS_mo_push_format']==1) $request=$this->get_JSON_by_recs($recs) ;
    if ($GLOBALS['LS_mo_push_format']==2) $request=$this->get_XML_by_recs($recs) ;
    return($request) ;
  }

  function get_JSON_by_recs($recs)
  {
  	  //настройка LS_mo_push_json_old_format используется только во Внуково (в связке с LS_mo_push_async_size=1)
	  //отправка была настроена в старом формате(без разбиения на Root-Results: только один элемент), после обновления шлюз перестал работать
	  if (!$GLOBALS['LS_mo_push_json_old_format']) $arr['Root']['Results']=$recs ;
	  else $arr=$recs[0];
	  return json_encode($arr,JSON_UNESCAPED_UNICODE) ;
  }

  function get_XML_by_recs($recs)
  {
	  //header("Content-type: text/xml;charset=UTF-8") ;
	  $imp = new DOMImplementation; // Creates an instance of the DOMImplementation class
	  $xml_doc = $imp->createDocument("",""); // Creates a DOMDocument instance
	  $xml_doc->encoding = 'utf-8';
	  $xml_doc->formatOutput = true;
	  $xml = add_element($xml_doc,$xml_doc,'xml_doc','',array('date'=>date('Y-m-d H:i'))) ;

	  $root=add_element($xml_doc,$xml,'Root','') ;
	  $item=add_element($xml_doc,$root,'Results','') ;
	  if (_sizeof($recs)) foreach($recs as $rec)
	  { $node=add_element($xml_doc,$item,'Result','') ;
	  	if (_sizeof($rec)) foreach($rec as $id=>$value) add_element($xml_doc,$node,$id,$value) ;
	  }
	  return($xml_doc->saveXML()) ;
  }


  function send($request,$options=array())
  {   $result=array('request'=>$request) ;
	  $arr_url=parse_url($this->sender['server']) ; //damp_array($arr_url,1,-1) ;

      if ($arr_url['host'])
       { if ($this->sender['basic_login']) $options['basic_login']=$this->sender['basic_login'] ;
         if ($this->sender['basic_pass']) $options['basic_pass']=$this->sender['basic_pass'] ;
         $options['connect_timeout']=$options['timeout'] ;
         $options['log_request']=$GLOBALS['LS_mo_push_log_req'] ;
         if ($GLOBALS['LS_mo_push_format']==1)  $options['content_type']='json' ;
         if ($GLOBALS['LS_mo_push_format']==2)  $options['content_type']='xml' ;
         if ($arr_url['port']) $arr_url['host'].=':'.$arr_url['port'] ;
         $result=IO()->doPut_v2($arr_url['scheme'].'://',$arr_url['host'],$arr_url['path'],'',$request,$options) ;
         $result['send_result']=($result['status']==200)? 'success':'error' ;
	     $result['request']=$request ;
       }
       return($result) ;
  }

  function send_sync($mo_id)
  {	$request=$this->prepare_request_sync($mo_id) ;
	$result=$this->send($request,array('timeout'=>$GLOBALS['LS_mo_push_timeout_sync'])) ;
	$event_send=($result['status']==200)? time():0 ;
	update_rec_in_table('obj_site_mo_session',array('event_send'=>$event_send),'pkey='.$mo_id) ;
	update_rec_in_table('obj_site_mo_session_now',array('event_send'=>$event_send),'pkey='.$mo_id) ;
	$log_comment=$_SESSION['ARR_mo_push_format'][$GLOBALS['LS_mo_push_format']].' ' ;
	$log_comment.=($result['status']==200)? 'success':'<span class="red">ERROR: '.$result['send_error'].' ['.$result['status'].']</span>' ;
	if ($GLOBALS['LS_mo_push_log_req'] ) $log_comment.='<br><a href="'.$result['log_url'].'" target="_blank">report</a>' ;
	LOGS()->reg_log('push_mo_sync',$log_comment,array('time_exec'=>$result['time_exec'],'data'=>array('mo_id'=>$mo_id))) ;
	return($result) ;
  }

  function send_async($mo_ids)
  { $request=$this->prepare_request_async($mo_ids) ;
	$result=$this->send($request,array('timeout'=>$GLOBALS['LS_mo_push_timeout_async'])) ;
	$event_send=($result['status']==200)? time():0 ;
	update_rec_in_table('obj_site_mo_session_now',array('event_send'=>$event_send),'pkey in ('.implode(',',$mo_ids).')') ;
	update_rec_in_table('obj_site_mo_session',array('event_send'=>$event_send),'pkey in ('.implode(',',$mo_ids).')') ;
	$log_comment=($result['status']==200)? 'success':'<span class="red">ERROR: '.$result['send_error'].' ['.$result['status'].']</span>' ;
	$log_comment.='<br><a href="'.$result['log_url'].'" target="_blank">report</a>' ;
	LOGS()->reg_log('push_mo_async',$log_comment,array('time_exec'=>$result['time_exec'],'data'=>array('mo_ids'=>implode(',',$mo_ids)))) ;
    return($result) ;
  }

  function get_mo_ids_to_async_send($time_start=0)
  {	$limit=($GLOBALS['LS_mo_push_async_size'])? $GLOBALS['LS_mo_push_async_size']:'100' ;
    //$mo_ids_old=execSQL_line('select pkey from obj_site_mo_session where c_data>'.$time_start.' and event_send=0 and dopusk in (1,2) order by pkey limit '.$limit) ;
$mo_ids_old=[] ;
    $mo_ids_now=execSQL_line('select pkey from obj_site_mo_session_now where c_data>'.$time_start.' and event_send=0 and dopusk in (1,2) order by pkey limit '.$limit) ;
	//  $mo_ids_now  имееют более больший приоритет, их надо отправить первыми
	$mo_ids=array_merge($mo_ids_now,$mo_ids_old) ;
	$mo_ids=array_slice($mo_ids,0,$limit);
	return($mo_ids) ;
  }


}



?>
