<?php
//  ini_set("error_reporting", E_ALL);
//  ini_set("display_errors", true);
    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']);
    $app_price = DEFAULT_PRICE;
    $channel_id = 1;
    $store_hash = "";
    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'];
        if($channel_id != 1){
            $app_price = CHANNEL_PRICE;
        }
        $subscription_details = $db->select("subscription","*" ,array( "store_id" => $store_hash, "channel_id"=> $channel_id));
        if(isset($_REQUEST["stripeToken"])){
            try {
                $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;
                $API_PATH = 'https://api.bigcommerce.com/stores/'.$store_hash;
                $access_token = $db->getSingleColumn( "stores", "access_token", array( "store_id" => $store_hash, "channel_id"=> $channel_id ));
                $headers = array(
                    "accept: application/json",
                    "content-type: application/json",
                    "x-auth-client: ".CLIENT_ID,
                    "x-auth-token: ".$access_token
                );
                $stripeCustomerID = "";
                $checkIfStripCutomer = $db->select("subscription","*" ,array( "store_id" => $store_hash, "channel_id"=> $channel_id));
                
                $getEmail = $db->select("stores","*" ,array( "store_id" => $store_hash, "channel_id"=> $channel_id));
                $stripe_obj = new \Stripe\StripeClient(
                    $stripe['secret_key']
                );
                $stripe_obj->customers->update(
                    $checkIfStripCutomer['stripe_customer_id'],
                    ["source"=> $_REQUEST["stripeToken"]]
                );
                $fields = array(
                    "card_user_name" => $cc_name,
                    "card_number" => $cc_number,
                    "phone" => $phone,
                    "address" => $address,
                    "city" => $city,
                    "state" => $state,
                    "country" => $country,
                    "complete_address" => $complete_address,
                    "updated_at" =>  date("Y-m-d H:i:s"),
                );
                $db->update("subscription", $fields, array("store_id"=> $store_hash, "channel_id"=> $channel_id));

                $success = "true";
                
            } catch (\Stripe\Exception\CardException $e) {
                $_GET["error"] = "Sorry! ".$e->getError()->message;
            }	
        }
    }
?>
<!DOCTYPE html>

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

</head>

<body>
    <?php require_once("header.php"); ?>

    <div class="container mt-3 d-flex justify-content-center">
        <div class="w-50">
            <div class="card mt-3 cstm-card w-100">
                <div class="card-body">
                    <h5 class="card-title">Current Payment Details</h5>
                    <div>
                        <span class="light-gray small-font">Your subscription</span><br />
                        <h6>Basic (USD $<? echo number_format($app_price, 2) ?>/month)</h6>
                    </div>
                    <div class="d-flex justify-content-between align-items-start pb-3 pt-3">
                        <div>
                            <span class="light-gray small-font">Credit Card</span><br />
                            <span>**** **** **** <? echo $subscription_details['card_number'];?></span>
                        </div>
                    </div>
                    <div class="row pb-3">
                        <div class="col-sm">
                            <span class="light-gray small-font">Name on Card</span><br />
                            <span><? echo $subscription_details['card_user_name'];?></span>
                        </div>
                        <div class="col-sm">
                            <span class="light-gray small-font">Billing Address</span><br />
                            <span><? echo $subscription_details['complete_address'];?></span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="card mt-3 cstm-card w-100 mb-5">
                <div class="card-body">
                    <h5 class="card-title mb-3">Update Payment Details</h5>
                    <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>"; ?>
                                    </div>
                                <?php
                            }
                            if($success){
                                ?>
                                    <div class="alert alert-success" role="alert">
                                        Details updated Successfully!
                                    </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" value="<? echo $subscription_details["card_user_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" name="cc-month">
                                        </div>
                                        <div class="col-4">
                                            <input required placeholder="YYYY"
                                                type="text" class="form-control cc-year" name="cc-year">
                                        </div>
                                        <div class="col-4">
                                            <input required placeholder="CVV"
                                                type="text" class="form-control cc-cvc" name="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"  value="<? echo $subscription_details['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" value="<? echo $subscription_details['address'];?>">
                        </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" value="<? echo $subscription_details['city'];?>" >
                                </div>
                            </div>
                        </div>
                        <button type="submit" name="update" class="btn btn-primary button-primary w-100">Update Details</button>
                        <a href="index.php?store_hash=<? echo $store_hash; ?>&channel_id=<? echo $channel_id; ?>" class="btn btn-secondary w-100 mt-3" style="color: white;" >Back</a>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <script>
        $(document).ready(function () {
            var success = "<? echo $success; ?>";
            if(success == "true"){
                setTimeout(() => {
                    window.location.href = "index.php?store_hash=<? echo $store_hash;?>&channel_id=<? echo $channel_id;?>";
                }, 200);
            }
            $(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>";
                    $(".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);
                }
            });
            var saved_country = "<? echo $subscription_details['country'];?>" ;
            // console.log(saved_country);
            var saved_state = "<? echo $subscription_details['state'];?>" ;
            setTimeout(() => { 
                $('#country option[value="'+saved_country+'"]').prop('selected', 'selected').change();
                setTimeout(() => { 
                    if($("select#state").length > 0){
                        $('#state option[value="'+saved_state+'"]').prop('selected', 'selected').change();
                    }
                    else{
                        $('#state').val(saved_state);
                    }
                }, 200);
            }, 200);

        });
    </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(),
                        name: $('.cc-name').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>