<?php
namespace Models;

class yapay_qr {
	public $f3, $sets, $config, $web;
	
	function __construct($f3, $sets, $config) {
		$this->f3=$f3;
		$config['Api-Key']='QGV0DxZ9n7PwyINPiAvd';
		$this->sets=$sets;
        $this->config=$config;
        $this->web=\Web::instance();
	}

	static function accounts($data) {
		if(!$data['User-Token']) {
        	return array(
        		'success'=>false,
        		'txt'=>'Укажите данные для авторизации'
        	);
        }

		$url='https://api.qr.yandex.net/api/v1/s1/accounts';
		$options = array(
			'method'=>'GET',
    		'follow_location'=>1,
    		'header'=>array(
    			'Api-Key: QGV0DxZ9n7PwyINPiAvd',
    			'User-Token: '.$data['User-Token'],
    			'Content-Type: application/json'
    		),
		);
		$web=\Web::instance();
		$request=$web->request($url, $options);

		$json=json_decode($request['body'], true);

		if(mb_strpos($request['headers'][0], '200')>0) {
			if(isset($json['code']) && $json['code']==0) {
            	return array(
            		'success'=>false,
            		'txt'=>$json['error']
            	);
            }
            if(isset($json['message'])) {
            	return array(
            		'success'=>false,
            		'txt'=>$json['message']
            	);
            }
            $options=array();
            foreach ($json as $value) {
            	if($value['active']==1) $options[]=array($value['name'], $value['key']);
            }
            return array(
            	'success'=>true,
            	'options'=>$options
            );
        }

        if(is_array($json) && isset($json['message'])) {
        	return array(
	        	'success'=>false,
	        	'txt'=>$json['message']
	        );
        }

        return array(
        	'success'=>false,
        	'txt'=>$request['body']
        );
	}

	function cancel_qr($data) {
		$vars=array(
			"key"=>$this->config['key'],
		);
		$options = array(
			'method'=>'POST',
    		'follow_location'=>1,
    		'header'=>array(
    			'Api-Key: '.$this->config['Api-Key'],
    			'User-Token: '.$this->config['User-Token'],
    			'Content-Type: application/json'
    		),
    		'content'=>json_encode($vars)
		);

		$request=$this->web->request('https://api.qr.yandex.net/api/v1/s1/operation/cancel', $options);
		if(mb_strpos($request['headers'][0], '200')>0) {
            $json=json_decode($request['body'], true);
            if($json['code']==0) {
            	return array(
            		'success'=>false,
            		'txt'=>$json['error']
            	);
            }
			return array(
				'success'=>true
			);
        }
        return array(
        	'success'=>false,
        	'txt'=>$request['body']
        );
	}

	function create_cancel_qr($sum, $return_epay) {
		$receipt_id=$this->f3->get('COOKIE.receipt_id');

		$vars=array(
			"sale_token"=>$return_epay['sbp_order_id'],
  			"cost"=>(float)$sum,
		);
		$options = array(
			'method'=>'POST',
    		'follow_location'=>1,
    		'header'=>array(
    			'Api-Key: '.$this->config['Api-Key'],
    			'User-Token: '.$this->config['User-Token'],
    			'Content-Type: application/json'
    		),
    		'content'=>json_encode($vars)
		);

		$request=$this->web->request('https://api.qr.yandex.net/api/v1/s1/operation/return', $options);
		//var_dump($return_epay); exit();

		if(mb_strpos($request['headers'][0], '200')>0) {
            $json=json_decode($request['body'], true);
            if($json['code']==0) {
            	return array(
            		'success'=>false,
            		'txt'=>$json['error']
            	);
            }
            $slip="Статус: Успешно\n";
			$slip.="Идентификатор операции\n";
			$slip.=' - в Банке: '.$return_epay['sbp_order_id']."\n";
			return array(
				'success'=>true,
				'txt'=>nl2br($slip),
				'slip'=>nl2br($slip),
				'pan'=>'',
				'transid'=>$return_epay['transid'],
				'authcode'=>'',
			);
        }
        return array(
        	'success'=>false,
        	'txt'=>$request['body']
        );
	}

