<?php
/**
 * Plugin Name: AR for WordPress
 * Plugin URI: https://augmentedrealityplugins.com
 * Description: AR for WordPress Augmented Reality plugin.
 * Version: 8.36
 * Author: Web and Print Design
 * Author URI: https://webandprint.design
 * License: GPL2
 * Text Domain: ar-for-wordpress
 * Domain Path: /languages
 */

defined( 'ABSPATH' ) || exit;

// --------------------------------------------------
// Global Plugin Setup
// --------------------------------------------------

global $ar_version, $ar_plugin_id, $ar_plugin_root_url;
$plugin_data = get_file_data(__FILE__, array('Version' => 'Version'), false);
$ar_version = $plugin_data['Version'];

$ar_plugin_id = 'ar-for-wordpress';
$ar_plugin_root_url = plugin_dir_url( __FILE__ );

// --------------------------------------------------
// Load Translations (WordPress 6.7+ compliant)
// --------------------------------------------------

add_action( 'init', 'ar_for_wordpress_load_textdomain' );
function ar_for_wordpress_load_textdomain() {
    load_plugin_textdomain( 'ar-for-wordpress', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
}

// --------------------------------------------------
// Load ar-class.php early
// --------------------------------------------------

require_once plugin_dir_path( __FILE__ ) . 'includes/ar-class.php';
require_once plugin_dir_path( __FILE__ ) . 'includes/ardisplay_ai/class-ardisplay-ai-rest.php';
require_once plugin_dir_path( __FILE__ ) . 'includes/ar-analytics.php';

if ( ! function_exists( 'ar_output_default_favicon' ) ) {
	function ar_output_default_favicon() {
		$icon_data = base64_decode( 'iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOCAYAAAAfSC3RAAAALElEQVQoU2NkIBIwEqmOYVAosL///xkYGBgkGo0Go6GhgWg0Gg0mIQYAtSMe8GFs0dUAAAAASUVORK5CYII=' );

		if ( empty( $icon_data ) ) {
			status_header( 204 );
			exit;
		}

		status_header( 200 );
		nocache_headers();
		header( 'Content-Type: image/png' );
		header( 'Content-Length: ' . strlen( $icon_data ) );
		header( 'Cache-Control: public, max-age=31536000' );
		echo $icon_data; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		exit;
	}

	add_action( 'do_faviconico', 'ar_output_default_favicon' );
}

// --------------------------------------------------
// Load Security Enhancements
// --------------------------------------------------

require_once plugin_dir_path( __FILE__ ) . 'includes/ar-security.php';

// --------------------------------------------------
// Load Remaining Plugin Files (on init)
// --------------------------------------------------

add_action( 'init', 'ar_for_wordpress_load_plugin_files', 5 );
function ar_for_wordpress_load_plugin_files() {
    require_once plugin_dir_path( __FILE__ ) . 'includes/ar-model.php';
    require_once plugin_dir_path( __FILE__ ) . 'ar-wp-functions.php';
    require_once plugin_dir_path( __FILE__ ) . 'ar-model-fields.php';
    require_once plugin_dir_path( __FILE__ ) . 'includes/ar-initialise.php';
    require_once plugin_dir_path( __FILE__ ) . 'includes/ar-settings.php';
    require_once plugin_dir_path( __FILE__ ) . 'includes/ar-file-handling.php';
    require_once plugin_dir_path( __FILE__ ) . 'includes/ar-gallery-builder.php';
    require_once plugin_dir_path( __FILE__ ) . 'includes/ar-user-upload.php';
    require_once plugin_dir_path( __FILE__ ) . 'includes/ar-qrcode.php';
    require_once plugin_dir_path( __FILE__ ) . 'includes/onboarding/class-ar-onboarding.php';
    require_once plugin_dir_path( __FILE__ ) . 'includes/ar-standalone.php';
    require_once plugin_dir_path( __FILE__ ) . 'ar-model-post-type.php';
    require_once plugin_dir_path( __FILE__ ) . 'ar-widgets.php';
    require_once plugin_dir_path( __FILE__ ) . 'ar-api.php';
    require_once plugin_dir_path( __FILE__ ) . 'includes/ar-add-media.php';
    require_once plugin_dir_path( __FILE__ ) . 'includes/ar-model-shop.php';
    require_once plugin_dir_path( __FILE__ ) . 'includes/ar-secure-url-generate.php';
    require_once plugin_dir_path( __FILE__ ) . 'gutenberg-block/gutenberg-block.php';

    $this_file = __FILE__;
    $update_check = "https://augmentedrealityplugins.com/plugins/check-update-ar-for-wordpress.txt";
    require_once plugin_dir_path( __FILE__ ) . 'ar-updates.php';
}

// --------------------------------------------------
// Register AJAX Handlers
// --------------------------------------------------

// Ensure AJAX handlers are registered early
add_action( 'plugins_loaded', function() {
    add_action( 'wp_ajax_ar_process_user_image', 'ar_process_user_image_callback' );
    add_action( 'wp_ajax_nopriv_ar_process_user_image', 'ar_process_user_image_callback' );
    
    // Test AJAX handler to verify AJAX is working
    add_action( 'wp_ajax_ar_test_ajax', 'ar_test_ajax_callback' );
    add_action( 'wp_ajax_nopriv_ar_test_ajax', 'ar_test_ajax_callback' );
    
    // Handler for getting fresh nonces
    add_action( 'wp_ajax_ar_get_fresh_nonce', 'ar_get_fresh_nonce_callback' );
    add_action( 'wp_ajax_nopriv_ar_get_fresh_nonce', 'ar_get_fresh_nonce_callback' );
}, 1 );

function ar_test_ajax_callback() {
    error_log('AR Test AJAX: Handler called successfully');
    wp_send_json_success(array(
        'message' => 'AJAX is working!',
        'timestamp' => current_time('mysql'),
        'nonce' => wp_create_nonce('ar_test_ajax')
    ));
}

if (!function_exists('ar_get_fresh_nonce_callback')) {
    function ar_get_fresh_nonce_callback() {
        
        wp_send_json_success(array(
            'nonce' => wp_create_nonce('ar_process_user_image'),
            'timestamp' => current_time('mysql')
        ));
    }
}



if (!function_exists('ar_process_user_image_callback')) {
    function ar_process_user_image_callback() {
    // Add debugging
    
    
    // Check if this is actually an AJAX request
    if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || $_SERVER['HTTP_X_REQUESTED_WITH'] !== 'XMLHttpRequest') {

        wp_send_json_error('Invalid request type - AJAX required');
        return;
    }
    
    // Verify nonce
    if (!wp_verify_nonce($_POST['_wpnonce'], 'ar_process_user_image')) {

        wp_send_json_error('Security check failed');
        return;
    }

    // Get image data
    $image_data = $_POST['image_data'];
    $width = isset($_POST['width']) ? intval($_POST['width']) : 300;
    $height = isset($_POST['height']) ? intval($_POST['height']) : 144;
    $framed = isset($_POST['framed']) ? sanitize_text_field($_POST['framed']) : '0';
    $frame_color = isset($_POST['frame_color']) ? sanitize_text_field($_POST['frame_color']) : '000000';
    $opacity = isset($_POST['opacity']) ? floatval($_POST['opacity']) : 1.0;
    
    // Log server configuration
    

    // Validate data URL format
    if (strpos($image_data, 'data:image/') !== 0) {
        wp_send_json_error('Invalid image data format');
        return;
    }

    // Extract base64 data
    $base64_data = substr($image_data, strpos($image_data, ',') + 1);
    $image_binary = base64_decode($base64_data);

    if (!$image_binary) {
        wp_send_json_error('Failed to decode image data');
        return;
    }

    // Create temporary file
    $upload_dir = wp_upload_dir();
    $temp_filename = 'ar_user_upload_' . uniqid() . '.jpg';
    $temp_filepath = $upload_dir['basedir'] . '/ar_temp/' . $temp_filename;

    // Ensure temp directory exists
    if (!file_exists($upload_dir['basedir'] . '/ar_temp/')) {
        wp_mkdir_p($upload_dir['basedir'] . '/ar_temp/');
    }

    // Write temporary file
    if (file_put_contents($temp_filepath, $image_binary) === false) {
        wp_send_json_error('Failed to create temporary file');
        return;
    }

    // Calculate aspect ratio from image dimensions (always width/height for consistency)
    $raw_ratio = $width / $height;
    $aspect_ratio = round($raw_ratio, 2);
    
    // Determine orientation
    $orientation = 'l'; // default to landscape
    if ($width < $height) {
        $orientation = 'p'; // portrait
        // For portrait images, invert the ratio to match available models
        $aspect_ratio = round($height / $width, 2);
    } elseif ($width == $height) {
        $orientation = 'square'; // square
    }
    
    // Find the closest available ratio
    $json_file_fs = plugin_dir_path(__FILE__) . 'assets/models/models.json';
    if (file_exists($json_file_fs)) {
        $json_data = file_get_contents($json_file_fs);
        $data_array = json_decode($json_data, true);
        
        if ($data_array !== null && json_last_error() === JSON_ERROR_NONE) {
            $available_ratios = array_keys($data_array);
            
            $aspect_ratio_string = (string) $aspect_ratio;
            if (!isset($data_array[$aspect_ratio_string])) {
                $closest_ratio = ar_findClosestRatio($aspect_ratio, $available_ratios);
                $aspect_ratio = $closest_ratio ?: '1.0'; // fallback to 1.0 if no closest found
            }
        } else {
            $aspect_ratio = '1.0'; // fallback
        }
    } else {
        $aspect_ratio = '1.0'; // fallback
    }
    
    // Convert ratio to numeric value for form fields
    $ratio_numeric = '1.5'; // Default to 2:3
    if ($aspect_ratio === '1.0') {
        $ratio_numeric = '1.0';
    } elseif ($aspect_ratio === '1.4142') {
        $ratio_numeric = '1.4142'; // A4
    } elseif ($aspect_ratio === '1.5') {
        $ratio_numeric = '1.5'; // 2:3
    } elseif ($aspect_ratio === '1.25') {
        $ratio_numeric = '1.25'; // 4:5
    } elseif ($aspect_ratio === '1.33') {
        $ratio_numeric = '1.33'; // 3:4
    } elseif ($aspect_ratio === '3.1') {
        $ratio_numeric = '3.1'; // 3:1
    }

    // Process through ar-gallery.php
    $gallery_url = site_url('/wp-content/plugins/ar-for-wordpress/includes/ar-gallery.php');
    $model_url = $gallery_url . '?url=' . urlencode($upload_dir['baseurl'] . '/ar_temp/' . $temp_filename) . 
                 '&width=' . $width . '&height=' . $height . 
                 '&ratio=' . $aspect_ratio . '&o=' . $orientation .
                 '&f=' . $framed . '&fc=' . $frame_color . '&opacity=' . $opacity . 
                 '&_wpnonce=' . wp_create_nonce('ar_secure_nonce');

    // Clean up temporary file after a delay
    wp_schedule_single_event(time() + 300, 'ar_cleanup_temp_file', $temp_filepath);

    wp_send_json_success(array(
        'gallery_url' => $model_url,
        'calculated_ratio' => $aspect_ratio,
        'ratio_numeric' => $ratio_numeric,
        'orientation' => $orientation,
        'message' => 'Image processed successfully'
    ));
    }
}

