<?php
    include_once 'inc/database.php';

    require_once __DIR__ .'/stripe/autoload.php';

    \Stripe\Stripe::setApiKey($stripe['secret_key']);
    
    if(isset($_REQUEST["stripeToken"])){
        try {
            $store_hash = $_GET['store_hash'];

            $stripeCustomerID = "";
            $checkIfStripCutomer = $db->select("subscription","*" ,array( "store_id" => $store_hash,"status" => "active"));
            
            $getEmail = $db->select("stores","*" ,array( "store_id" => $store_hash));
            if (!isset($checkIfStripCutomer["id"])) {
                
                $customer = \Stripe\Customer::create([
                    'email' => $getEmail['admin_email'],
                    'description' => "Customer is created for BC Automatic PRomotions app for subscription purpose",
                    'source' => $_REQUEST["stripeToken"],
                ]);
                $stripeCustomerID = $customer->id;
            } else {
                $stripeCustomerID = $checkIfStripCutomer["id"];
            }

            $priceObj = \Stripe\Price::create([
                'unit_amount' => 899 ,
                'currency' => 'usd',
                'recurring' => ['interval' => 'day'],
                'product_data' => ['name' => 'Regular Subscription for BC Automatic Promotions'],
                // "test" => true // false for live
            ]);

            $subscriptionObj = \Stripe\Subscription::create([
                'customer' => $stripeCustomerID,
                'items' => [['price' => $priceObj->id]]
            ]);
            
            if ($subscriptionObj->status == 'active') {
                $fields = array(
                    "stripe_customer_id" => $stripeCustomerID,
                    "card_user_name" => $_REQUEST["card_owner_name"],
                    "stripe_price_id" => $priceObj->id,
                    "stripe_subscription_id" => $subscriptionObj->id,
                    "store_id" => $store_hash,
                    "status" => $subscriptionObj->status == 'active' ? "active" : $subscriptionObj->status
                );
                $db->insert("subscription",$fields);
                echo "<script> window.location.replace('payment_confirmation.php?store_hash=".$store_hash."') </script>";
            } else {
                echo "<script> window.location.href='charge.php?message=Payment was unsuccessfully. Please try again later!&status_success=status_success&store_hash=".$store_hash."' </script>";
            }

        } catch (Exception $e) {
            print_r($e);
        }	
	}
?>
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>Automatic Promotions</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <!--<link rel="stylesheet" type="text/css" href="assets/stripe/bootstrap/css/bootstrap.min.css" />-->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="assets/stripe/font-awesome/css/font-awesome.min.css" />
    <link rel="stylesheet" type="text/css" href="assets/css/style.css?v=2.0.4" />
    <script type="text/javascript" src="assets/stripe/js/jquery-1.10.2.min.js"></script>
    <script type="text/javascript" src="assets/stripe/bootstrap/js/bootstrap.min.js"></script>
    <style>
        .close{
            position: absolute;
            top: 10rem;
            right: 4rem;
        }
        #back_btn:focus, #back_btn:focus-visible {
            box-shadow: none;
            outline: none;
        }
    </style>
</head>

