<?php

		$Subscription_info = $db->select("bc_ubSubscription", "*" , array( "store_id" => $store_hash));

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

       // print_r($created_date);
		
		if(array_search($created_date["admin_email"], $exception_emails) !== false){
		/*	$isActiveSubscription = true;*/
		}

        if(isset($created_date[0]))
        {

		  $created_at = $created_date[0]["created_at"]; 
        }else{
            $created_at = $created_date["created_at"]; 
        }


        //echo "created at is ",$created_at;

        $added_7_days = new DateTime($created_at);
        $added_7_days->modify('+7 days');
        $added_7_days = $added_7_days->format('Y-m-d H:i:s');

        $current_date = date("Y-m-d H:i:s");


		$expired_on = "";
		$subscription_expired = false;

		$user_store_hash=$store_hash;

		$user_account_id=$created_date[0]["merchnat_account_uuid"];
		
		$bc_ub_apiUrl = "https://api.bigcommerce.com/accounts/" .$user_account_id. "/graphql";
		
		include_once 'bigcommerce_unified_biling.php';

        //echo "days",$added_7_days;
		
		if(strtotime($current_date) <= strtotime($added_7_days)) {

            //echo "not expire";
            
        }
        else{
            
            $subscription_expired=true;
            
            if(count($Subscription_info)>0)
            {
                // echo "record  exist";
                if(!empty($Subscription_info["bc_subscripion_id"]))
                {
                    $store_subscription_id=$Subscription_info["bc_subscripion_id"];
                    $subscription_store_hash=$Subscription_info["store_id"];
                    $db_bc_cancelledAt=$Subscription_info["bc_cancelledAt"];
        
                    if(!empty($db_bc_cancelledAt))
                    {
                        date_default_timezone_set('UTC'); // Ensure UTC timezone
        
                        // Current UTC date in the required format
                        $currentDate = new DateTime('now', new DateTimeZone('UTC'));
        
                        
        
                        // Convert subscription date string to DateTime object
                        $subscriptionDate = DateTime::createFromFormat('Y-m-d\TH:i:s.v\Z', $db_bc_cancelledAt);
        
                        // Compare the dates
                        if ($currentDate >= $subscriptionDate) {
                           // echo "Subscription expired.";
        
                            mysqli_query($conn_db,"UPDATE `bc_ubSubscription` SET `subscription_status`='inactive',`bc_subcription_checkout_url`='',bc_subcription_checkout_id='',bc_subscripion_id='',bc_cancelledAt='' WHERE `store_id`='$store_hash'");
                            
                            echo '<script> window.location.reload();
        
                            </script>';
        
                        } else {
                           // echo "Subscription active.";
                        }
        
                    }
                    //fetch_bc_subscription($store_subscription_id,$subscription_store_hash);
                    
                }else if(!empty($Subscription_info["bc_subcription_checkout_url"]))
                {
                    $bc_checkout_url=$Subscription_info["bc_subcription_checkout_url"];

                   // print_r($Subscription_info);

                    $checkout_id=$Subscription_info["bc_subcription_checkout_id"];
                    
                    // first wee need to check when we create checkout because big commerce expire the checkout after 24 hours
                    $db_stored_date = $Subscription_info["checkout_created_at"];


                    $current_date = date("Y-m-d H:i:s");
                    
                    
                    $datetime1 = new DateTime($db_stored_date);
                    $datetime2 = new DateTime($current_date);
                    
                    
                    $interval = $datetime1->diff($datetime2);
                    
                    // Get total hours
                    $hours = $interval->days * 24 + $interval->h; // days * 24 + leftover hours
                    
                    /*echo "Time ago: " . $hours . " hour(s) ago";*/
                    if($hours>23)
                    {
                       // echo "expire";
                        
                        mysqli_query($Conn_db,"UPDATE bc_ubSubscription SET `bc_subcription_checkout_url`='',`bc_subcription_checkout_id`='' WHERE bc_subcription_checkout_url!='' AND `store_id`='$user_store_hash'");
                        echo '<script> window.location.reload();</script>';
                        
                    }





                    $bc_subscription_id=get_ub_checkout($checkout_id);

                    if(!empty($bc_subscription_id))
                    {
                        /*$bc_data=["bc_subscripion_id"=>$bc_subscription_id,"subscription_status"=>"active"];
                        $db->update("bc_ubSubscription", $bc_data, array("store_id" => $store_hash));*/

                        mysqli_query($Conn_db,"UPDATE bc_ubSubscription SET `bc_subscripion_id`='$bc_subscription_id',`subscription_status`='active' WHERE bc_subcription_checkout_url!='' AND `store_id`='$user_store_hash'");
                        

                    }
                    else{

                        $redirect_url="subscription/index.php?menu=subscription&checkout_url=".$bc_checkout_url."&store_hash=".$store_hash;
                        
                       // echo "record exist else run and checkout exist but subscription id not exist mean checkout status  is not uncompleted  reduirect user to app subscription page";
            
                        echo '<script> window.location.href="'.$redirect_url.'"
            
                        </script>';
                    }
                    
                    
                }else{
        
                    // echo "user cancel the subscription or uninstall the app so after one month subscription is expire and new checkout generated";
        
                        $create_checkout_data=create_ub_checkout($user_store_hash,$user_account_id);
        
                        if(count($create_checkout_data)>0)
                        {
                            $bc_checkout_id=$create_checkout_data[0];
                            $bc_checkout_url=$create_checkout_data[1]; 
                            
                            $current_date_time=date("Y-m-d H:i:s");
                            
                             $redirect_url="subscription/index.php?menu=subscription&checkout_url=".$bc_checkout_url."&store_hash=".$store_hash;
        
        
                            $checkout_record_insert=mysqli_query($conn_db,"UPDATE `bc_ubSubscription` SET `checkout_created_at`='$current_date_time', `bc_subcription_checkout_url`='$bc_checkout_url',bc_subcription_checkout_id='$bc_checkout_id',bc_cancelledAt='',bc_subscripion_id='' WHERE `store_id`='$store_hash'");
        
                            echo '<script>window.location.href="'.$redirect_url.'"
        
                            </script>';
        
        
        
                        }else{
                            //echo "checkout not genrate reload page";
                            echo '<script> window.location.reload();
        
                            </script>';
                        }
        
                }
                
            }
            else{
                
                //echo "record not exist mean user first time use app";
                $create_checkout_data=create_ub_checkout($user_store_hash,$user_account_id);
        
                if(count($create_checkout_data)>0)
                {
                    $bc_checkout_id=$create_checkout_data[0];
                    $bc_checkout_url=$create_checkout_data[1];
                    
                     $current_date_time=date("Y-m-d H:i:s");
                    
                     $redirect_url="subscription/index.php?menu=subscription&checkout_url=".$bc_checkout_url."&store_hash=".$store_hash;
                    $checkout_record_insert=mysqli_query($conn_db,"INSERT INTO `bc_ubSubscription` (`store_id`,`bc_subcription_checkout_url`,`bc_subcription_checkout_id`,`checkout_created_at`) VALUES('$store_hash','$bc_checkout_url','$bc_checkout_id','$current_date_time')");
        
                    echo '<script> window.location.href="'. $redirect_url.'"
        
                    </script>';
        
        
        
                }else{
                    //echo "checkout not genrate reload page";
                    echo '<script> window.location.reload();</script>';
                }
            }
            
            
            
        }
        
        /*here is end of unified billing big commerce code*/



?>