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

    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'];
		$access_token = $db->getSingleColumn( "stores", "access_token", array( "store_id" => $store_hash ));

        $headers = array(
			"accept: application/json",
			"content-type: application/json",
			"x-auth-client: ".CLIENT_ID,
			"x-auth-token: ".$access_token
		);

        $API_PATH = 'https://api.bigcommerce.com/stores/'.$store_hash;	
		$channels_url = $API_PATH."/v3/channels";
        $channels_arr = array();
		$channels = curlGetRequest($channels_url, $headers);
		if($channels["data"]){
            $channels_arr = $channels['data'];
		}
        $stores = $db->select("stores", "*", array( "store_id" => $store_hash));
        if($stores["id"]){
            $stores = array($stores); 
        }
        $channels_data = array();
        $created_date = $db->select("stores", "*", array( "store_id" => $store_hash));
        $created_date = $created_date["id"] ? $created_date : $created_date[0];
		$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 = "";
        $trial = true;
		$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 ));
				
				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);
				}
			}
		}
        foreach ($channels["data"] as $key => $channel) {
            foreach ($stores as $key => $store) {
                if($store['channel_id'] == $channel["id"]){
                    $subscription_details = $db->select("subscription","*" ,array( "store_id" => $store_hash, "channel_id" => $channel["id"] ));
                    $channel["enabled"] = $store["script_enabled"];
                    $channel["subscribed"] = $subscription_details["status"];
                    if($subscription_details["status"] == "active"){
                        $trial = false;
                    }
                }
            }
            array_push($channels_data, $channel);
        }
    }
    function titleBar_ (){
		global $store_hash;
		?>
			<h4 class="app-name" >
				<span><a style="color: white !important; text-decoration: none;" href="https://wepstaging.com/checkout_text_editor_app/load.php?store_hash=<? echo $store_hash; ?>&channel_id=<? echo $channel_id; ?>"><i class="fa fa-home" aria-hidden="true"></i> Checkout Text Editor By WebEcommercePros</a></span>
			</h4>
			<a style="margin-left: 10px" href="subscription/index.php?store_hash=<?php echo $store_hash; ?>&channel_id=<? echo $channel_id; ?>">
				<i style="font-size: 25px; color: white;" class="fa fa-sliders" aria-hidden="true"></i>
			</a>
		<?php
	}
    function subscribeBtn($days){
        ?>
            <div style="padding-right: 5px;" class="alert alert-warning fade show d-flex align-items-center justify-content-between mb-3 mt-3" 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>
            </div>
        <?php
    }
    function subscription_bar(){
        global $remaining_days;
        global $isActiveSubscription;
        global $subscription_expired;
        global $expired_on;
        if($remaining_days->days <= 7 && !$isActiveSubscription) { 
            if($remaining_days->days < 6) { 
                $days = 7 - $remaining_days->days; 
                subscribeBtn("in $days days"); 
            }
            else if($remaining_days->days == 6) {
                subscribeBtn("tomorrow"); 
            }
            else{
                subscribeBtn("today"); 
            }
        } 
        else if($expired_on){
            ?>
                <div style="padding-right: 5px;" class="alert alert-warning fade show d-flex align-items-center justify-content-between mb-3 mt-3" 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>
                        Your trial has expired. Please subscribe to continue using the service.
                    </div>
                </div>
            <?php
        }
    }
?>
<!DOCTYPE html>
<head>
    <link type="text/css" rel="stylesheet" href="<?php  echo BASE_PATH ?>assets/css/style.css?v=2.0.5">
    <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>
    <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>
<body style="background-color: #F5F5F5;" >
    <?php
        include_once("subscription/header.php");
    ?>
    <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>
    <div class="container mt-3">
        <? $trial && subscription_bar(); ?>
        <h3 class="mb-3" >Available Channels</h3>
        <?php
            foreach ($channels_data as $key => $channel) {
				$channel_id = (int) $channel["id"];
				$channel_name = $channel["name"];
                if($channel["platform"] == "bigcommerce" && $channel["type"] == "storefront" && $channel["is_enabled"] == "true"){
                    ?>
                        <div style="background:white; padding:20px" class="d-flex justify-content-between align-items-cetner mt-2">
                            <div>
                                <h5><?php echo $channel_name; ?></h5>
                            </div>
                            <?php
                                if($channel["subscribed"] == "active"){
                                    ?>
                                        <button id="unsubscribe-btn" data-value="<?php echo $channel_id; ?>" style="height: fit-content" type="button" class="btn btn-primary save-btn" >Unsubscribe</button>
                                    <?php
                                }
                                else{
                                    ?>
                                        <a style="height: fit-content" href="subscription/choose_plan.php?store_hash=<?php echo $store_hash; ?>&channel_id=<?php echo $channel_id; ?>&menu=subscription" class="btn btn-primary save-btn" >Subscribe</a>
                                    <?php
                                }
                            ?>
                        </div>
                    <?php
                }
			}
        ?>
    </div>
    <script>
        $(document).ready(function(){
            var submit_event = false;
            $(document).on("click", ".form-check-input", function(event){
                var _this = this;
                var channel_id = $(this).attr("data-value");
                var channel_name = $(this).attr("data-name");
                if(!submit_event){
                    Swal.fire({
                        icon: 'info',
                        title: !$(this).prop( "checked" ) ? 'Do you want to disable the checkout script for this store?' : 'Do you want to enable the checkout script for this store?',
                        confirmButtonText: 'Confirm',
                        showDenyButton: true,
                        denyButtonText: `Don't save`,
                    }).then((result) => {
                        /* Read more about isConfirmed, isDenied below */
                        if (result.isConfirmed) {
                            $.ajax({
                                url: "<? echo BASE_PATH;?>ajax.php",
                                method: "POST",
                                data:{
                                    "channel_name": channel_name,
                                    "channel_id": channel_id,
                                    "store_hash": "<?php echo $store_hash; ?>", 
                                    "status": !$(_this).prop( "checked" ) ? "disable" : "enable", 
                                    action: "handle_checkout_script",
                                },
                                dataType: "json",
                                success: function(res){
                                    Swal.fire({
                                        icon: res.status,
                                        title: res.message,
                                    });
                                    if(res.status == "success"){
                                        console.log( $(_this).prop( "checked" ));
                                        !$(_this).prop( "checked" ) ? $('.'+channel_id).html("Status: Disabled") : $('.'+channel_id).html("Status: Enabled")
                                    }
                                }
                            });
                        }
                        else{
                            submit_event = true;
                            $(_this).trigger("click");
                        }
                    });
                }
                else{
                    submit_event = false;
                }
            });
            $(document).on("click", "#unsubscribe-btn", function(){
                var channel_id = $(this).attr("data-value");
                Swal.fire({
                    title: 'Are you sure to cancle the subscription?',
                    confirmButtonText: 'Confirm',
                    showCancelButton: true,
                }).then((result) => {
                    /* Read more about isConfirmed, isDenied below */
                    $.ajax({
                        url: "<? echo BASE_PATH;?>ajax.php",
                        method: "POST",
                        data:{
                            "channel_id": channel_id, 
                            "store_hash": "<?php echo $store_hash; ?>", 
                            action: "unsubscribe",
                            
                        },
                        dataType: "json",
                        success: function(res){
                            if (res.status && result.isConfirmed) {
                                Swal.fire('Unsubscribe Successfuly!', '', 'success');
                                setTimeout(() => {
                                    window.location.reload();
                                }, 2000);
                            }
                        }
                    });
                });
            });
        });
    </script>
</body>

</html>