<?php
    include_once '../inc/database.php';
    include_once '../requestFunctions.php';
    include_once '../inc/functions.php';
    include_once "../countries.php";
    require_once '../vendor/autoload.php';
    \Stripe\Stripe::setApiKey($stripe['secret_key']);
    // ini_set("error_reporting", E_ALL);
    // ini_set("display_errors", true);
    $store_hash = "";
    $success = "false";
    $channel_id = 1;
    $app_price = DEFAULT_PRICE;
    if( isset($_GET['signed_payload']) || (isset($_GET['store_hash']) && !empty($_GET['store_hash'])) ){
        $data = decodeSignedRequest($_GET['signed_payload']);
        
		$access_payload	= $_GET['signed_payload'];
        $store_hash = $_GET['store_hash'];
        $channel_id = $_GET["channel_id"];
		$subscription_details = $db->select("subscription","*" ,array( "store_id" => $store_hash, "channel_id"=> $channel_id));
        if(isset($_REQUEST["stripeToken"])){
            try {
                $API_PATH = 'https://api.bigcommerce.com/stores/'.$store_hash;

                $access_token = $db->getSingleColumn( "stores", "access_token", array( "store_id" => $store_hash, "channel_id" => 1 ));

                $headers = array(
                    "accept: application/json",
                    "content-type: application/json",
                    "x-auth-client: ".CLIENT_ID,
                    "x-auth-token: ".$access_token
                );
                
                $cc_number = $_REQUEST["cc-number"];
                $cc_number = substr($cc_number, -4);
                $cc_name = preg_replace('/[^A-Za-z0-9\-]/', ' ', $_REQUEST["cc-name"]);
                $phone = $_REQUEST["phone"];
                $address1 = preg_replace('/[^A-Za-z0-9\-]/', ' ', $_REQUEST["address1"]);
                $country = $_REQUEST["country"];
                $state = preg_replace('/[^A-Za-z0-9\-]/', ' ', $_REQUEST["state"]);
                $city = preg_replace('/[^A-Za-z0-9\-]/', ' ', $_REQUEST["city"]);
                $complete_address = $address1 . " " .$city ." ". $state ." ". $country;
               
                $stripeCustomerID = "";

                $getEmail = $db->select("stores","*" ,array( "store_id" => $store_hash, "channel_id" => 1));

                if (!isset($subscription_details["id"])) {
                    $customer = \Stripe\Customer::create([
                        'email' => $getEmail["admin_email"],
                        'description' => $getEmail["admin_first_name"]." ".$getEmail["admin_last_name"]." ".SUBSCRIPTION_NAME,
                        'source' => $_REQUEST["stripeToken"],
                    ]); 
                    $stripeCustomerID = $customer->id;
                } else {
                    $stripeCustomerID = $subscription_details["stripe_customer_id"];
                        
                    $stripe_obj = new \Stripe\StripeClient(
                        $stripe['secret_key']
                    );
                    try{
                        $cancelObj = $stripe_obj->subscriptions->cancel(
                            $subscription_details["stripe_subscription_id"]
                        );
                    }
                    catch (Exception $e){
                        // print_r($e);
                    }
                }

                $priceObj = \Stripe\Price::create([
                    'unit_amount' => $app_price * 100,
                    'currency' => 'usd',
                    'recurring' => ['interval' => 'month'],
                    'product_data' => ['name' => $getEmail["admin_first_name"]." ".$getEmail["admin_last_name"]." ".SUBSCRIPTION_NAME],
                ]);
                $subscriptionObj = \Stripe\Subscription::create([
                    'customer' => $stripeCustomerID,
                    'items' => [['price' => $priceObj->id]],
                    "metadata"=> [
                        "app_id"=> APP_ID,
                        "store_hash"=> $store_hash,
                        "channel_id"=> $channel_id
                    ]
                ]);

                if ($subscriptionObj->status == 'trialing' || $subscriptionObj->status == 'active') {
                    $fields = array(
                        "stripe_customer_id" => $stripeCustomerID,
                        "card_user_name" => $cc_name,
                        "card_number" => $cc_number,
                        "phone" => $phone,
                        "address" => $address1,
                        "city" => $city,
                        "state" => $state,
                        "country" => $country,
                        "complete_address" => $complete_address,
                        "stripe_price_id" => $priceObj->id,
                        "stripe_subscription_id" => $subscriptionObj->id,
                        "store_id" => $store_hash,
                        "status" => $subscriptionObj->status == 'active' ? "active" : $subscriptionObj->status,
                        "app_price"=> $app_price,
                    );
                    if($subscription_details['id']){
                        $fields['updated_at'] = date("Y-m-d H:i:s");
                        $db->update("subscription", $fields, array("store_id"=> $store_hash, "channel_id" => $channel_id));
                    }
                    else{
                        $fields['channel_id'] = $channel_id;
                        $fields['created_at'] = date("Y-m-d H:i:s");
                        $db->insert("subscription", $fields);
                        $store_data = $db->select("stores", "*", array("store_id"=> $store_hash, "channel_id"=> $channel_id));
                        if(!isset($store_data["id"])){
                            $store_data = $db->select("stores", "*", array("store_id"=> $store_hash, "channel_id"=> 1));

                            $channel_url = $API_PATH."/v3/channels/$channel_id";
                            $channel_data = curlGetRequest($channel_url, $headers);
                            $channel_name = $store_data["store_name"]." $channel_id";
                            if($channel_data["data"]){
                                $channel_name = $channel_data["data"]["name"];
                            }
                            $store_data = $store_data;
                            $store_data["store_name"] = $channel_name;
                            $store_data["channel_id"] = $channel_id;
                            unset($store_data["id"]);
                            unset($store_data["created_at"]);
                            unset($store_data["updated_at"]);
                            unset($store_data["welcome"]);
                            unset($store_data["shipping"]);
                            unset($store_data["shippingexp"]);
                            unset($store_data["mode"]);
                                                        
                            $API_PATH = 'https://api.bigcommerce.com/stores/'.$store_hash;
                            $url = $API_PATH."/v3/sites?channel_id:in=$channel_id";
                            $result_site = curlGetRequest($url, $headers);
                            if($result_site["data"] && $result_site["data"][0]){
                                $store_data["store_url"] = $result_site["data"][0]["url"];
                            }  
                            
                            $db->insert("stores", $store_data);
                        }
                        if($store_data["id"]){
                            $store_data[] = $store_data;
                        }
                    }
                    

                    $store_data["script_enabled"] = 1;
                    $db->update("stores", $store_data, array("store_id"=> $store_hash, "channel_id" => $channel_id));
                    
                    $store_settings = $db->insert( "subscription_payments", array(
                        "subscription_id" => $subscriptionObj->id,
                        "price" => $app_price,
                        "status" => "paid",
                        "created_at" => date("Y-m-d H:i:s")
                    ));
                    
                    $success = "true";
                } else {
                    $_GET["error"] = "Something went wrong, Please try again later!";
                }                
            } catch (\Stripe\Exception\CardException $e) {
                $_GET["error"] = "Sorry! ".$e->getError()->message;
            }	
        }
    }

