<?php
namespace Models;

class russtandart_sbp {
	public $f3, $sets, $config;
	
	function __construct($f3, $sets, $config) {
		$this->f3=$f3;
		$this->sets=$sets;
        $this->config=$config;
	}

	function send_curl($url, $vars) {
		$headers=array(
			'Content-Type: application/json;charset=UTF-8',
			'x-User-login: '.$this->config['x-User-login']
		);
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL,$url);
		curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($curl, CURLOPT_POST,true);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $vars);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($curl, CURLOPT_CAINFO, __DIR__.'/cacerts.pem');
		curl_setopt($curl, CURLOPT_SSLCERT, __DIR__.'/client_cert.pem');
		curl_setopt($curl, CURLOPT_SSLKEY, __DIR__.'/private.pem');
		$data = curl_exec($curl);
		$error=curl_error($curl);
		curl_close($curl);
		if(!$data) {
			return array(
				'success'=>false,
				'txt'=>$error
			);
		}
		$json=json_decode($data, true);
		if($json['code']==0) {
			return array(
				'success'=>true,
				'data'=>$json
			);
		}
		if(is_array($json)) {
			return array(
				'success'=>false,
				'txt'=>$json['message'],
				'data'=>$json
			);
		}
		return array(
			'success'=>false,
			'txt'=>$data
		);
	}

	function create_cancel_qr($sum, $return_epay) {
		$sourceId=$this->config['merchantId'].'-'.time();
		$title=$return_epay['id'];

		$vars=array(
			'sourceId'=>(string)$sourceId,
			'originalId'=>(string)$return_epay['transid'],
			'amount'=>$sum,
			'currency'=>'RUB',
			'refundPurpose'=>$title,
			'terminalId'=>$this->config['merchantId'],
			'merchantId'=>$this->config['merchantId'],
		);
		openssl_sign(json_encode($vars), $sign, file_get_contents(__DIR__.'/selfSignedKey.pem'), OPENSSL_ALGO_SHA256);
		$sign=base64_encode($sign);
		$vars['msgSign']=$sign;
		$url=$this->config['RusStandart_path'].'/eis-app/eis-rs/businessPaymentService/qrRefund';
		$res=$this->send_curl($url, json_encode($vars));
		if(!$res['success']) {
			return $res;
		}
		$refundId=$res['data']['refundId'];
		if(!$res['data']['paymentData']) {
			$ok=false;
			$n=60;
			while(!$ok && $n>0) {
				sleep(1);
				$vars=array(
					'sourceId'=>$sourceId,
					'originalId'=>$return_epay['transid'],
					'refundId'=>$refundId
				);
				$url=$this->config['RusStandart_path'].'/eis-app/eis-rs/businessPaymentService/getRefundStatus';
				$res=$this->send_curl($url, json_encode($vars));
				if(!$res['success']) {
					return $res;
				}
				if($res['data']['paymentData']) {
					$ok=true;
				}
				$n-=1;
			}
		}
		if(!$res['data']['paymentData']) {
			return array(
				'success'=>false,
				'txt'=>'Ошибка при возврате платежа'
			);
		}
		$slip="Статус: Успешно\n";
		$slip.="Идентификатор операции\n";
		$slip.=' - в Банке: '.$sourceId."\n";
		$slip.=' - в СБП: '.$refundId."\n";
		return array(
			'success'=>true,
			'txt'=>nl2br($slip),
			'slip'=>nl2br($slip),
			'pan'=>'',
			'transid'=>$sourceId,
			'authcode'=>'',
		);
	}

	function create_sale_qr($sum) {
		$receipt_id=$this->f3->get('COOKIE.receipt_id');
		$sourceId=$this->config['merchantId'].'-'.time();
		$title='Оплата по чеку '.$receipt_id;
		$vars=array(
			'sourceId'=>(string)$sourceId,
			'terminalId'=>$this->config['merchantId'],
			'merchantId'=>$this->config['merchantId'],
			'account'=>$this->config['account'],
			'templateVersion'=>'01',
			'qrcType'=>'02',
			'qrcExpire'=>5,
			'amount'=>$sum,
			'currency'=>'RUB',
			'paymentPurpose'=>$title
		);
		$url=$this->config['RusStandart_path'].'/eis-app/eis-rs/businessPaymentService/getQrCode';
		$res=$this->send_curl($url, json_encode($vars));
		if(!$res['success']) {
			return $res;
		}
		$url=$res['data']['data']['payload'];
		
		return array(
			'success'=>true,
			'qr'=>$url,
			'qr_id'=>$res['data']['data']['qrcId'],
			'sbp_order_id'=>$res['data']['operationId'],
			'receipt_id'=>$receipt_id,
			'show_qr'=>'/receipts/show_qr?receipt_id='.$receipt_id.'&order_id='.$sourceId.'&sbp_order_id='.$res['data']['operationId'].'&qr_id='.$res['data']['data']['qrcId'].'&epay='.$this->sets['id'].'&sum='.$sum.'&url='.urlencode($url)
		);
	}

	function ticket($type, $sum, $return_epay=null) {
		if($type=='sale') {
			return $this->create_sale_qr($sum*100);
		}
		return $this->create_cancel_qr($sum*100, $return_epay);
	}

	function paycontrol_qr($data) {
		$vars=array(
			'sourceId'=>(string)$data['order_id'],
			'operationId'=>$data['sbp_order_id'],
			'qrcId'=>$data['qr_id']
		);
		$url=$this->config['RusStandart_path'].'/eis-app/eis-rs/businessPaymentService/getQrdStatus';
		$res=$this->send_curl($url, json_encode($vars));
		if(!$res['success']) {
			return $res;
		}

		if($res['data']['data']['status']=='ACCEPTED') {
			$slip="Статус: Успешно\n";
			$slip.="Идентификатор операции\n";
			$slip.=' - в Банке: '.$data['sbp_order_id']."\n";
			$slip.=' - в СБП: '.$data['qr_id']."\n";
			return array(
				'success'=>true,
				'txt'=>nl2br($slip),
				'slip'=>nl2br($slip),
				'pan'=>'',
				'transid'=>$data['order_id'],
				'authcode'=>'',
			);
		}
		else {
			if($res['data']['data']['status']=='DECLINED') {
				return array(
					'success'=>false,
					'txt'=>'Статус платежа: '.$res['data']['data']['status'],
					'show_error'=>true
				);
			}
			return array(
				'success'=>false,
				'txt'=>'Статус платежа: '.$res['data']['data']['status']
			);
		}

		return array(
			'success'=>false,
			'txt'=>'Неудается отправить запрос'
		);
	}

	function z($change) {
		$cheq=$this->sets['title']."\nСмена успешно закрыта";
		return array(
			'success'=>true,
			'txt'=>nl2br($cheq),
			'slip'=>nl2br($cheq),
			'pan'=>0,
			'transid'=>0,
			'authcode'=>0
		);
	}

	function x($change) {
		$cheq='';
		return array(
			'success'=>true,
			'txt'=>nl2br($cheq),
			'slip'=>nl2br($cheq),
			'pan'=>0,
			'transid'=>0,
			'authcode'=>0
		);
	}
}
