<?php 
require_once ST_ABSPATH . "vendor/autoload.php";
use \Firebase\JWT\JWT;
use Firebase\JWT\Key;

add_action('init', 'st_init_auth');
function st_init_auth() {
    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        if (isset($_GET['licenses_method']) && $_GET['licenses_method'] === "woo-checkout") {
            if (isset($_GET['key']) && !empty($_GET['key'])) {
                $token = $_GET['key'];
                try {
                    $decoded = JWT::decode($token, new Key(LICENSE_TOKEN_SALT, 'HS256'));
                    $decoded_token = (array) $decoded;
                    $spacetree_user_email = $decoded_token['user_email'];
                    $user_check = get_user_by('email', $spacetree_user_email);

                    if (!$user_check) {
                        wp_redirect("/shop");
                        exit;
                    }

                    $user_id = $user_check->ID;
                    wp_set_auth_cookie($user_id);

                    // Set session data for product and redirect if not yet in cart
                    if (isset($_GET['product_id']) && !empty($_GET['product_id'])) {
                        // $_SESSION['product_id_to_add'] = $_GET['product_id'];
                        // $_SESSION['redirect_after_add_to_cart'] = $_GET['redirect'] ?? '/shop';
                        
                        // Redirect to a custom URL to trigger the add-to-cart on the next page load
                        wp_safe_redirect('/?wo_cart='.$_GET['product_id']);
                        exit;
                    }
                } catch (Exception $e) {
                    wp_redirect("/shop"); // Redirect if token decoding fails
                    exit;
                }
            }
        } else if (!empty($_GET['wp_cart']) && isset($_GET['wp_cart'])) { 
            // wp_safe_redirect("/checkout");
            // exit;
        }
    }
}

// Handle the custom add-to-cart and redirect logic
add_action('template_redirect', 'st_add_product_to_cart');
function st_add_product_to_cart() {
    if (!empty($_GET['wo_cart']) && isset($_GET['wo_cart'])) {
        $product_id = $_GET['wo_cart'];
        WC()->cart->empty_cart();
        // Initialize WooCommerce cart and add product
        if (WC()->cart->add_to_cart($product_id)) {
            // $redirect_url = $_SESSION['redirect_after_add_to_cart'];
            
            // Clear session data after adding to prevent multiple adds
            // unset($_SESSION['product_id_to_add'], $_SESSION['redirect_after_add_to_cart']);
            
            // Redirect to the final destination
            wp_safe_redirect("/checkout");
            exit;
        }
    }
}