?>
<!DOCTYPE html>

<head>
    <link rel="stylesheet" href="styles/choose_plan.css">
    <link rel="stylesheet" href="styles/subscription.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>

<body>
    <?php require_once("header.php"); ?>
    
    <div class="container-fluid" id="grad1">
        <div class="row justify-content-center mt-0">
            <div class="p-0 mt-3 mb-2">
                <div class="cstm-card px-0 pt-4 pb-0 mt-3 mb-3">
                    <div class="row m-0">
                        <div class="">
                            <div id="msform">
                                <fieldset class="plan-container" style="display:none;">
                                    <div class="row" style="max-width: 1000px; margin: 0 auto;">
                                        <div class="col-4">
                                            <div class="card fs-title h-100" style="width: 100%;">
                                                <div class="card-body">
                                                    <div class="row mb-5">
                                                        <div class="col-8 text-start">
                                                            <div class="row">
                                                                <div class="col-4">
                                                                    <i style="font-size: 50px;" class="fa fa-gift primary-color" aria-hidden="true"></i>
                                                                </div>
                                                                <div class="col-8" style="padding-left: 0;" >
                                                                    <h5 class="">Basic </h5>
                                                                    <h5 class="primary-color">$<? echo $app_price; ?><sub class="primary-color">USD/MONTH </sub></h5>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div class="col-4" style="padding: 0;" >
                                                            <button type="button" class="billed-btn small-font">Billed
                                                                Monthly</button>
                                                        </div>
                                                    </div>
                                                    <div class="row text-start mt-3 align-items-center">
                                                        <div class="col-1"><span id="check"></span></div>
                                                        <div class="col-11">
                                                            <h6 class="mb-0 plan-detials">Product Level Promotion</h6>
                                                        </div>
                                                    </div>
                                                    <div class="row text-start mt-3 align-items-center">
                                                        <div class="col-1"><span id="check"></span></div>
                                                        <div class="col-11">
                                                            <h6 class="mb-0 plan-detials">Category Level Promotion</h6>
                                                        </div>
                                                    </div>
                                                    <div class="row text-start mt-3 align-items-center">
                                                        <div class="col-1"><span id="check"></span></div>
                                                        <div class="col-11">
                                                            <h6 class="mb-0 plan-detials">Order Level Promotion</h6>
                                                        </div>
                                                    </div>
                                                    <div class="row text-start mt-3 align-items-center">
                                                        <div class="col-1"><span id="check"></span></div>
                                                        <div class="col-11">
                                                            <h6 class="mb-0 plan-detials">Customer Level Promotion</h6>
                                                        </div>
                                                    </div>
                                                    <div class="row text-start mt-3 align-items-center">
                                                        <div class="col-1"><span id="check"></span></div>
                                                        <div class="col-11">
                                                            <h6 class="mb-0 plan-detials">Single Use Coupons</h6>
                                                        </div>
                                                    </div>
                                                    <div class="row text-start mt-3 align-items-center">
                                                        <div class="col-1"><span id="check"></span></div>
                                                        <div class="col-11">
                                                            <h6 class="mb-0 plan-detials">Help Center</h6>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-8">
                                            <div class="card">
                                                <div class="card-body d-flex justify-content-between">
                                                    <span class="small-font">Today's Chrage 
                                                        <span style="font-size: 20px;" class="primary-color">$<? echo $app_price; ?></span>
                                                        USD
                                                    </span>
                                                    <button style="pointer-events: none;" type="button"
                                                        class="cancel-subscription small-font btn btn-warning">Cancel
                                                        Subscription Anytime
                                                    </button>
                                                </div>
                                            </div>
                                            <div class="card mt-3 cstm-card w-100">
                                                <div class="card-body text-start">
                                                    <form action="" method="POST" class="require-validation"
                                                        data-cc-on-file="false"
                                                        data-stripe-publishable-key="<?php echo $stripe['publishable_key'];?>"
                                                    >
                                                        <?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="mb-3">
                                                            <label for="cc-name" class="form-label">Card Holder's
                                                                Name</label>
                                                            <input required type="text" class="form-control" name="cc-name">
                                                        </div>
                                                        <div class="mb-3">
                                                            <label for="cc-number" class="form-label">Credit
                                                                Card</label>
                                                            <div class="row g-2 align-items-center">
                                                                <div class="col-6">
                                                                    <input required placeholder="Card Number"
                                                                        type="text" class="form-control cc-number"
                                                                        name="cc-number"
                                                                    />
                                                                </div>
                                                                <div class="col-6">
                                                                    <div class="row g-2 align-items-center">
                                                                        <div class="col-4">
                                                                            <input required placeholder="MM"
                                                                                type="text" class="form-control cc-month">
                                                                        </div>
                                                                        <div class="col-4">
                                                                            <input required placeholder="YYYY"
                                                                                type="text" class="form-control cc-year">
                                                                        </div>
                                                                        <div class="col-4">
                                                                            <input required placeholder="CVV"
                                                                                type="text" class="form-control cc-cvc">
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div class="mb-3">
                                                            <label for="phone" class="form-label">Phone
                                                                Number</label>
                                                            <input required type="text" class="form-control" id="phone"
                                                                name="phone">
                                                        </div>
                                                        <div class="mb-3">
                                                            <label for="address1" class="form-label">Billing
                                                                Address</label>
                                                            <input required type="text" class="form-control"
                                                                id="address1" name="address1">
                                                        </div>
                                                        <div class="mb-5">
                                                            <div class="row g-2 align-items-center">
                                                                <div class="col-4">
                                                                    <label for="country"
                                                                        class="form-label">Country</label>
                                                                    <select required class="form-select" id="country"
                                                                        name="country">
                                                                        <option disabled selected value="">Select</option>
                                                                        <?
                                                                            foreach ($countries as $key => $country) {
                                                                                ?>
                                                                                    <option value="<? echo $key; ?>"> <? echo $key; ?> </option>
                                                                                <?php
                                                                            }
                                                                        ?>
                                                                    </select>
                                                                </div>
                                                                <div class="col-4 states-input">
                                                                    <label for="state" class="form-label">State</label>
                                                                    <input required type="text" class="form-control"
                                                                        id="state" name="state">
                                                                </div>
                                                                <div class="col-4">
                                                                    <label for="city" class="form-label">City</label>
                                                                    <input required type="text" class="form-control"
                                                                        id="city" name="city">
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div>
                                                            <p class="small-font">
                                                                You hereby authorise WebeCommercePros to charge you automatically every month until you cancel your subscription, and agree to WebeCommercePros <a href="https://www.webecommercepros.com/terms-of-use" class="primary-color">Terms of service</a> and <a href="https://www.webecommercepros.com/privacy-policy" class="primary-color">Privacy Policy</a>.
                                                            </p>
                                                        </div>
                                                        <button type="submit" name="update" class="btn btn-primary button-primary w-100">Subscribe</button>
                                                    </form>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <input type="button" name="next" class="next action-button d-none" value="Next Step" />
                                </fieldset>
                                <fieldset class="card p-3" style="margin: 0 auto; max-width: 600px;" >
                                    <h2 class="fs-title text-center">Congratulations!</h2> <br><br>
                                    <div class="row justify-content-center">
                                        <div class="col-3"> <img src="https://img.icons8.com/color/96/000000/ok--v2.png"
                                                class="fit-image"> </div>
                                    </div> <br><br>
                                    <div class="row justify-content-center">
                                        <div class="col-7 text-center">
                                            <h5>You have successfully subscribed!</h5>
                                            <p>Please wait while redirecting.</p>
                                        </div>
                                    </div>
                                </fieldset>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script>
        $(document).ready(function () {
            var current_fs, next_fs, previous_fs; //fieldsets
            var opacity;
            var success = <? echo $success; ?>;
            if(success == true){
                setTimeout(() => {
                    $(".next.action-button").trigger("click");
                    setTimeout(() => {
                        window.location.href = "<? echo BASE_PATH; ?>load.php?store_hash=<? echo $store_hash;?>&channel_id=<? echo $channel_id;?>";
                    }, 5000);
                }, 200);
            }
            else{
                $(".plan-container").show();
            }
            $(".next").click(function () {

                current_fs = $(this).closest("fieldset");
                next_fs = $(this).closest("fieldset").next();
                
                //Add Class Active
                $("#progressbar li").eq($("fieldset").index(next_fs)).addClass("active");

                //show the next fieldset
                next_fs.show();
                //hide the current fieldset with style
                current_fs.animate({ opacity: 0 }, {
                    step: function (now) {
                        // for making fielset appear animation
                        opacity = 1 - now;

                        current_fs.css({
                            'display': 'none',
                            'position': 'relative'
                        });
                        next_fs.css({ 'opacity': opacity });
                    },
                    duration: 600
                });
            });
            $(document).on("change", "#country", function(){
                var country = $(this).val();
                var countries_arr = <? echo json_encode($countries); ?>;
                var states_arr = countries_arr[country];
                console.log(states_arr);
                if(states_arr.length > 0){
                    var state_options = "<label for='state' class='form-label'>State</label><select required class='form-select' id='state' name='state'><option disabled selected value='' >Select</option>";
                    states_arr.map(function(state){
                        state_options += "<option value='"+state+"'>"+state+"</option>";
                    });
                    state_options += "</select>";
                    // $("select#state").
                    // $(".states-select").show();
                    $(".states-input").html(state_options);
                }
                else {
                    var state_input = '<label for="state" class="form-label">State</label> <input required type="text" class="form-control" id="state" name="state">';
                    $(".states-input").html(state_input);
                    // $(".states-select").css("display", "none");
                }
            });
            $(document).on("submit", "form.require-validation", function(){
                $("form.require-validation .button-primary").attr("disabled","true");
            });
        });
    </script>
    <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: $('.cc-number').val(),
                        cvc: $('.cc-cvc').val(),
                        exp_month: $('.cc-month').val(),
                        exp_year: $('.cc-year').val()
                    }, stripeResponseHandler);
                }

            });

            function stripeResponseHandler(status, response) {
                if (response.error) {
                $("form.require-validation .button-primary").removeAttr("disabled","true");

                    $('#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>