<body>

    <div class="app_conatiner">
        <div id="main_content">
            <div class="container">

                <div class="page-header">
                    <h4 class="app-name mt-3" >
                        <a href="load.php?store_hash=<?php echo $_GET['store_hash'];?>" style="" class="btn back_btn" id="back_btn">
                            <i style="padding: 0px 10px 10px 0px;" class="fa fa-arrow-left" aria-hidden="true"></i>
                        </a>
                        <span>Checkout Text Editor By WebEcommercePros</span>
                        <span class="req_feature">
                            <span class="contact-support">
                                <button id="support_btn1" class="btn support_btn">
                                <a href="//www.webecommercepros.com/" target="_blank">Contact Support</a></button>
                            </span>
                        </span> 
                    </h4>
                </div>

                <!-- Credit Card Payment Form - START -->

                <div class="container ">
                    <div class="row payment-form-container">
                        <div class="col-xs-12 col-md-4 col-md-offset-4">
                            <div class="panel panel-default Upgrade-Account">
                                <div class="panel-heading">
                                    <div class="row">
                                        <h3 class="text-center">Upgrade Your Account</h3>
                                    </div>
                                </div>
                                <form action="#" method="post" class="require-validation"
                                    data-cc-on-file="false"
                                    data-stripe-publishable-key="<?php echo $stripe['publishable_key'];?>"
                                >
                                    <div class="panel-body">
                                            <?php
                                            if(@$_GET['error']){
                                                ?>
                                                    <div class="alert alert-danger" role="alert">
                                                        <?php echo "<p>".$_GET['error']."</p>"; ?>
                                                        <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                                                    </div>
                                                <?php
                                            }
                                            ?>
                                        <div style="display:none;" class="alert alert-danger" role="alert">
                                            <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                                        </div>

                                        <div class="row">
                                            <div class="col-xs-12">
                                                <div class="form-group">
                                                    <label>CARD NUMBER</label>
                                                    <div class="input-group">
                                                        <input type="tel" id="ccnum" name="card" value=""
                                                            class="form-control card-number" placeholder="Valid Card Number" />
                                                        <span class="input-group-addon"><span class="fa fa-credit-card"></span></span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-xs-4 col-md-4">
                                                <div class="form-group">
                                                    <label><span class="hidden-xs">MONTH</span> </label>
                                                    <input type="tel" id="expmonth" name="month"
                                                        class="form-control card-expiry-month" placeholder="MM" />
                                                </div>
                                            </div>
                                            <div class="col-xs-4 col-md-4">
                                                <div class="form-group">
                                                    <label><span class="hidden-xs">YEAR</span></label>
                                                    <input type="tel" id="expyear" name="year"
                                                        class="form-control card-expiry-year" placeholder="YYYY" />
                                                </div>
                                            </div>
                                            <div class="col-xs-4 col-md-4 pull-right">
                                                <div class="form-group">
                                                    <label>CVC</label>
                                                    <input type="tel" id="cvv" name="cvc" class="form-control card-cvc"
                                                        placeholder="CVC" />
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-xs-12">
                                                <div class="form-group">
                                                    <label>CARD OWNER</label>
                                                    <input type="text" class="form-control" id="cname" name="card_owner_name"
                                                        placeholder="Card Owner Names" />
                                                </div>
                                            </div>
                                        </div>

                                    </div>
                                    <div class="panel-footer">
                                        <div class="row text-center">
                                            <div class="col-xs-12">
                                                <button type="submit" class="btn btn-lg btn-block containerBlock"
                                                    id="btn_payment">Upgrade ($8.99)</button>
                                            </div>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>

                <style>
                    .cc-img {
                        margin: 0 auto;
                    }
                </style>
                <!-- Credit Card Payment Form - END -->
                <div class="cc-logo-img" >
                    <a href="https://www.webecommercepros.com/" target="_blank" >
                        <img src="<?php BASE_PATH ?>assets/images/logo.png" />
                    </a>
                </div>

            </div>
        </div>
    </div>

    <script type="text/javascript" src="https://js.stripe.com/v2/"></script>



    <script type="text/javascript">
        $(function () {
            var $form = $(".require-validation");
            $('form.require-validation').bind('submit', function (e) {
                $('#btn_payment').attr("disabled", true);
                var $form = $(".require-validation"),
                    inputSelector = ['input[type=email]', 'input[type=password]',
                        'input[type=text]', 'input[type=file]',
                        'textarea'].join(', '),
                    $inputs = $form.find('.required').find(inputSelector),
                    $errorMessage = $form.find('div.error'),
                    valid = true;
                $errorMessage.addClass('hide');

                $('.has-error').removeClass('has-error');
                $inputs.each(function (i, el) {
                    var $input = $(el);
                    if ($input.val() === '') {
                        $input.parent().addClass('has-error');
                        $errorMessage.removeClass('hide');
                        e.preventDefault();
                    }
                });

                if (!$form.data('cc-on-file')) {
                    e.preventDefault();
                    Stripe.setPublishableKey($form.data('stripe-publishable-key'));
                    Stripe.createToken({
                        number: $('.card-number').val(),
                        cvc: $('.card-cvc').val(),
                        exp_month: $('.card-expiry-month').val(),
                        exp_year: $('.card-expiry-year').val()
                    }, stripeResponseHandler);
                }

            });

            function stripeResponseHandler(status, response) {
                if (response.error) {
                    $('#btn_payment').attr("disabled", false)
                    $(".alert-danger").html(response.error.message);
                    $(".alert-danger").show()
                    // alert(response.error.message)
                    // $('.error')
                    //     .removeClass('hide')
                    //     .find('.alert')
                    //     .text(response.error.message);
                } else {
                    // token contains id, last4, and card type

                    var token = response['id'];
                    // insert the token into the form so it gets submitted to the server
                    $form.find('input[type=text]').empty();
                    $form.append("<input type='hidden' name='stripeToken' value='" + token + "'/>");
                    $form.get(0).submit();
                }
            }

        });
    </script>

</body>

</html>