<?php

use app\modules\subscription\models\SubscriptionPrice;
use app\modules\subscription\models\SubscriptionProduct;
use yii\helpers\Url;

/* @var $price SubscriptionPrice */
/* @var $subscription app\modules\subscription\models\Subscription|null */
/* @var $now int 1 or 0 */

// Paypal Plan ID
$paypalPlanId = $price->getPaypalId();

// Paypal Client ID
$paypalClientId = Yii::$app->settings->get('subscription.paypalLiveClientID');
if (Yii::$app->settings->get('subscription.environment') == SubscriptionProduct::MODE_TEST) {
    $paypalClientId = Yii::$app->settings->get('subscription.paypalSandboxClientID');
}

// If there is a not-cancelled subscription
$changeSubscription = $subscription && !$subscription->cancelled() ? 1 : 0;

// Subscription id
$subscriptionID = $changeSubscription ? $subscription->gateway_id : null;

// URL to validate the subscription
$url = $changeSubscription
    ? Url::to(['/subscription/user/change-paypal-plan'])
    : Url::to(['/subscription/user/create']);

$locale = str_replace('-', '_', Yii::$app->language);

?>

<div id="paypal-button-container" style="width: 80%; margin-top: 30px"></div>

<?php if ($price->type == SubscriptionPrice::TYPE_RECURRING): ?>

<script src="https://www.paypal.com/sdk/js?client-id=<?= $paypalClientId ?>&vault=true&intent=subscription&locale=<?= $locale ?>" data-sdk-integration-source="button-factory"></script>

<?php

$script = <<<JS

    var changeSubscription = {$changeSubscription};
    var now = {$now};

    paypal.Buttons({
        style: {
            color: 'gold',
            shape: 'pill',
            label: 'subscribe',
            height: 40
        },
        createSubscription: function(data, actions) {
            if (changeSubscription && !now) {
                return actions.subscription.revise('{$subscriptionID}', {
                    plan_id: '{$paypalPlanId}'
                });
            } else {
                return actions.subscription.create({
                    'plan_id': '{$paypalPlanId}'
                });
            }
        },
        onApprove: function(data, actions) {
            jQuery('#subscription-pending').show();
            jQuery('#subscription-product').hide();
            jQuery.post( "{$url}", { id: {$price->id}, now: {$now}, details: JSON.stringify(data) })
                .done(function(res) {
                    if (typeof res.success !== 'undefined' && res.success) {
                        if (typeof res.action !== 'undefined' && res.action === 'redirect') {
                            window.location.href = res.url;
                        } else if (typeof res.action !== 'undefined' && res.action === 'message') {
                            if (typeof res.message !== 'undefined' && res.message.length > 0) {
                                alert(res.message);
                            }
                        }
                    }
                })
                .fail(function() {
                    alert("An error occurred. Please contact us.");
                })
        }
    }).render('#paypal-button-container');

JS;

$this->registerJs($script, $this::POS_END);
?>

<?php else: ?>

<script type='text/javascript' src='https://www.paypal.com/sdk/js?client-id=<?= $paypalClientId ?>&locale=<?= $locale ?>'></script>

<?php
$script = <<<JS

    [ '#paypal-button-container' ].forEach(function(selector) {

        var style = {
            color: 'gold',
            shape: 'pill',
            label: 'checkout',
            height: 40
        };

        if (selector === '#paypal-button-1') {
            style = {
                color:  'blue',
                shape:  'pill',
                label:  'buynow',
                height: 55
            }
        }

        paypal.Buttons({

            style: style,

            createOrder: function(data, actions) {
                return actions.order.create({
                    purchase_units: [{
                        description: '{$price->product->name}',
                        amount: {
                            currency_code: '{$price->currency_code}',
                            value: '{$price->getFormattedAmount()}'
                        }
                    }]
                });
            },

            onApprove: function(data, actions) {
                return actions.order.capture().then(function(details) {
                    jQuery('#subscription-pending').show();
                    jQuery('#subscription-product').hide();
                    jQuery.post("{$url}", { id: {$price->id}, details: JSON.stringify(details) })
                        .done(function(res) {
                            if (typeof res.success !== 'undefined' && res.success) {
                                if (typeof res.action !== 'undefined' && res.action === 'redirect') {
                                    window.location.href = res.url;
                                } else if (typeof res.action !== 'undefined' && res.action === 'message') {
                                    if (typeof res.message !== 'undefined' && res.message.length > 0) {
                                        alert(res.message);
                                    }
                                }
                            }
                        })
                        .fail(function() {
                            alert("An error occurred. Please contact us.");
                        })
                });
            }
        }).render(selector);
    });
JS;

$this->registerJs($script, $this::POS_END);
?>

<?php endif; ?>