<?php
namespace frontend\controllers;

use AmazonPay\Client;
use Braintree\Configuration;
use Braintree\Transaction as BraintreeTransaction;
use common\models\MailSend;
use common\models\PaymentDetails;
use Exception;
use Yii;
use yii\web\Controller;
use frontend\models\PaymentForm;
use yii\helpers\Url;
use yii\httpclient\XmlParser;

/**
 * Site controller
 */
class SiteController extends Controller
{
    
    /**
     * {@inheritdoc}
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
        
    }


    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionIndex()
    {
        $model  =   new PaymentForm();
        if(Yii::$app->request->isAjax){

            $params     =   Yii::$app->request->get();
            
            Configuration::merchantId('8frhtc6vnktkjyww');
            Configuration::publicKey('bqnbr34yt49ngd7p');
            Configuration::privateKey('494723c9647e278895ccd2f87c27f6f7');
            Configuration::environment('sandbox');

            $result     =   BraintreeTransaction::sale([
                'amount' => $params['price'],
                'paymentMethodNonce' => $params['result'],
                'options' => [
                    'submitForSettlement' => True
                ],
            ]);
            $response   =   [];

            if($result->success == 1){
                 
                $params['transactionid']    =   $result->transaction->id;
                $params['price']            =   $result->transaction->amount;

                $transt    =   new PaymentDetails();

                $transt->transaction_id  =   $result->transaction->id;
                $transt->name            =   $params['name'];
                $transt->email           =   $params['email'];
                $transt->mobile          =   $params['number'];
                $transt->amount          =   $result->transaction->amount;
                $transt->paytype         =   $params['ptype'];

                if($transt->save()){

                    // $data['subject'] = 'Payment Information';
                    // $data['cc'] = $params['email'];
                    // $table= '<table>';

                    // $table .= '<tr><td>Transaction ID : </td><td>'.$params['transactionid'].'</td></tr>';
                    // $table .= '<tr><td>Payment By : </td><td>'.$params['ptype'].'</td></tr>';
                    // $table .= '<tr><td>Name : </td><td>'.$params['name'].'</td></tr>';
                    // $table .= '<tr><td>Email : </td><td>'.$params['email'].'</td></tr>';
                    // $table .= '<tr><td>Mobile Number : </td><td>'.$params['mobile'].'</td></tr>';
                    // $table .= '<tr><td>Paid amount : </td><td>'.$params['price'].'</td></tr>';
                    // $table .= '</table>';

                    // $data['content'] = $table;
                    // MailSend::mail_to_user($data);
                    // MailSend::mail_to_owner($data);
                    
                  //  MailSend::test_mail('chandan@mailinator.com');
                }
                $data       =   json_encode($params);
                $paydata    =   base64_encode($data);

                $response['status']     =   'success';
                $response['msg']        =   'Your payment has been successfully done.';
                $response['url']        =   Url::to(['/success', 'success' => $paydata]);
            }else{
                $response['status']     =   'error';
                $response['msg']        =   'Your payment not be done. Kindly try again.';
            }
            return json_encode($response);
        }else if($model->load(Yii::$app->request->post())){
            $params     =   Yii::$app->request->post('PaymentForm');
            $amsjson    =   json_encode($params);
            $datacode   =   base64_encode($amsjson);
            return $this->render('payment', [ 'params' => $params, 'datacode' =>$datacode ]);
        }
        return $this->render('index', ['model' => $model]);
    }
   
    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionPayment()
    {
        $data['subject'] = 'Payment Information';
        $data['cc'] = 'chandan@mailinator.com';
      
        $data['transactionid']  =  '4dsdfs';
        $data['ptype']          =  'Credit Card Pay';
        $data['name']           =  'Chandan ';
        $data['email']          =  'chandan@mailinator.com';
        $data['mobile']         =  '9414581228';
        $data['price']          =  '25';

        MailSend::mail_to_user($data);
        MailSend::mail_to_owner($data);
        //MailSend::test_mail('chandan@mailinator.com');
    }

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionSuccess()
    {
        if((@$_GET['success']) != ''){
            
            $data   =   base64_decode($_GET['success']);
            $params =   json_decode($data, true);

            return $this->render('success', ['params' => $params]);
        }else{
            return $this->redirect(['/']);
        }
    }


    public function actionAmazonPay($data= '')
	{
        if($data != ''){
            $amsjson    =   base64_decode($data);
            $params     =   json_decode($amsjson, true);
           
            return $this->render('amazon-pay', ['params' => $params, 'data' => $data]);
        }
	}
    
    public function actionAmazonDetails(){

        $config = array(
            'merchant_id'   => 'A2S8OZDSS5LEKH',
            'access_key'    => 'AKIAJVPDDR7KC75M52RQ',
            'secret_key'    => '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',
            'client_id'     => "amzn1.application-oa2-client.febe59d671b1444c9a083382386b2c1c",
            'region'        => 'us',  // us, de, uk, jp
            'currency_code' => 'USD', // USD, EUR, GBP, JPY
            'sandbox'       => true
        );

        $amount         =   Yii::$app->request->post('amount');
        $refereceid     =   Yii::$app->request->post('orderReferenceId');
        $accessToken    =   Yii::$app->request->post('accessToken');

        $client = new Client($config);

        $requestParameters = array();

        // Create the parameters array to set the order
        $requestParameters['amount']            = $amount;
        $requestParameters['currency_code']     = $config['currency_code'];
        $requestParameters['seller_note']       = 'Tower Nephro Payment';
        // $requestParameters['seller_order_id']   = '123456-TestOrder-123456';
        // $requestParameters['store_name']        = 'SDK Sample Store Name';
        // $requestParameters['custom_information']= 'Any custom information';
        $requestParameters['mws_auth_token']    = null; // only non-null if calling API on behalf of someone else
        $requestParameters['amazon_order_reference_id'] = $refereceid;

        // Set the Order details by making the SetOrderReferenceDetails API call
        $response = $client->setOrderReferenceDetails($requestParameters);

        // If the API call was a success Get the Order Details by making the GetOrderReferenceDetails API call
        if ($client->success)
        {
            $requestParameters['access_token'] = $accessToken;
            $response = $client->getOrderReferenceDetails($requestParameters);
        }
        // Pretty print the Json and then echo it for the Ajax success to take in
        $json = json_decode($response->toJson());

        return json_encode($json, JSON_PRETTY_PRINT);
    }
    
    public function actionAmazonAuthorize()
	{
        if(Yii::$app->request->isAjax){
            
            $config = array(
                'merchant_id'   => 'A2S8OZDSS5LEKH',
                'access_key'    => 'AKIAJVPDDR7KC75M52RQ',
                'secret_key'    => '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',
                'client_id'     => "amzn1.application-oa2-client.febe59d671b1444c9a083382386b2c1c",
                'region'        => 'us',  // us, de, uk, jp
                'currency_code' => 'USD', // USD, EUR, GBP, JPY
                'sandbox'       => true
            );

            $requestParameters  =   $params =   $postArr    =   $payresponse    =   $paysucces  =   [];

            $postArr    =   Yii::$app->request->post();
            $amsjson    =   base64_decode($postArr['paydata']);
            $params     =   json_decode($amsjson, true);
         
            $client     =   new Client($config);
        
            // Adding the Order Reference ID to the session so that we can use it in ConfirmAndAuthorize.php
            // Create the parameters array to set the order
            $requestParameters['amazon_order_reference_id'] = $postArr['orderReferenceId'];
            $requestParameters['mws_auth_token']            = null;

            // Confirm the order by making the ConfirmOrderReference API call
            $payresponse    =   $client->confirmOrderReference($requestParameters);
            
            // If the API call was a success make the Authorize (with Capture) API call
            if ($client->success)
            {
                $requestParameters['authorization_amount']          =   $params['amount'];
                $requestParameters['authorization_reference_id']    =   uniqid();
                $requestParameters['seller_authorization_note']     =   'Authorizing and capturing the payment';
                $requestParameters['transaction_timeout']           =   0;
                
                // For physical goods the capture_now is recommended to be set to false
                // When set to false, you will need to make a separate Capture API call in order to get paid
                // If you are selling digital goods or plan to ship the physical good immediately, set it to true
                $requestParameters['capture_now']       =   true;
                $requestParameters['soft_descriptor']   =   null;

                $payresponse   =   $client->authorize($requestParameters);
            }

            $paysucces  =   json_decode($payresponse->toJson(), true);
            
            if(!empty(@$paysucces['AuthorizeResult']) && !empty(@$paysucces['AuthorizeResult']['AuthorizationDetails'])){
                
                $result         =   $paysucces['AuthorizeResult']['AuthorizationDetails'];
           
                $params['transactionid']    =   $result['IdList']['member'];
                $params['price']            =   $result['AuthorizationAmount']['Amount'];
                $params['ptype']            =   'Amazon Pay';
                $params['number']           =   $params['mobile'];
                $transt    =   new PaymentDetails();

                $transt->transaction_id  =   $params['transactionid'];
                $transt->name            =   $params['name'];
                $transt->email           =   $params['email'];
                $transt->mobile          =   $params['mobile'];
                $transt->amount          =   $params['price'];
                $transt->paytype         =   $params['ptype'];

                if($transt->save()){

                    $data['subject'] = 'Payment Information';
                    $data['cc'] = $params['email'];
                    $table= '<table>';

                    $table .= '<tr><td>Transaction ID : </td><td>'.$params['transactionid'].'</td></tr>';
                    $table .= '<tr><td>Payment By : </td><td>'.$params['ptype'].'</td></tr>';
                    $table .= '<tr><td>Name : </td><td>'.$params['name'].'</td></tr>';
                    $table .= '<tr><td>Email : </td><td>'.$params['email'].'</td></tr>';
                    $table .= '<tr><td>Mobile Number : </td><td>'.$params['mobile'].'</td></tr>';
                    $table .= '<tr><td>Paid amount : </td><td>'.$params['price'].'</td></tr>';
                    $table .= '</table>';

                    $data['content'] = $table;
                    MailSend::mail_to_user($data);
                    MailSend::mail_to_owner($data);
                   //MailSend::test_mail('chandan@mailinator.com');
                }
                $data       =   json_encode($params);
                $paydata    =   base64_encode($data);

                $response['status']     =   'success';
                $response['msg']        =   'Your payment has been successfully done.';
                $response['url']        =   Url::to(['/success', 'success' => $paydata]);
            }else{
                $response['status']     =   'error';
                $response['msg']        =   'Your payment not be done. Kindly try again.';
            }
            return json_encode($response);
        }
	}
}
