<?php
class i_push_kt
{ public $rec_kt  ;
  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_kt_push_server'],
	                      'basic_login'=>$GLOBALS['LS_kt_push_login'],
	                      'basic_pass'=>$GLOBALS['LS_kt_push_password'],
	                     ) ;
	  $this->settings=$GLOBALS['LS_kt_push_fields'] ;
	  if (!is_array($this->settings))  $this->settings=unserialize($this->settings) ;
	  $this->format='json' ;
  }

  function prepare_request($rec_kt)
  {
	$group_timezone=_DEFAULT_TIMEZONE ;

	$rec=array() ;

	if ($this->settings['kt_id'])         $rec['kt_id']=$rec_kt['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_kt['c_data'],$group_timezone) ; ;
	if ($this->settings['time_end'])      $rec['time_end']=ENGINE()->get_local_time($rec_kt['e_data'],$group_timezone) ;
	if ($this->settings['zone_name'])    $rec['zone_name']=$rec_kt['zone_name'] ;
	if ($this->settings['personal_name']) $rec['personal_name']=$rec_kt['member_name'] ;
	if ($this->settings['personal_uid'])  $rec['personal_uid']=$rec_kt['member_uid'] ;
    if ($this->settings['personal_tabnumber'])  $rec['personal_tabnumber']=$rec_kt['member_tabnumber'] ;
	if ($this->settings['dopusk'])        {
	    $rec['dopusk']=$rec_kt['dopusk'] ;
	    //Доработка для СКД
	    if ($GLOBALS['LS_kt_push_zero_dopusk'] and $rec['dopusk']==2) $rec['dopusk']=0;
    }
	if ($this->settings['dopusk_start'])  $rec['dopusk_start']=ENGINE()->get_local_time($rec_kt['dopusk_time'],$group_timezone) ;
	if ($this->settings['dopusk_end'])    $rec['dopusk_end']=ENGINE()->get_local_time($rec_kt['dopusk_time_end'],$group_timezone) ;
    if ($this->settings['alko_value'])        $rec['alko_value']=$rec_kt['alko_value'] ;

	  return($rec) ;
  }

  function prepare_request_sync($kt_id)
  {	$options=array() ; if (!$GLOBALS['LS_kt_push_format']) $GLOBALS['LS_kt_push_format']=1 ;
    if ($this->settings['stamp']) $options['view_sertificate_stamp']='image_print_MO_sertificate_stamp' ; // включать показ печати по допуску ;
  	$rec_kt=KT()->get_mo_by_id($kt_id,$options) ;
    $rec=$this->prepare_request($rec_kt) ;
	$recs[]=$rec ;   $request=array() ;
    if ($GLOBALS['LS_kt_push_format']==1) { $arr['Root']['Results']=$recs ; $request=json_encode($arr) ; }
    if ($GLOBALS['LS_kt_push_format']==2) $request=$this->get_XML_by_recs($recs) ;
	return($request) ;
  }

  function prepare_request_async($kt_ids)
  {	$options=array() ; if (!$GLOBALS['LS_kt_push_format']) $GLOBALS['LS_kt_push_format']=1 ;
    if ($this->settings['stamp']) $options['view_sertificate_stamp']='image_print_MO_sertificate_stamp' ; // включать показ печати по допуску ;
  	$recs_kt=KT()->get_mo_by_ids($kt_ids,$options) ; //print_2x_arr($recs_kt) ;
	$recs=array() ;  $request=array() ;
    if (_sizeof($recs_kt)) foreach($recs_kt as $rec_kt)
    {   $recs[]=$this->prepare_request($rec_kt) ;
    }
	if ($GLOBALS['LS_kt_push_format']==1) { $arr['Root']['Results']=$recs ;  $request=json_encode($arr) ; }
    if ($GLOBALS['LS_kt_push_format']==2) $request=$this->get_XML_by_recs($recs) ;
    return($request) ;
  }


  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_kt_push_log_req'] ;
         if ($GLOBALS['LS_kt_push_format']==1)  $options['content_type']='xls' ;
         if ($GLOBALS['LS_kt_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($kt_id)
  {	$request=$this->prepare_request_sync($kt_id) ;
	$result=$this->send($request,array('timeout'=>$GLOBALS['LS_kt_push_timeout_sync'])) ;
	$event_send=($result['status']==200)? time():0 ;
	update_rec_in_table('obj_site_kt_session',array('event_send'=>$event_send),'pkey='.$kt_id) ;
	$log_comment=$_SESSION['ARR_kt_push_format'][$GLOBALS['LS_kt_push_format']].' ' ;
	$log_comment.=($result['status']==200)? 'success':'<span class="red">ERROR: '.$result['send_error'].' ['.$result['status'].']</span>' ;
	if ($GLOBALS['LS_kt_push_log_req'] ) $log_comment.='<br><a href="'.$result['log_url'].'" target="_blank">report</a>' ;
	LOGS()->reg_log('push_kt_sync',$log_comment,array('time_exec'=>$result['time_exec'],'data'=>array('kt_id'=>$kt_id))) ;
	return($result) ;
  }

  function send_async($kt_ids)
  { $request=$this->prepare_request_async($kt_ids) ;
	$result=$this->send($request,array('timeout'=>$GLOBALS['LS_kt_push_timeout_async'])) ;
	$event_send=($result['status']==200)? time():0 ;
	update_rec_in_table('obj_site_kt_session',array('event_send'=>$event_send),'pkey in ('.implode(',',$kt_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_kt_async',$log_comment,array('time_exec'=>$result['time_exec'],'data'=>array('kt_ids'=>implode(',',$kt_ids)))) ;
    return($result) ;
  }

  function get_kt_ids_to_async_send()
  {	$limit=($GLOBALS['LS_kt_push_async_size'])? 'limit '.$GLOBALS['LS_kt_push_async_size']:'' ;
  	$kt_ids=execSQL_line('select pkey from obj_site_kt_session where c_data>'.$GLOBALS['LS_kt_push_async'].' and event_send=0 and dopusk in (1,2) '.$limit,2) ;
	return($kt_ids) ;
  }


}



?>
