<?php

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

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

// Plan Type
$isRecurring = $price->type === SubscriptionPrice::TYPE_RECURRING ? 1 : 0;
$stripePlanId = null;
$intent = null;

if ($isRecurring) {

    // Stripe Plan ID
    $stripePlanId = $price->getStripeId();

} else {

    if (!empty($price->amount) && !empty($price->currency_code)) {
        // Stripe Payment Intent
        $stripeClient = new StripeClient();
        $intent = $stripeClient->paymentIntent($price->amount, strtolower($price->currency_code));
    }

}

// stripe Client ID
$stripePublishableKey = Yii::$app->settings->get('subscription.stripeLivePublishableKey');
if (Yii::$app->settings->get('subscription.environment') == SubscriptionProduct::MODE_TEST) {
    $stripePublishableKey = Yii::$app->settings->get('subscription.stripeSandboxPublishableKey');
}

// 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-stripe-plan'])
    : Url::to(['/subscription/user/create']);

?>

<script src="https://js.stripe.com/v3/"></script>
    <style>
        #stripe-form {
            align-self: center;
        }
        #stripe-form input {
            border-radius: 6px;
            margin-bottom: 6px;
            padding: 12px;
            border: 1px solid #dddddd;
            height: 44px;
            font-size: 16px;
            width: 100%;
            background: white;
        }
        #stripe-form .result-message {
            line-height: 22px;
            font-size: 16px;
        }
        #stripe-form .result-message a {
            color: rgb(89, 111, 214);
            font-weight: 600;
            text-decoration: none;
        }
        #stripe-form .hidden {
            display: none;
        }
        #card-error {
            text-align: left;
            line-height: 17px;
            margin-top: 12px;
        }
        #card-element {
            border-radius: 4px 4px 0 0 ;
            padding: 12px;
            border: 1px solid rgba(50, 50, 93, 0.1);
            height: 44px;
            width: 100%;
            background: white;
        }
        #payment-request-button {
            margin-bottom: 32px;
        }
        /* Buttons and links */
        #stripe-form button {
            background: #009eda;
            color: #ffffff;
            border-radius: 0 0 4px 4px;
            border: 0;
            padding: 12px 16px;
            font-weight: 600;
            cursor: pointer;
            display: block;
            transition: all 0.2s ease;
            box-shadow: 0px 4px 5.5px 0px rgba(0, 0, 0, 0.07);
            width: 100%;
        }
        #stripe-form button:hover {
            filter: contrast(115%);
        }
        #stripe-form button:disabled {
            opacity: 0.5;
            cursor: default;
        }
        /* spinner/processing state, errors */
        #stripe-form .spinner,
        #stripe-form .spinner:before,
        #stripe-form .spinner:after {
            border-radius: 50%;
        }
        #stripe-form .spinner {
            color: #ffffff;
            font-size: 22px;
            text-indent: -99999px;
            margin: 0px auto;
            position: relative;
            width: 20px;
            height: 20px;
            box-shadow: inset 0 0 0 2px;
            -webkit-transform: translateZ(0);
            -ms-transform: translateZ(0);
            transform: translateZ(0);
        }
        #stripe-form .spinner:before,
        #stripe-form .spinner:after {
            position: absolute;
            content: "";
        }
        #stripe-form .spinner:before {
            width: 10.4px;
            height: 20.4px;
            background: #5469d4;
            border-radius: 20.4px 0 0 20.4px;
            top: -0.2px;
            left: -0.2px;
            -webkit-transform-origin: 10.4px 10.2px;
            transform-origin: 10.4px 10.2px;
            -webkit-animation: loading 2s infinite ease 1.5s;
            animation: loading 2s infinite ease 1.5s;
        }
        #stripe-form .spinner:after {
            width: 10.4px;
            height: 10.2px;
            background: #5469d4;
            border-radius: 0 10.2px 10.2px 0;
            top: -0.1px;
            left: 10.2px;
            -webkit-transform-origin: 0px 10.2px;
            transform-origin: 0px 10.2px;
            -webkit-animation: loading 2s infinite ease;
            animation: loading 2s infinite ease;
        }
        @-webkit-keyframes loading {
            0% {
                -webkit-transform: rotate(0deg);
                transform: rotate(0deg);
            }
            100% {
                -webkit-transform: rotate(360deg);
                transform: rotate(360deg);
            }
        }
        @keyframes loading {
            0% {
                -webkit-transform: rotate(0deg);
                transform: rotate(0deg);
            }
            100% {
                -webkit-transform: rotate(360deg);
                transform: rotate(360deg);
            }
        }
        @media only screen and (max-width: 600px) {
            #stripe-form  {
                width: 80vw;
            }
        }
    </style>

    <div class="stripe-button-container" style="width: 80%; margin-top: 30px">
        <form id="stripe-form" class="form-vertical" action="<?= Url::to(['/subscription/user/create']) ?>" method="post" <?php if (isset($intent->client_secret)): ?>data-secret="<?= $intent->client_secret ?>"<?php endif; ?>>
            <label style="control-label"><?= Yii::t('app', 'Credit/Debit Card') ?></label>
            <input type="hidden" name="<?= Yii::$app->request->csrfParam; ?>" value="<?= Yii::$app->request->csrfToken; ?>" />
            <input type="hidden" name="id" value="<?= $price->id ?>">
            <div id="card-element"><!--Stripe.js injects the Card Element--></div>
            <button>
                <span class="spinner hidden" id="spinner"></span>
                <span id="button-text"><?= Yii::t('app', 'Subscribe') ?></span>
            </button>
            <div class="text-danger">
                <p id="card-error" role="alert"></p>
            </div>
            <p class="result-message hidden">
                <?= Yii::t('app', 'Subscription succeeded!') ?>
            </p>
        </form>
    </div>

