<?php
class KavehApphandler {
    // Constructor to initialize hooks
    public function __construct() {
        
        // Register custom rewrite rule for /apphandler
        add_action('init', [$this, 'register_rewrite_rule']);
        // Add custom query variable
        add_filter('query_vars', [$this, 'add_query_vars']);
        // Handle the custom endpoint when visited
        add_action('template_redirect', [$this, 'handle_cookie_transfer']);
    }

    // Register custom rewrite rule for /apphandler
    public function register_rewrite_rule() {
        add_rewrite_rule('^apphandler/?$', 'index.php?apphandler=1', 'top');
    }

    // Add custom query variable to WordPress
    public function add_query_vars($query_vars) {
        $query_vars[] = 'apphandler';
        return $query_vars;
    }

    // Handle the cookie transfer when /apphandler is accessed
    public function handle_cookie_transfer() {
        // Check if the custom query variable is set (i.e., /apphandler is accessed)
        if (get_query_var('apphandler') == 1) {
            // Get the cookies parameter from the query string
            $base64_cookies = isset($_GET['cookies']) ? sanitize_text_field($_GET['cookies']) : '';

            if (!$base64_cookies) {
                wp_die('No cookies provided', 'Error', array('response' => 400));
            }

            // Decode base64 to JSON
            $decoded_cookies = base64_decode($base64_cookies);
            $cookies_array = json_decode($decoded_cookies, true);
            
            if (json_last_error() !== JSON_ERROR_NONE) {
                wp_die('Invalid cookie data', 'Error', array('response' => 400));
            }

            // Set the cookies in the browser
            foreach ($cookies_array as $cookie_name => $cookie_value) {
                // URL decode the cookie value (to handle encoded characters like %7C)
                $cookie_value = urldecode($cookie_value);
                // Set each cookie with a 1-hour expiry time (adjust domain to match your setup)
                setcookie($cookie_name, $cookie_value, time() + 3600, COOKIEPATH, COOKIE_DOMAIN);
            }

            $checkout_url = add_query_arg( 'redirect_to_checkout_from_app', 'true', wc_get_checkout_url() );
            wp_redirect( $checkout_url );
            exit;
        }
    }
}
