<?php

    include_once '../inc/database.php';
    include_once '../requestFunctions.php';
	include_once '../inc/functions.php';
    $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'];
        $subscriptions = $db->select("subscription","*" ,array( "store_id" => $store_hash, "status"=> "active"));
        if($subscriptions['id']){
            if($subscriptions['channel_id'] == $channel_id){
                $app_price = DEFAULT_PRICE;
            }
            else{
                $app_price = CHANNEL_PRICE;
            }
        }
        else if($subscriptions){
            if($subscriptions[0]["channel_id"] == $channel_id){
                $app_price = DEFAULT_PRICE;
            }
            else{
                $app_price = CHANNEL_PRICE;
            }
        }

        $subscription_details = $db->select("subscription","*" ,array( "store_id" => $store_hash, "channel_id" => $channel_id));

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

		$isActiveSubscription = $db->select("subscription", "*" , array( "store_id" => $store_hash, "channel_id" => $channel_id,"status" => "active"));

		$added_7_days = new DateTime($created_date["created_at"]);
		$added_7_days = $added_7_days->format('Y-m-d H:i:s');

		$remaining_days = date_diff(date_create($added_7_days), date_create(date("Y-m-d h:i:s")));
		$expired_on = "";
		$subscription_expired = false;
		if($remaining_days->days <= 7) {}
		else{
			if($isActiveSubscription){}
			else{
				$get_stripe_subscription_id = $db->getSingleColumn( "subscription", "stripe_subscription_id", array( "store_id" => $store_hash, "channel_id"=> $channel_id ));
				
				if($get_stripe_subscription_id){
					$get_subscription_payments = $db->getSingleColumn( "subscription_payments", "created_at", array( "subscription_id" => $get_stripe_subscription_id ));

					$date = strtotime($get_subscription_payments);
					$date = strtotime("+30 day", $date);
					$expired_on = date('F jS, Y', $date);
					$subscription_expired = true;
					
				}
				else{
					$date = strtotime($added_7_days);
					$date = strtotime("+7 day", $date);
					$expired_on = date('F jS, Y', $date);
				}
			}
		}
    }
    function buyNowBtn($days){
        ?>
        <div class="alert alert-warning fade show d-flex align-items-center justify-content-between mb-5" role="alert">
            <div>
                <svg class="bi flex-shrink-0 me-2" width="24" height="24" role="img" aria-label="Info:">
                    <use xlink:href="#info-fill" />
                </svg>
                You are using a free trial which will expire <? echo $days; ?>. Subscribe to prevent any interruption.
            </div>
            <!-- <button type="button" class="btn btn-primary button-primary">Subscribe</button> -->
        </div>
        <?php
    }
    function subscription_bar(){
        global $remaining_days;
        global $isActiveSubscription;
        if($remaining_days->days <= 7 && !$isActiveSubscription) { 
            if($remaining_days->days < 6) { 
                $days = 7 - $remaining_days->days; 
                buyNowBtn("in $days days"); 
            }
            else if($remaining_days->days == 6) {
                buyNowBtn("tomorrow"); 
            }
            else{
                buyNowBtn("today"); 
            }
        } 
    }
?>
<!DOCTYPE html>
<head>
    <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">
    <link rel="stylesheet" href="styles/subscription.css">
    <style>
        /* button.billed-btn {
            border: 1px solid;
            border-radius: 20px;
            padding: 3px 5px;
        } */
    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@9.17.1/dist/sweetalert2.all.min.js" ></script>