<?php

$script = <<<JS

var isRecurring = {$isRecurring};
var stripe = Stripe('{$stripePublishableKey}');

// Create an instance of elements
var elements = stripe.elements();

var style = {
    base: {
        fontWeight: 400,
        fontFamily: 'Roboto, Open Sans, Segoe UI, sans-serif',
        fontSize: '16px',
        lineHeight: '1.4',
        color: '#555',
        backgroundColor: '#fff',
        '::placeholder': {
            color: '#888'
        }
    },
    invalid: {
        color: '#eb1c26'
    }
};

var card = elements.create("card", { style: style });
    // Stripe injects an iframe into the DOM
    card.mount("#card-element");

card.on("change", function (event) {
    // Disable the Pay button if there are no card details in the Element
    document.querySelector("button").disabled = event.empty;
    document.querySelector("#card-error").textContent = event.error ? event.error.message : "";
});

// Get payment form element
var form = document.getElementById('stripe-form');

// Create a token when the form is submitted.
form.addEventListener('submit', function(e) {
    e.preventDefault();
    if (isRecurring) {
        createToken();
    } else {
        // Complete payment when the submit button is clicked
        payWithCard(stripe, card, form.dataset.secret);
    }
});

// Create single-use token to subscribe the user
function createToken() {
    stripe.createToken(card).then(function(result) {
        if (result.error) {
            // Inform the user if there was an error
            document.querySelector("#card-error").textContent = result.error.message;
        } else {
            // Send the token to your server
            stripeTokenHandler(result.token);
        }
    });
}

// Callback to handle the response from stripe
function stripeTokenHandler(token) {
    // Insert the token ID into the form so it gets submitted to the server
    var hiddenInput = document.createElement('input');
    hiddenInput.setAttribute('type', 'hidden');
    hiddenInput.setAttribute('name', 'token');
    hiddenInput.setAttribute('value', token.id);
    form.appendChild(hiddenInput);
	
    // Submit the form
    jQuery('#subscription-pending').show();
    jQuery('#subscription-product').hide();
    jQuery.post("{$url}", $("#stripe-form").serialize())
        .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.");
        })
}

// Callback to handle the response from stripe
function stripePaymentHandler(paymentIntent) {
    // Insert the token ID into the form so it gets submitted to the server
    var hiddenInput = document.createElement('input');
    hiddenInput.setAttribute('type', 'hidden');
    hiddenInput.setAttribute('name', 'paymentIntent');
    hiddenInput.setAttribute('value', paymentIntent.id);
    form.appendChild(hiddenInput);
	
    // Submit the form
    jQuery('#subscription-pending').show();
    jQuery('#subscription-product').hide();
    jQuery.post("{$url}", $("#stripe-form").serialize())
        .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.");
        })
}

var payWithCard = function(stripe, card, clientSecret) {
  stripe
    .confirmCardPayment(clientSecret, {
      payment_method: {
        card: card
      }
    })
    .then(function(result) {
      if (result.error) {
          // Show error to your customer
          document.querySelector("#card-error").textContent = result.error.message;
      } else {
        // The payment succeeded!
        stripePaymentHandler(result.paymentIntent);
      }
    });
};

JS;

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