	function create_sale_qr($sum) {
		$receipt_id=$this->f3->get('COOKIE.receipt_id');

		$vars=array(
  			"cost"=>(float)$sum,
  			"key"=>$this->config['key'],
  			"client_transaction"=>date('Y-m-d-H-i-s').'-'.$receipt_id,
  			"duration"=>180,
  			"comment"=>"Оплата по чеку ".$receipt_id
		);
		$options = array(
			'method'=>'POST',
    		'follow_location'=>1,
    		'header'=>array(
    			'Api-Key: '.$this->config['Api-Key'],
    			'User-Token: '.$this->config['User-Token'],
    			'Content-Type: application/json'
    		),
    		'content'=>json_encode($vars)
		);

		$request=$this->web->request('https://api.qr.yandex.net/api/v1/s1/operation/create', $options);

		if(mb_strpos($request['headers'][0], '200')>0) {
            $json=json_decode($request['body'], true);
            if($json['code']==0) {
            	return array(
            		'success'=>false,
            		'txt'=>$json['error']
            	);
            }
            return array(
				'success'=>true,
				'qr'=>$json['qrKey'],
				'sbp_order_id'=>$json['sale_token'],
				'receipt_id'=>$receipt_id,
				'show_qr'=>'/receipts/show_qr?receipt_id='.$receipt_id.'&sbp_order_id='.$json['sale_token'].'&epay='.$this->sets['id'].'&sum='.($sum*100).'&url='.urlencode($json['qrKey'])
			);
        }
        return array(
        	'success'=>false,
        	'txt'=>$request['body']
        );
	}

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

	}

	function paycontrol_qr($data) {
		$url='https://api.qr.yandex.net/api/v1/s1/operation/result?sale_token='.$data['sbp_order_id'];
		$options = array(
			'method'=>'GET',
    		'follow_location'=>1,
    		'header'=>array(
    			'Api-Key: '.$this->config['Api-Key'],
    			'User-Token: '.$this->config['User-Token'],
    			'Content-Type: application/json'
    		),
		);

		$request=$this->web->request($url, $options);

		$json=json_decode($request['body'], true);

		if(mb_strpos($request['headers'][0], '200')>0) {
            if($json['code']==0) {
            	return array(
            		'success'=>false,
            		'txt'=>$json['error']
            	);
            }
            if($json['status']==1 && $json['result']==true) {
            	$slip="Статус: Успешно\n";
				$slip.="Идентификатор операции\n";
				$slip.=' - в Банке: '.$data['sbp_order_id']."\n";
				return array(
					'success'=>true,
					'txt'=>nl2br($slip),
					'slip'=>nl2br($slip),
					'pan'=>'',
					'transid'=>$data['sbp_order_id'],
					'authcode'=>'',
				);
            }
            if($json['status']==1 && $json['result']==false) {
            	return array(
					'success'=>false,
					'txt'=>'Статус платежа: Неуспешно',
					'show_error'=>true
				);
            }
            return array(
				'success'=>false,
				'txt'=>'Статус платежа: Неизвестно',
			);
        }

        if(is_array($json) && isset($json['message'])) {
        	return array(
	        	'success'=>false,
	        	'txt'=>$json['message']
	        );
        }

        return array(
        	'success'=>false,
        	'txt'=>$request['body']
        );
	}

	function report($change) {
		$vars=array(
  			"key"=>$this->config['key'],
  			"data_begin"=>gmdate('Y-m-d H:i:s', $change['time_start']),
  			"data_end"=>gmdate('Y-m-d H:i:s', $change['time_end']>0?$change['time_end']:time()),
		);
		$options = array(
			'method'=>'GET',
    		'follow_location'=>1,
    		'header'=>array(
    			'Api-Key: '.$this->config['Api-Key'],
    			'User-Token: '.$this->config['User-Token'],
    			'Content-Type: application/json'
    		),
		);

		$request=$this->web->request('https://api.qr.yandex.net/api/v1/s1/report/finance?'.http_build_query($vars), $options);
		if(mb_strpos($request['headers'][0], '200')>0) {
            $json=json_decode($request['body'], true);
            if($json['code']==0) {
            	return array(
            		'success'=>false,
            		'txt'=>$json['error']
            	);
            }
            return array(
				'success'=>true,
				'operations'=>$json['data']['operations']??array()
			);
        }
        return array(
        	'success'=>false,
        	'txt'=>$request['body']
        );
	}

	function report2txt($operations) {
		$sales=0;
		$sales_sum=0;
		$returns=0;
		$returns_sum=0;
		foreach($operations as $operation) {
			if($operation['source']=='payment') {
				$sales+=1;
				$sales_sum+=$operation['total_cost'];
			}
			if($operation['source']=='refund') {
				$returns+=1;
				$returns_sum+=abs($operation['total_cost']);
			}
		}
		$cheq='Отчет по Я.Пэй<br>';
		$cheq.='Продаж - '.$sales.'<br>';
		$cheq.='  На сумму - '.number_format($sales_sum, 2, '.', '').'<br>';
		$cheq.='<br>';
		$cheq.='Возвратов - '.$returns.'<br>';
		$cheq.='  На сумму - '.number_format($returns_sum, 2, '.', '').'<br>';
		return $cheq.='<br>';
	}

	function z($change) {
		$cheq=$this->sets['title']."<br>Смена успешно закрыта<br>";
		$res=$this->report($change);

		if(!$res['success']) {
			return $res;
		}

		$cheq.=$this->report2txt($res['operations']);
		return array(
			'success'=>true,
			'txt'=>nl2br($cheq),
			'slip'=>nl2br($cheq),
			'pan'=>0,
			'transid'=>0,
			'authcode'=>0
		);
	}

	function x($change) {
		$res=$this->report($change);

		if(!$res['success']) {
			return $res;
		}

		$cheq=$this->report2txt($res['operations']);

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