</head>
<body>
    <?php require_once("header.php"); ?>
    <div class="container mt-3">
        <svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
            <symbol id="check-circle-fill" fill="currentColor" viewBox="0 0 16 16">
                <path
                    d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z" />
            </symbol>
            <symbol id="info-fill" fill="currentColor" viewBox="0 0 16 16">
                <path
                    d="M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16zm.93-9.412-1 4.705c-.07.34.029.533.304.533.194 0 .487-.07.686-.246l-.088.416c-.287.346-.92.598-1.465.598-.703 0-1.002-.422-.808-1.319l.738-3.468c.064-.293.006-.399-.287-.47l-.451-.081.082-.381 2.29-.287zM8 5.5a1 1 0 1 1 0-2 1 1 0 0 1 0 2z" />
            </symbol>
            <symbol id="exclamation-triangle-fill" fill="currentColor" viewBox="0 0 16 16">
                <path
                    d="M8.982 1.566a1.13 1.13 0 0 0-1.96 0L.165 13.233c-.457.778.091 1.767.98 1.767h13.713c.889 0 1.438-.99.98-1.767L8.982 1.566zM8 5c.535 0 .954.462.9.995l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 5.995A.905.905 0 0 1 8 5zm.002 6a1 1 0 1 1 0 2 1 1 0 0 1 0-2z" />
            </symbol>
        </svg>
        <? subscription_bar(); ?>
        <div class="p">
            <h3>Plan & billing</h3>
            <span class="light-gray">View or modify your subscription plan or update your billing info.</span>
        </div>
        <div class="card mt-3 cstm-card" style="width: 100%;">
            <div class="card-body d-flex justify-content-between align-items-center">
                <div class="">
                    <h5 class="card-title mb-0 d-inline">Basic <span class="primary-color">$<? echo number_format($app_price, 2); ?> </span></h5><sub
                        class="primary-color">USD/MONTH </sub><button type="button" class="billed-btn small-font">Billed
                        Monthly</button>
                </div>
                <?php
                    if($subscription_details['status'] == "active"){
                        ?><button type="button" class="btn btn-primary button-primary" id="unsubscribe-btn" >Unsubscribe</button><?
                    }
                    else{
                        ?><a href="choose_plan.php?menu=subscription&store_hash=<? echo $store_hash; ?>&channel_id=<? echo $channel_id; ?>" class="btn btn-primary button-primary">Subscribe</a><?
                    }
                ?>
            </div>
        </div>
        <div class="card mt-3 cstm-card" style="width: 100%;">
            <div class="card-body">
                <h5 class="card-title">Current Payment Details</h5>
                <?php
                    if($subscription_details['status'] == "active"){
                        ?>
                            <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><?php echo $subscription_details['card_number'] ? "**** **** **** ".$subscription_details['card_number'] : "Not Provided"; ?></span>
                                </div>
                                <a href="subscription_details.php?store_hash=<? echo $store_hash; ?>&channel_id=<? echo $channel_id; ?>" class="btn btn-primary button-primary">Edit</a>
                            </div>
                            <div class="row pb-3">
                                <div class="col-sm">
                                    <span class="light-gray small-font">Name on Card</span><br />
                                    <span><?php echo $subscription_details['card_user_name'] ? $subscription_details['card_user_name'] : "Not Provided"; ?></span>
                                </div>
                                <div class="col-sm">
                                    <span class="light-gray small-font">Billing Address</span><br />
                                    <span><?php echo $subscription_details['complete_address'] ? $subscription_details['complete_address'] : "Not Provided"; ?></span>
                                </div>
                            </div>
                        <?php
                    }
                    else{
                        ?>
                            <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>Not Provided</span>
                                </div>
                                <button type="button" class="btn btn-primary button-primary disabled">Edit</button>
                            </div>
                            <div class="row pb-3">
                                <div class="col-sm">
                                    <span class="light-gray small-font">Name on Card</span><br />
                                    <span>Not Provided</span>
                                </div>
                                <div class="col-sm">
                                    <span class="light-gray small-font">Billing Address</span><br />
                                    <span>Not Provided</span>
                                </div>
                            </div>
                        <?php
                    }
                ?>
            </div>
        </div>
    </div>
    <script>
        $(document).ready(function(){
            $(document).on("click", "#unsubscribe-btn", function(){
                Swal.fire({
                    title: 'Are you sure to cancel the subscription?',
                    confirmButtonText: 'Confirm',
                    showCancelButton: true,
                }).then((result) => {
                    /* Read more about isConfirmed, isDenied below */
                    if (result.isConfirmed) {
                        $.ajax({
                            url: "<? echo BASE_PATH;?>ajax.php",
                            method: "POST",
                            data:{
                                "channel_id": "<?php echo $channel_id; ?>", 
                                "store_hash": "<?php echo $store_hash; ?>", 
                                action: "unsubscribe",
                                
                            },
                            dataType: "json",
                            success: function(res){
                                if (res.status && result.isConfirmed) {
                                    Swal.fire('Unsubscribed Successfuly!', '', 'success');
                                    setTimeout(() => {
                                        window.location.reload();
                                    }, 2000);
                                }
                            }
                        });
                    }
                });
            });
        });
    </script>
</body>

</html>