// Cleanup function for temporary files
add_action('ar_cleanup_temp_file', 'ar_cleanup_temp_file_callback');
if (!function_exists('ar_cleanup_temp_file_callback')) {
    function ar_cleanup_temp_file_callback($filepath) {
        // Ensure we have a valid string filepath
        if (is_string($filepath) && !empty($filepath) && file_exists($filepath)) {
            unlink($filepath);
        }
    }
}

// --------------------------------------------------
// Setup Shortcode Examples (on init)
// --------------------------------------------------

add_action( 'init', 'ar_for_wordpress_setup_shortcodes_help_text', 15 );
function ar_for_wordpress_setup_shortcodes_help_text() {
    global $shortcode_examples_wc, $shortcode_examples, $ar_rate_this_plugin, $ar_wcfm;

    if ( ! isset( $ar_wcfm ) ) {
        $shortcode_examples_wc = '<b>[ar-display]</b> - ' . esc_html__( 'Place on the Woocommerce product page to display the 3D model for the product id and includes all variations.', 'ar-for-wordpress' ) . '<br>';

        $shortcode_examples = '
            <b>[ar-display id=X]</b> - ' . esc_html__( 'Displays the 3D model for a given model/post id.', 'ar-for-wordpress' ) . '<br>
            <b>[ar-display id=\'X,Y,Z\']</b> - ' . esc_html__( 'Displays the 3D models for multiple comma separated model/post ids.', 'ar-for-wordpress' ) . '<br>
            <b>[ar-display cat=X]</b> - ' . esc_html__( 'Displays the 3D models for a given category.', 'ar-for-wordpress' ) . '<br>
            <b>[ar-display cat=\'X,Y,Z\']</b> - ' . esc_html__( 'Displays the 3D models for multiple categories.', 'ar-for-wordpress' ) . '<br>
            <b>[ar-gallery]</b> - ' . esc_html__( 'Displays the 3D Gallery Model.', 'ar-for-wordpress' ) . '<br>
            <b>[ar-user-upload]</b> - ' . esc_html__( 'Displays a drag and drop model uploader for users to upload their own artwork images.', 'ar-for-wordpress' ) . '<br>
            <b>[ar-view id=X text=true (OR) buttons=true]</b> - ' . esc_html__( 'Display AR View button or text link.', 'ar-for-wordpress' ) . '<br>
            <b>[ar-qr]</b> - ' . esc_html__( 'QR Code shortcode.', 'ar-for-wordpress' ) . '<br>';

        $ar_rate_this_plugin = '<h3 style="margin-top:0px">' . esc_html__( 'Rate This Plugin', 'ar-for-wordpress' ) . '</h3>
            <img src="' . esc_url( plugins_url( "assets/images/5-stars.png", __FILE__ ) ) . '" style="height:30px"><br>
            ' . esc_html__( 'We really hope you like using AR For WordPress and would be very grateful if you could leave a rating.', 'ar-for-wordpress' ) . '<br>
            <button 
                id="open-ar-reviews" 
                class="ar_model_shop_btn button" 
                onclick="window.open(\'https://wordpress.org/support/plugin/ar-for-wordpress/reviews/\', \'_blank\')">
                '.esc_html(__('Leave a Rating', 'ar-for-wordpress')).' <sup>&#x2197;</sup>
        </button>';
    }
}

// --------------------------------------------------
// Run Main Plugin (on init)
// --------------------------------------------------

add_action( 'init', 'ar_for_wordpress_run_plugin', 20 );
function ar_for_wordpress_run_plugin() {
    $plugin = new AR_Plugin();
    $plugin->run();
}

// --------------------------------------------------
// Admin Menu and Customizations
// --------------------------------------------------

add_action( 'admin_menu', 'ar_for_wordpress_admin_menus' );
function ar_for_wordpress_admin_menus() {
    add_submenu_page( 'edit.php?post_type=armodels', __( 'Settings', 'ar-for-wordpress' ), __( 'Settings', 'ar-for-wordpress' ), 'manage_options', '', 'ar_subscription_setting' );
    add_submenu_page( 'edit.php?post_type=armodels', __( 'Whats New', 'ar-for-wordpress' ), __( 'Whats New', 'ar-for-wordpress' ), 'manage_options', 'ar-whats-new', 'ar_whats_new' );
    add_submenu_page( 'edit.php?post_type=armodels', __( 'AI Credits', 'ar-for-wordpress' ), __( 'AI Credits', 'ar-for-wordpress' ), 'manage_options', 'ar-ai-credits', 'ar_ai_credits_page' );
}

add_action( 'admin_menu', function() {
    remove_menu_page( 'ar-analytics' );
}, 100 );

add_action( 'admin_menu', function() {
    global $submenu;

    $parent_slug = 'edit.php?post_type=armodels';

    if ( empty( $submenu[ $parent_slug ] ) ) {
        return;
    }


    $found = false;

    foreach ( $submenu[ $parent_slug ] as $index => $item ) {
        $slug = isset( $item[2] ) ? $item[2] : '';

        if ( 'ar-analytics' === $slug ) {
            if ( $found ) {
                unset( $submenu[ $parent_slug ][ $index ] );
            } else {
                $found = true;
            }
        }
    }

    $submenu[ $parent_slug ] = array_values( $submenu[ $parent_slug ] );
}, 110 );

add_action( 'admin_head', function() {
    ?>
    <style>
        #menu-posts-armodels .wp-submenu li a[href$="page=ar-analytics"] {
            display: block;
        }
    </style>
    <?php
} );

add_action( 'admin_footer', function() {
    ?>
    <script>
        ( function() {
            var links = document.querySelectorAll('#menu-posts-armodels .wp-submenu li a[href$="page=ar-analytics"]');
            if (links.length > 1) {
                for (var i = 0; i < links.length - 1; i++) {
                    if (links[i] && links[i].parentElement) {
                        links[i].parentElement.style.display = 'none';
                    }
                }
            }
        }() );
    </script>
    <?php
} );

add_action( 'admin_head', 'ar_for_wordpress_customize_meta_box' );
function ar_for_wordpress_customize_meta_box() {
    remove_meta_box( 'postimagediv', 'armodels', 'side' );
    add_meta_box( 'postimagediv', __( 'AR Poster Image', 'ar-for-wordpress' ), 'post_thumbnail_meta_box', 'armodels', 'side', 'low' );
}

// --------------------------------------------------
// Manage Custom Columns
// --------------------------------------------------

add_filter( 'manage_armodels_posts_columns', 'ar_for_wordpress_custom_columns' );
function ar_for_wordpress_custom_columns( $columns ) {
    unset( $columns['date'], $columns['pro-image'] );

    $columns['Shortcode'] = __( 'Shortcode', 'ar-for-wordpress' );
    $columns['date'] = __( 'Date', 'ar-for-wordpress' );

    return $columns;
}

// Add action hook to populate the Shortcode column content
add_action( 'manage_armodels_posts_custom_column', 'ar_for_wordpress_custom_column_content', 10, 2 );
function ar_for_wordpress_custom_column_content( $column, $post_id ) {
    if ( $column === 'Shortcode' ) {
        $shortcode = '[ar-display id=' . esc_html( $post_id ) . ']';
        echo '<span class="ar-shortcode-copy" style="cursor: pointer; color: #0073aa;" onclick="arCopyShortcodeToClipboard(\'' . esc_js( $shortcode ) . '\', this)">' . esc_html( $shortcode ) . '</span>';
        
        // Check if model exists and show thumb icon
        $model_file = get_post_meta( $post_id, '_ar_model_file', true );
        if ( $model_file ) {
            $ARimgSrc = esc_url( plugins_url( "assets/images/chair.png", __FILE__ ) );
            echo '<br><div class="ar_tooltip" style="margin-top: 5px;"><img src="' . $ARimgSrc . '" width="15"><span class="ar_tooltip_text">' . __( 'AR Model', 'ar-for-wordpress' ) . '</span></div>';
        }
    }
}

// Add JavaScript for copy functionality
add_action( 'admin_footer', 'ar_for_wordpress_admin_footer_scripts' );
function ar_for_wordpress_admin_footer_scripts() {
    if ( get_current_screen()->post_type === 'armodels' ) {
        ?>
        <script>
        function arCopyShortcodeToClipboard(text, element) {
            // Fallback for older browsers
            if (navigator.clipboard && window.isSecureContext) {
                // Modern clipboard API
                navigator.clipboard.writeText(text).then(function() {
                    arShowCopyFeedback(element);
                }).catch(function(err) {
                    console.error('Could not copy text: ', err);
                    arFallbackCopy(text, element);
                });
            } else {
                // Fallback for older browsers
                arFallbackCopy(text, element);
            }
        }
        
        function arShowCopyFeedback(element) {
            const originalText = element.textContent;
            element.textContent = 'Copied!';
            element.style.color = '#46b450';
            
            setTimeout(function() {
                element.textContent = originalText;
                element.style.color = '#0073aa';
            }, 2000);
        }
        
        function arFallbackCopy(text, element) {
            // Create temporary textarea for older browsers
            const textArea = document.createElement('textarea');
            textArea.value = text;
            textArea.style.position = 'fixed';
            textArea.style.left = '-999999px';
            textArea.style.top = '-999999px';
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();
            
            try {
                document.execCommand('copy');
                arShowCopyFeedback(element);
            } catch (err) {
                console.error('Fallback copy failed: ', err);
            }
            
            document.body.removeChild(textArea);
        }
        </script>
        <?php
    }
}

add_filter( 'post_row_actions', 'ar_for_wordpress_remove_row_actions', 10, 1 );
function ar_for_wordpress_remove_row_actions( $actions ) {
    if ( get_post_type() === 'armodels' ) {
        unset( $actions['view'] );
    }
    return $actions;
}

// --------------------------------------------------
// Plugin Action Links and Meta Links
// --------------------------------------------------

add_filter( 'plugin_action_links_ar-for-wordpress/ar-wordpress.php', 'ar_for_wordpress_action_links' );
function ar_for_wordpress_action_links( $links ) {
    $url = esc_url( add_query_arg( 'post_type', 'armodels', get_admin_url() . 'edit.php' ) );
    $settings_link = "<a href='$url&page'>" . __( 'Settings', 'ar-for-wordpress' ) . '</a>';
    $whatsnew_link = "<a href='$url&page=ar-whats-new'>" . __( 'Whats New', 'ar-for-wordpress' ) . '</a>';
    array_push( $links, $settings_link, $whatsnew_link );
    return $links;
}

add_filter( 'plugin_row_meta', 'ar_for_wordpress_plugin_meta_links', 10, 2 );
function ar_for_wordpress_plugin_meta_links( $links, $file ) {
    if ( plugin_basename( __FILE__ ) === $file ) {
        $documentation_link = '<a href="https://augmentedrealityplugins.com/support/" target="_blank">' . __( 'Documentation', 'ar-for-wordpress' ) . '</a>';
        $links[] = $documentation_link;
    }
    return $links;
}

// --------------------------------------------------
// AI Credits Admin Page
// --------------------------------------------------

function ar_ai_credits_page() {
    if (!current_user_can('manage_options')) return;
    
    // Check if the AI credits system is available
    if (!class_exists('ARDisplay_AI_Proxy_Credits')) {
        echo '<div class="wrap"><h1>' . esc_html__('AI Credits', 'ar-for-wordpress') . '</h1>';
        echo '<div class="notice notice-error"><p>' . esc_html__('AI Credits system not available. Please ensure the AR Display AI plugin is installed and activated.', 'ar-for-wordpress') . '</p></div>';
        echo '<div class="card"><h2>' . esc_html__('What You Need', 'ar-for-wordpress') . '</h2>';
        echo '<p>' . esc_html__('To use the AI Credits system, you need to install and activate the AR Display AI plugin. This plugin provides:', 'ar-for-wordpress') . '</p>';
        echo '<ul><li>' . esc_html__('User credit management', 'ar-for-wordpress') . '</li>';
        echo '<li>' . esc_html__('WooCommerce integration for credit purchases', 'ar-for-wordpress') . '</li>';
        echo '<li>' . esc_html__('AI model generation with credit validation', 'ar-for-wordpress') . '</li>';
        echo '<li>' . esc_html__('Admin tools for managing user credits', 'ar-for-wordpress') . '</li></ul>';
        echo '<p><a href="' . esc_url(admin_url('plugins.php')) . '" class="button button-primary">' . esc_html__('Go to Plugins', 'ar-for-wordpress') . '</a></p>';
        echo '</div>';
        
        echo '<div class="card"><h2>' . esc_html__('Fallback Option', 'ar-for-wordpress') . '</h2>';
        echo '<p>' . esc_html__('If you need to use AI generation without the credits system (for development/testing), you can configure a fallback token:', 'ar-for-wordpress') . '</p>';
        echo '<ol><li>' . esc_html__('Go to your wp-config.php file', 'ar-for-wordpress') . '</li>';
        echo '<li>' . esc_html__('Add this line: define(\'ARDISPLAY_AI_FALLBACK_TOKEN\', \'your-token-here\');', 'ar-for-wordpress') . '</li>';
        echo '<li>' . esc_html__('Replace \'your-token-here\' with a valid AI proxy token', 'ar-for-wordpress') . '</li></ol>';
        echo '<p><strong>' . esc_html__('Note:', 'ar-for-wordpress') . '</strong> ' . esc_html__('This bypasses the credit system and should only be used for development or testing purposes.', 'ar-for-wordpress') . '</p>';
        echo '</div>';
        return;
    }
    
    $credits_manager = new ARDisplay_AI_Proxy_Credits();
    $current_user_id = get_current_user_id();
    $user_credits = $credits_manager->get_or_create_user_credits($current_user_id);
    
    if (!$user_credits) {
        echo '<div class="wrap"><h1>' . esc_html__('AI Credits', 'ar-for-wordpress') . '</h1>';
        echo '<div class="notice notice-error"><p>' . esc_html__('Failed to load user credits. Please try refreshing the page or contact support if the issue persists.', 'ar-for-wordpress') . '</p></div></div>';
        return;
    }
    
    $available_credits = $user_credits->total_credits_purchased - $user_credits->total_credits_spent;
    $credit_cost = intval(get_option('ardisplay_ai_proxy_credit_cost_per_model', 10));
    ?>
    <div class="wrap">
        <h1><?php esc_html_e('AI Credits', 'ar-for-wordpress'); ?></h1>
        
        <?php if (isset($_GET['token_updated']) && $_GET['token_updated'] === '1'): ?>
            <div class="notice notice-success is-dismissible">
                <p><?php esc_html_e('✅ AI Credits Token updated successfully! You can now generate AI models.', 'ar-for-wordpress'); ?></p>
            </div>
        <?php endif; ?>
        
        <?php if (isset($_GET['token_error']) && $_GET['token_error'] === '1'): ?>
            <div class="notice notice-error is-dismissible">
                <p><?php esc_html_e('❌ Failed to update AI Credits Token. Please try again or contact support.', 'ar-for-wordpress'); ?></p>
            </div>
        <?php endif; ?>
        
        <div class="card">
            <h2><?php esc_html_e('Your AI Credits Status', 'ar-for-wordpress'); ?></h2>
            <table class="form-table">
                <tr>
                    <th><?php esc_html_e('AI Credits Token:', 'ar-for-wordpress'); ?></th>
                    <td><code><?php echo esc_html($user_credits->ai_credits_token); ?></code></td>
                </tr>
                <tr>
                    <th><?php esc_html_e('Total Credits Purchased:', 'ar-for-wordpress'); ?></th>
                    <td><?php echo esc_html($user_credits->total_credits_purchased); ?></td>
                </tr>
                <tr>
                    <th><?php esc_html_e('Total Credits Spent:', 'ar-for-wordpress'); ?></th>
                    <td><?php echo esc_html($user_credits->total_credits_spent); ?></td>
                </tr>
                <tr>
                    <th><?php esc_html_e('Available Credits:', 'ar-for-wordpress'); ?></th>
                    <td><strong><?php echo esc_html($available_credits); ?></strong></td>
                </tr>
                <tr>
                    <th><?php esc_html_e('Credit Cost Per Model:', 'ar-for-wordpress'); ?></th>
                    <td><?php echo esc_html($credit_cost); ?></td>
                </tr>
                <tr>
                    <th><?php esc_html_e('Can Generate Models:', 'ar-for-wordpress'); ?></th>
                    <td>
                        <?php if ($available_credits >= $credit_cost): ?>
                            <span style="color: green;">✓ <?php esc_html_e('Yes', 'ar-for-wordpress'); ?></span>
                        <?php else: ?>
                            <span style="color: red;">✗ <?php esc_html_e('No - Insufficient credits', 'ar-for-wordpress'); ?></span>
                        <?php endif; ?>
                    </td>
                </tr>
            </table>
            
            <?php if ($available_credits < $credit_cost): ?>
                <p class="description">
                    <?php esc_html_e('You need more credits to generate AI models. ', 'ar-for-wordpress'); ?>
                    <a href="https://ardisplay.ai/product/ai-model-credits/?return_site=<?php echo urlencode(home_url()); ?>&user_id=<?php echo esc_attr($current_user_id); ?>" target="_blank" class="button button-primary">
                        <?php esc_html_e('Purchase Credits', 'ar-for-wordpress'); ?>
                    </a>
                </p>
            <?php endif; ?>
        </div>
        
        <div class="card">
            <h2><?php esc_html_e('How It Works', 'ar-for-wordpress'); ?></h2>
            <ol>
                <li><?php esc_html_e('Purchase AI credits from our store', 'ar-for-wordpress'); ?></li>
                <li><?php esc_html_e('Each AI model generation costs', 'ar-for-wordpress'); ?> <?php echo esc_html($credit_cost); ?> <?php esc_html_e('credits', 'ar-for-wordpress'); ?></li>
                <li><?php esc_html_e('Your credits are automatically deducted when generating models', 'ar-for-wordpress'); ?></li>
                <li><?php esc_html_e('Track your usage and remaining credits here', 'ar-for-wordpress'); ?></li>
            </ol>
        </div>
    </div>
    <?php
}

// Handle return from AR Display AI with updated token
add_action('init', 'ar_handle_ai_credits_return');
function ar_handle_ai_credits_return() {
    // Check if this is a return from AR Display AI
    if (isset($_GET['return_from']) && $_GET['return_from'] === 'ardisplay_ai' && 
        isset($_GET['ai_token']) && isset($_GET['user_id'])) {
        
        $ai_token = sanitize_text_field($_GET['ai_token']);
        $user_id = intval($_GET['user_id']);
        
        // Verify the current user matches the returned user_id
        if ($user_id !== get_current_user_id()) {
            wp_die('Unauthorized access');
        }
        
        // Update the user's AI credits token in the AR Display AI plugin
        if (class_exists('ARDisplay_AI_Proxy_Credits')) {
            $credits_manager = new ARDisplay_AI_Proxy_Credits();
            $result = $credits_manager->update_user_ai_credits_token($user_id, $ai_token, home_url());
            
            if ($result) {
                // Redirect to AI credits page with success message
                wp_redirect(add_query_arg('token_updated', '1', admin_url('edit.php?post_type=armodels&page=ar-ai-credits')));
                exit;
            } else {
                // Redirect with error message
                wp_redirect(add_query_arg('token_error', '1', admin_url('edit.php?post_type=armodels&page=ar-ai-credits')));
                exit;
            }
        }
    }
}
