<?php

namespace app\api\controller;

use AdaPay\AdaTools;
use app\models\article\ArticleContent;
use app\models\store\StoreOrder;
use app\models\user\UserRecharge;
use app\Request;
use crmeb\services\UtilService;
include_once  dirname(__FILE__). "/AdapayCore/utils/AdaTools.php";
/**
 *
 * Class DouYiCantroller
 * @package app\api\controller
 */
class AdaPayController
{
    public $rsaPublicKeyFilePath = "";
    public $rsaPublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwN6xgd6Ad8v2hIIsQVnbt8a3JituR8o4Tc3B5WlcFR55bz4OMqrG/356Ur3cPbc2Fe8ArNd/0gZbC9q56Eb16JTkVNA/fye4SXznWxdyBPR7+guuJZHc/VW2fKH2lfZ2P3Tt0QkKZZoawYOGSMdIvO+WqK44updyax0ikK6JlNQIDAQAB";

    public function notify(Request $request)
    {
        $post = $request->post();
        $data = json_decode($post['data']);
        $sing = $post['sign'];
        $res = $this->verifySign($sing, $post['data']);
        if($res){
            if ($data->status == 'succeeded'){
                $order = strstr($data->order_no, '-', -1);
                $res = StoreOrder::paySuccess($order, $data->pay_channel);
                if ($res){
                    echo '200';
                    exit();
                }
            }
            echo 'error';
            exit();
        }else {
            echo 'error';
            exit();
        }
    }

    public function cz_notify(Request $request)
    {
        $post = $request->post();
        $data = json_decode($post['data']);
        $sing = $post['sign'];
        $res = $this->verifySign($sing, $post['data']);
        if($res){
            if ($data->status == 'succeeded'){
                $order = strstr($data->order_no, '-', -1);
                $res = UserRecharge::rechargeSuccess($order);
                if ($res){
                    echo '200';
                    exit();
                }
            }
            echo 'error';
            exit();
        }else {
            echo 'error';
            exit();
        }
    }


    public function checkEmpty($value) {
        if (!isset($value))
            return true;
        if ($value === null)
            return true;
        if (trim($value) === "")
            return true;
        return false;
    }


    public function verifySign($signature, $data){
        if($this->checkEmpty($this->rsaPublicKeyFilePath)){
            $pubKey=$this->rsaPublicKey;
            $key = "-----BEGIN PUBLIC KEY-----\n".wordwrap($pubKey, 64, "\n", true)."\n-----END PUBLIC KEY-----";
        }else {
            $pubKey = file_get_contents($this->rsaPublicKeyFilePath);
            $key = openssl_get_publickey($pubKey);
        }
        if (openssl_verify($data, base64_decode($signature), $key)){
            return true;
        }else{
            return false;
        }
    }

}