<?php
/**
 * AR Display
 * https://augmentedrealityplugins.com
**/

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}



/************* AR User Upload output *******************/
if (!function_exists('ar_user_upload_wp')){
    function ar_user_upload_wp($atts) {
        global $ar_plugin_id, $post, $ar_plugin_root_url;
        add_action('wp_enqueue_scripts', 'ar_advance_register_style');
        ar_advance_register_script();
        ar_advance_register_style();
        $output_html ='';
        $output_atts ='';
        $input_field = '';
        $frame_type = '';
        $ar_frame_color = '';
        $ar_frame_opacity = '';
        $ar_user_upload_button_hidden = '';
        $ar_gallery_builder_message = '';
        
        // Sanitize attributes
        $atts = array_map('sanitize_text_field', $atts);
        
        // Handle message attribute
        if (isset($atts['message'])){
            $ar_gallery_builder_message = sanitize_text_field($atts['message']);
        }
        
        // Handle frame attribute
        if (isset($atts['frame'])){
            $frame_type = sanitize_text_field($atts['frame']);
            // Validate frame value
            if (!in_array($frame_type, ['none', 'mounted', 'framed'])) {
                $frame_type = 'none';
            }
        }
        
        // Handle color attribute
        if (isset($atts['color'])){
            $ar_frame_color = sanitize_hex_color($atts['color']);
            // Ensure it's a valid hex color
            if (!$ar_frame_color) {
                $ar_frame_color = '#f8f8f8'; // Default color
            }
        }
        
        // Handle opacity attribute
        if (isset($atts['opacity'])){
            $ar_frame_opacity = floatval($atts['opacity']);
            // Ensure opacity is between 0 and 1
            if ($ar_frame_opacity < 0) $ar_frame_opacity = 0;
            if ($ar_frame_opacity > 1) $ar_frame_opacity = 1;
        }
        
        // Handle ratio attribute
        $ar_ratio = '2:3'; // Default ratio
        if (isset($atts['ratio'])){
            $ratio_value = sanitize_text_field($atts['ratio']);
            $valid_ratios = ['1:1', 'A4', 'A3', 'A2', 'A1', '2:3', '4:5', '3:4', '3:1'];
            if (in_array($ratio_value, $valid_ratios)) {
                $ar_ratio = $ratio_value;
            }
        }
        
        // Handle size attribute
        $ar_size = '2'; // Default size
        if (isset($atts['size'])){
            $size_value = floatval($atts['size']);
            $valid_sizes = [1, 1.5, 2, 2.5];
            if (in_array($size_value, $valid_sizes)) {
                $ar_size = $size_value;
            }
        }
        
        // Handle hide attribute
        $hidden_elements = [];
        if (isset($atts['hide'])){
            $hide_values = explode(',', sanitize_text_field($atts['hide']));
            $hide_values = array_map('trim', $hide_values);
            $valid_hide_options = ['options', 'ratio', 'size', 'frame', 'color', 'opacity', 'all'];
            
            foreach ($hide_values as $hide_value) {
                if (in_array($hide_value, $valid_hide_options)) {
                    $hidden_elements[] = $hide_value;
                }
            }
        }
        
        // Handle disable attribute
        $disabled_elements = [];
        if (isset($atts['disable'])){
            $disable_values = explode(',', sanitize_text_field($atts['disable']));
            $disable_values = array_map('trim', $disable_values);
            $valid_disable_options = ['ratio', 'size', 'frame', 'color', 'opacity'];
            
            foreach ($disable_values as $disable_value) {
                if (in_array($disable_value, $valid_disable_options)) {
                    $disabled_elements[] = $disable_value;
                }
            }
        }
        
        // Define allowed file types and create secure accept attribute
        $allowed_file_types = array('.glb', '.gltf', '.jpg', '.jpeg', '.png', '.webp');
        $accept_attribute = implode(',', $allowed_file_types);
        
        $input_field = '<input type="file" id="ar_upload_model_file" name="ar_upload_model_file" accept="' . esc_attr($accept_attribute) . '" style="display: none;">';
        $ar_user_default = get_option('ar_user_default');
        $ar_user_default_image = get_option('ar_user_default_image');
        $ar_user_button_location = get_option('ar_user_button');
        $gallery_url = site_url('/wp-content/plugins/' . $ar_plugin_id . '/includes/ar-gallery.php?url=');
        $glb_url = $gallery_url.site_url('/wp-content/plugins/' . $ar_plugin_id . '/assets/images/drag-drop-upload.jpg&width=760&height=420&_wpnonce='.esc_html(wp_create_nonce( 'ar_secure_nonce' )));
        if (($ar_user_default=='Custom')AND($ar_user_default_image!='')){
            // Get the user default image URL with width and height
            $user_default_image_width = 760; // Default width if no image
            $user_default_image_height = 420; // Default height if no image
            if ($ar_user_default_image != '') {
                $upload_dir = wp_upload_dir(); // Get the WordPress upload directory
                // Check if $ar_user_default_image is a full URL and belongs to the current site
                $site_url = site_url(); // Get the current site URL
                
                $ar_user_default_image_path ='';
                // Ensure that $ar_user_default_image is a relative path, not a full URL
                if (strpos($ar_user_default_image, $upload_dir['baseurl']) !== false) {
                    // If $ar_user_default_image contains the full URL, remove the base URL
                    $ar_user_default_image_2 = str_replace($upload_dir['baseurl'], '', $ar_user_default_image);
                }elseif (strpos($ar_user_default_image, $site_url) !== false) {
                    // Strip the domain and make the path relative if it matches the site URL
                    $ar_user_default_image_2 = str_replace($site_url, '', $ar_user_default_image);
                    // Ensure there is no leading slash
                    $ar_user_default_image_2 = ltrim($ar_user_default_image, '/');
                }
                // Full path to the image file
                $ar_user_default_image_path = $upload_dir['basedir'] . '/' . $ar_user_default_image_2;
                if (file_exists($ar_user_default_image_path)) {
                    // Get the file extension
                    $file_extension = pathinfo($ar_user_default_image_path, PATHINFO_EXTENSION);
                    
                    // Convert the extension to lowercase for case-insensitive comparison
                    $file_extension = strtolower($file_extension);
                    
                    // Check if the file is one of the allowed types
                    if (in_array($file_extension, ['glb', 'gltf'])) {
                        $glb_url = esc_url($ar_user_default_image);
                    }elseif (in_array($file_extension, ['jpg', 'jpeg', 'png', 'webp'])) {
                        $ar_user_default_image_data = getimagesize($ar_user_default_image_path); // Get image size data
                        if ($ar_user_default_image_data) {
                            $user_default_image_width = intval($ar_user_default_image_data[0]); // Width of the user default image
                            $user_default_image_height = intval($ar_user_default_image_data[1]); // Height of the user default image
                        }
                        $glb_url = $gallery_url.esc_url($ar_user_default_image).'&width='.$user_default_image_width.'&height='.$user_default_image_height.'&_wpnonce='.esc_html(wp_create_nonce( 'ar_secure_nonce' ));
                    }else{
                        // Invalid file type, use default
                        $glb_url = $gallery_url.site_url('/wp-content/plugins/' . $ar_plugin_id . '/assets/images/drag-drop-upload.jpg&width=760&height=420&_wpnonce='.esc_html(wp_create_nonce( 'ar_secure_nonce' )));
                    }
                }
            }
            
        }elseif (($ar_user_default=='Featured Image')AND$featured_image_id = get_post_thumbnail_id(get_the_ID())){
            // Get the featured image ID and its URL with width and height
            $featured_image_id = get_post_thumbnail_id(get_the_ID()); // Get the featured image ID of the current post
            $featured_image = '';
            $featured_image_width = 760; // Default width if no image
            $featured_image_height = 420; // Default height if no image
            
            if ($featured_image_id) {
                $featured_image_data = wp_get_attachment_image_src($featured_image_id, 'full'); // Retrieve the image data
                if ($featured_image_data) {
                    $featured_image = esc_url($featured_image_data[0]); // URL of the featured image
                    $featured_image_width = intval($featured_image_data[1]); // Width of the featured image
                    $featured_image_height = intval($featured_image_data[2]); // Height of the featured image
                }
            }

            $glb_url = $gallery_url.$featured_image.'&width='.$featured_image_width.'&height='.$featured_image_height.'&_wpnonce='.esc_html(wp_create_nonce( 'ar_secure_nonce' ));
        }else{
            $glb_url = $gallery_url.site_url('/wp-content/plugins/' . $ar_plugin_id . '/assets/images/drag-drop-upload.jpg&width=760&height=420&_wpnonce='.esc_html(wp_create_nonce( 'ar_secure_nonce' )));
        }
        
        // Display the file input and model viewer
        $button_label = wp_kses('Upload Model or Image', ar_allowed_html());
        $ar_upload_label = get_option('ar_user_upload_button');
        if ($ar_upload_label !=''){
            $button_label = get_option('ar_user_upload_button');
        }
        
        if ($ar_user_button_location=='Hidden'){
            $ar_user_upload_button_hidden =' style="display: none;"';
        }
            
        

        if ($atts == 'input'){
            return $input_field; 
        }

        $model_array['model_id'] = 'user_upload';

        /******** AR Model Gallery Builder ************/
        ob_start();
        // Pass the attributes to the gallery builder form
        $gallery_args = array_merge($model_array, array(
            'ar_ratio' => $ar_ratio,
            'ar_size' => $ar_size,
            'ar_frame_type' => $frame_type,
            'ar_frame_color' => $ar_frame_color,
            'ar_frame_opacity' => $ar_frame_opacity,
            'ar_hidden_elements' => $hidden_elements,
            'ar_disabled_elements' => $disabled_elements
        ));
        ar_gallery_builder_form($gallery_args);
        $ar_options_output = ob_get_clean();
        
        // Map frame type text to numeric values for the URL and form fields
        $frame_numeric = '0'; // Default to none
        if ($frame_type === 'mounted') {
            $frame_numeric = '1';
        } elseif ($frame_type === 'framed') {
            $frame_numeric = '2';
        }
        
        // Map ratio text to numeric values for form fields
        $ratio_numeric = '1.5'; // Default to 2:3
        if ($ar_ratio === '1:1') {
            $ratio_numeric = '1.0';
        } elseif ($ar_ratio === 'A4') {
            $ratio_numeric = '1.4142';
        } elseif ($ar_ratio === '2:3') {
            $ratio_numeric = '1.5';
        } elseif ($ar_ratio === '4:5') {
            $ratio_numeric = '1.25';
        } elseif ($ar_ratio === '3:4') {
            $ratio_numeric = '1.33';
        } elseif ($ar_ratio === '3:1') {
            $ratio_numeric = '3.1';
        }
        
        //Assign framed, frame color and opacity to glb_url if they are set in shortcode
        $glb_url .= '&f='.$frame_numeric.'&fc='.str_replace('#','',$ar_frame_color).'&opacity='.$ar_frame_opacity;
        
        $settings_fields = array('ar_view_file', 'ar_scene_viewer', 'ar_qr_file', 'ar_qr_destination', 'ar_dimensions_units', 'ar_dimensions_label', 'ar_fullscreen_file', 'ar_dimensions_inches', 'ar_hide_dimensions', 'ar_hide_arview', 'ar_hide_qrcode', 'ar_hide_reset', 'ar_hide_fullscreen','ar_hide_gallery_sizes','ar_css','ar_css_positions','ar_camera_orbit', 'ar_x', 'ar_y', 'ar_z'.'ar_variants','ar_pop');
        foreach ($settings_fields as $k => $v){
            if (!isset($_POST[$v])){$_POST[$v]='';}
            $model_array[$v] = get_option($v);
        }

        $model_array['ar_camera_orbit_reset'] = '';
        if ($model_array['ar_camera_orbit']!=''){
            $model_array['ar_camera_orbit_reset'] = $model_array['ar_camera_orbit'];
            $model_array['ar_camera_orbit'] = 'camera-orbit="'.$model_array['ar_camera_orbit'].'"';                
        } 

        
        $viewers = ($model_array['ar_scene_viewer'] == 1) ? 'scene-viewer webxr quick-look' : 'webxr scene-viewer quick-look';
        //$viewers = 'webxr scene-viewer quick-look';
        $model_array['ar_hide_arview'] = ($model_array['ar_hide_arview'] != '') ? ' nodisplay' : '';
        $show_ar = ($model_array['ar_hide_arview'] != '') ? '' : ' ar ar-modes="'.$viewers.'" ';
        
        // Force hide dimensions for user upload
        $ar_dimensions_display = ' nodisplay';

        $output_html.='<button slot="ar-button" data-id="'.$model_array['model_id'].'" data-plugin="'.esc_attr( $ar_plugin_id ).'" class="ar-button ar-button-default " id="ar-button_'.$model_array['model_id'].'"><img id="ar-img_'.$model_array['model_id'].'" src="'.esc_url( $ar_plugin_root_url. "assets/images/ar-view-btn.png" ).'" class="ar-button-img"></button>';

        $output_html .= '<div class="ar-reset-btn-container">
            <button id="ar-reset_'.$model_array['model_id'].'" class="ar-reset" onclick="document.getElementById(\'model_'.$model_array['model_id'].'\').setAttribute(\'camera-orbit\', \''.$model_array['ar_camera_orbit_reset'].'\');return getData()"><img src="'.esc_url( plugins_url( "assets/images/reset.png", dirname(__FILE__) ) ).'"></button>
            </div>';

        $output_html.='<input type="hidden" id="src_'.$model_array['model_id'].'" value="'. ar_get_secure_model_url($glb_url).'">';

        $output_html.= $atts['hotspots_html'];
        
        // Add QR code if available
        if (!empty($atts['qrcode_html']) && $atts['qrcode_html'] !== 'data:image/png;base64,') {
            $output_html .= '<div class="ar-qrcode-btn-container hide_on_devices">
                <button id="ar-qrcode_user_upload" type="button" class="ar-qrcode hide_on_devices" onclick="this.classList.toggle(\'ar-qrcode-large\');" style="background-image: url(' . $atts['qrcode_html'] . ');"></button>
            </div>';
        } else {
            // Fallback: Show QR code with current page URL for local testing
            $current_url = get_permalink(get_the_ID());
            $fallback_qr_url = 'https://quickchart.io/qr?text=' . urlencode($current_url) . '&size=200';
            $output_html .= '<div class="ar-qrcode-btn-container hide_on_devices">
                <button id="ar-qrcode_user_upload" type="button" class="ar-qrcode hide_on_devices" onclick="this.classList.toggle(\'ar-qrcode-large\');" style="background-image: url(' . $fallback_qr_url . ');"></button>
            </div>';
        }

        if ($model_array['ar_view_file'] == ''){
            $output_html .= '<button slot="ar-button" data-plugin="'.esc_attr( $ar_plugin_id ).'" class="ar-button ar-button-default '.$model_array['ar_hide_arview'].'" id="ar-button_user_upload"><img id="ar-img_user_upload" src="'.esc_url($ar_plugin_root_url.("/assets/images/ar-view-btn.png")).'" class="ar-button-img"></button>';
        } else {
            $output_html .= '<button slot="ar-button" data-plugin="'.esc_attr( $ar_plugin_id ).'" class="ar-button '.$model_array['ar_hide_arview'].'" id="ar-button_user_upload"><img id="ar-img_user_upload" src="'.esc_url($model_array['ar_view_file']).'" class="ar-button-img"></button>';
        }

        /*
        $output_html.='<div class="ar-popup-btn-container">';
        
        //Fullscreen option - if not disabled in settings
        $ar_hide_fullscreen='';
        if ((!isset($model_array['ar_hide_fullscreen']))OR($model_array['ar_hide_fullscreen']=='')){
            if ($model_array['ar_pop']=='pop'){
                                
                $output.='<button id="ar_close_'.$model_array['id'].'" class="ar_popup-btn '.$ar_show_close_on_devices.'" onclick="document.getElementById(\'ar_popup_'.$mdl_id.'\').style.display = \'none\';"><img src="'.esc_url( plugins_url( "assets/images/close.png", dirname(__FILE__) ) ).'" class="ar-fullscreen_btn-img"></button>';
            }else{
                if ($model_array['ar_fullscreen_file']!=''){
                    $ar_fullscreen_image = $model_array['ar_fullscreen_file'];
                }else{
                    $ar_fullscreen_image = esc_url( plugins_url( "assets/images/fullscreen.png", dirname(__FILE__) ) );
                }
                
                $output.='<button id="ar_pop_Btn_'.$model_array['model_id'].'" class="ar_popup-btn hide_on_devices" type="button"><img src="'.$ar_fullscreen_image.'" class="ar-fullscreen_btn-img"></button>';
            }
        }
        $output.='</div>';
        */

        load_model_viewer_js();

        $model_viewer = '
        <div class="ardisplay_viewer"><model-viewer id="model_user_upload" camera-controls '.$show_ar.' src="'.ar_get_secure_model_url($glb_url).'" alt="AR Display 3D model" class="ardisplay_viewer ar_model_user_upload" quick-look-browsers="safari chrome" '.$output_atts.' >'.$output_html.'</model-viewer></div>';
        $model_viewer .= '
        <input type="hidden" name="_ar_x" id="_ar_x" value="" />
        <input type="hidden" name="_ar_y" id="_ar_y" value="" />
        <input type="hidden" name="_ar_asset_ratio" id="_ar_asset_ratio" value="' . esc_attr($ratio_numeric) . '" />
        <input type="hidden" name="_ar_asset_size" id="_ar_asset_size" value="' . esc_attr($ar_size) . '" />
                <script>
        // Make ajaxurl available for AJAX calls
        var ajaxurl = \'' . admin_url("admin-ajax.php") . '\';
        </script>
        <script>
        jQuery(document).ready(function(){  
                var modelFieldOptions = {                                                   
                    glb_thumb: \''. esc_url( plugins_url( "assets/images/ar_model_icon_tick.jpg", __FILE__ ) ).'\',
                    site_url: \''. esc_url(get_site_url()).'\',
                    js_alert: \''. esc_html(__('Invalid file type. Please choose a USDZ, REALITY, GLB or GLTF.', 'ar-for-wordpress' )).'\',
                    uploader_title: \''. esc_html(__('Choose your AR Files', 'ar-for-wordpress' )).'\',
                    public: \'y\',
                };
                
                var options = {                                                   
                    ar_x: \'\',
                    ar_y: \'\',
                    ar_z: \'\',
                    ar_pop: \''.esc_html($model_array['ar_pop']).'\',
                    ar_dimensions_units: \''.esc_html($model_array['ar_dimensions_units']).'\',
                    ar_hide_fullscreen: \'false\',
                    ar_model_list: \'1\',
                    ar_variants: \'\',
                    id: \''.esc_html($model_array['model_id']).'\',
                    pluginId: \''.esc_js( $ar_plugin_id ? $ar_plugin_id : 'ar-for-wordpress' ).'\',
                };
                
                // Function to wait for ARModelFields to be available
                function waitForARModelFields() {
                    if (typeof ARModelFields === \'function\') {
                        var modelFields_'.esc_html($model_array['model_id']).' = new ARModelFields(\''.esc_html($model_array['model_id']).'\',modelFieldOptions);
                    } else {
                        console.log(\'Waiting for ARModelFields...\');
                        setTimeout(waitForARModelFields, 100);
                    }
                }
                
                // Delay ARModelViewer and ARModelFields initialization to ensure scripts are loaded
                setTimeout(function() {
                    // Wait for ARModelFields
                    waitForARModelFields();
                    
                    // Only initialize ARModelViewer if the element exists and the function is available
                    if (document.getElementById(\'model_user_upload\') && typeof ARModelViewer === \'function\') {
                        try {
                            var model_'.esc_html($model_array['model_id']).' = ARModelViewer(\'user_upload\',options);
                        } catch (e) {
                            console.error(\'ARModelViewer initialization failed:\', e);
                        }
                    }
                }, 500); // Increased delay to ensure DOM is fully ready

            });
         
            jQuery(document).ready(function($) {
                // When the custom button with ID #ar_user_upload_button is clicked
                $("#asset_thumb_img").on("click", function() {                    
                    // Trigger the click event on the hidden file input
                    $("#ar_upload_model_file").click();
                });

                // Handle file input change
                $("#ar_upload_model_file").on("change", function(e) {
                    handleFileUpload(e.target.files[0]);
                });

                // Add drag-and-drop functionality to the model-viewer element
                $("#model_user_upload").on("dragover", function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    $(this).addClass("dragover");
                });

                $("#model_user_upload").on("dragleave", function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    $(this).removeClass("dragover");
                });

                $("#model_user_upload").on("drop", function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    $(this).removeClass("dragover");

                    var file = e.originalEvent.dataTransfer.files[0];
                    $("#ar_upload_model_file")[0].files = e.originalEvent.dataTransfer.files; // Update input file
                    handleFileUpload(file);
                });

                // Function to handle file upload
                function handleFileUpload(file) {
                    if (file) {
                        var fileType = file.type;
                        if (!fileType) {
                            var fileExtension = file.name.split(".").pop().toLowerCase();
                            if (fileExtension === "glb") {
                                fileType = "model/gltf-binary";
                            } else if (fileExtension === "gltf") {
                                fileType = "model/gltf+json";
                            } else if (fileExtension === "jpg" || fileExtension === "jpeg") {
                                fileType = "image/jpeg";
                            } else if (fileExtension === "png") {
                                fileType = "image/png";
                            } else if (fileExtension === "webp") {
                                fileType = "image/webp";
                            }
                        }

                        if (fileType === "model/gltf-binary" || fileType === "model/gltf+json") {
                            var url = URL.createObjectURL(file);
                            $("#model_user_upload").attr("src", url);
                        } else if (fileType === "image/jpeg" || fileType === "image/png" || fileType === "image/webp") {
                                // Handle image files and calculate dimensions
                            ar_upload_file_dimenions(file, function(width, height, file) {
                                // Convert file to data URL and send to server for processing
                                var reader = new FileReader();
                                reader.onload = function(e) {
                                    var dataUrl = e.target.result;
                                    $("#_asset_texture_file_0").val(dataUrl);
                                    
                                                                        // Initialize variables for frame settings - use shortcode attributes as defaults
                                    var framedValue = \'<?php echo esc_js($frame_numeric); ?>\';
                                    var frameColor = \'<?php echo esc_js(str_replace("#", "", $ar_frame_color)); ?>\';
                                    var frameOpacity = \'<?php echo esc_js($ar_frame_opacity); ?>\';
                                    
                                    // Override with form field values if they exist and are different from defaults
                                    if ($("#_ar_framed").length && $("#_ar_framed").val() !== \'<?php echo esc_js($frame_numeric); ?>\') {
                                        framedValue = $("#_ar_framed").val();
                                    }
                                    
                                    if ($("#_ar_frame_color").length && $("#_ar_frame_color").val() !== \'<?php echo esc_js($ar_frame_color); ?>\') {
                                        frameColor = $("#_ar_frame_color").val();
                                        // Check if frameColor is a valid hex color and remove the # if it exists
                                        if (/^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/.test(frameColor)) {
                                            frameColor = frameColor.replace(/^#/, \'\'); // Remove the # if it exists
                                        } else {
                                            console.log(\'frameColor is not a valid hex color, using shortcode default\');
                                            frameColor = \'<?php echo esc_js(str_replace("#", "", $ar_frame_color)); ?>\';
                                        }
                                    }
                                    
                                    if ($("#_ar_frame_opacity").length && $("#_ar_frame_opacity").val() !== \'<?php echo esc_js($ar_frame_opacity); ?>\') {
                                        frameOpacity = $("#_ar_frame_opacity").val();
                                    }
                                    
                                    console.log(\'Using shortcode attributes - framed:\', framedValue, \'color:\', frameColor, \'opacity:\', frameOpacity);
                                    // Send image data to server for processing through ar-gallery.php
                                    processImageThroughGallery(dataUrl, width, height, framedValue, frameColor, frameOpacity);
                                };
                                reader.readAsDataURL(file);
                            });
                        } else {
                            console.log(\'Unsupported file type.\');
                        }
                    } else {
                        console.log(\'No file selected or file is empty.\');
                    }
                }

                // Function to handle image upload and get dimensions
                function ar_upload_file_dimenions(file, callback) {
                    if (file && file.type.match(\'image.*\')) {
                        var reader = new FileReader();

                        reader.onload = function(event) {
                            var img = new Image();
                            img.src = event.target.result;

                            img.onload = function() {
                                var width = img.width;
                                var height = img.height;

                                callback(width, height, file);
                            };
                            
                            img.onerror = function() {
                                console.log(\'Failed to load the image for dimensions.\');
                            };
                        };

                        reader.onerror = function() {
                            console.log(\'Failed to read the file.\');
                        };

                        reader.readAsDataURL(file);
                    } else {
                        console.log(\'Please select a valid image file.\');
                    }
                }

                // Function to process image through gallery system via AJAX
                function processImageThroughGallery(dataUrl, width, height, framedValue, frameColor, frameOpacity) {
                    // Get a fresh nonce first
                                       $.ajax({
                        url: ajaxurl,
                        type: \'POST\',
                        data: {
                            action: \'ar_get_fresh_nonce\'
                        },
                        success: function(nonceResponse) {
                            if (nonceResponse.success && nonceResponse.data && nonceResponse.data.nonce) {
                                console.log(\'Got fresh nonce for image processing:\', nonceResponse.data.nonce);
                                
                                // Send image data to server via AJAX to process through ar-gallery.php
                                var formData = new FormData();
                                formData.append(\'action\', \'ar_process_user_image\');
                                formData.append(\'image_data\', dataUrl);
                                formData.append(\'width\', width);
                                formData.append(\'height\', height);
                                formData.append(\'framed\', framedValue);
                                formData.append(\'frame_color\', frameColor);
                                formData.append(\'frame_opacity\', frameOpacity);
                                formData.append(\'_wpnonce\', nonceResponse.data.nonce);
                                
                                // Try to use WordPress ajaxurl if available, fallback to constructed URL
                                var ajaxUrl = (typeof ajaxurl !== \'undefined\') ? ajaxurl : \'<?php echo admin_url("admin-ajax.php"); ?>\';
                                
                                console.log(\'AJAX URL:\', ajaxUrl);
                                console.log(\'FormData:\', formData);
                                
                                $.ajax({
                                    url: ajaxUrl,
                                    type: \'POST\',
                                    data: formData,
                                    processData: false,
                                    contentType: false,
                                    headers: {
                                        \'X-Requested-With\': \'XMLHttpRequest\'
                                    },
                                    success: function(response) {
                                        console.log(\'AJAX success response:\', response);
                                        if (response.success && response.data && response.data.gallery_url) {
                                            // Get the calculated ratio and orientation from the response
                                            var calculatedRatio = response.data.calculated_ratio || \'' . esc_js($ratio_numeric) . '\';
                                            var calculatedRatioNumeric = response.data.ratio_numeric || \'' . esc_js($ratio_numeric) . '\';
                                            var calculatedOrientation = response.data.orientation || \'l\';
                                            
                                            console.log(\'Using calculated ratio:\', calculatedRatio, \'numeric:\', calculatedRatioNumeric, \'orientation:\', calculatedOrientation);
                                            
                                            // Update both the model viewer src and the hidden input field
                                            var modelViewer = $("#model_user_upload")[0];
                                            var newUrl = response.data.gallery_url;
                                            
                                            console.log(\'Initial URL from server:\', newUrl);
                                            
                                            $("#src_user_upload").val(newUrl);
                                            $("#ar_asset_size_container").css("display", "block");
                                            
                                            // IMPORTANT: Update the _asset_texture_file_0 field with the processed image URL
                                            // instead of the base64 data, so updateModelViewer can work properly
                                            $("#_asset_texture_file_0").val(newUrl);
                                            
                                            // Update the frame-related fields to match the shortcode attributes
                                            if ($("#_ar_framed").length) {
                                                $("#_ar_framed").val(framedValue);
                                            }
                                            if ($("#_ar_frame_color").length) {
                                                $("#_ar_frame_color").val(\'#\' + frameColor);
                                            }
                                            if ($("#_ar_frame_opacity").length) {
                                                $("#_ar_frame_opacity").val(frameOpacity);
                                            }
                                            
                                            
                                            // DEBUG: Log what we\'re about to set
                                            console.log(\'=== DEBUGGING FORM FIELD UPDATES ===\');
                                            console.log(\'Calculated values - ratio_numeric:\', calculatedRatioNumeric, \'ar_size:\', \'' . $ar_size . '\');
                                            console.log(\'Form field selectors found:\');
                                            console.log(\'#_ar_asset_ratio exists:\', $("#_ar_asset_ratio").length > 0);
                                            console.log(\'#_ar_asset_ratio_select exists:\', $("#_ar_asset_ratio_select").length > 0);
                                            console.log(\'#ar_asset_size exists:\', $("#ar_asset_size").length > 0);
                                            
                                            // Also update the ratio and size fields if they exist
                                            if ($("#_ar_asset_ratio").length) {
                                                var oldRatioValue = $("#_ar_asset_ratio").val();
                                                $("#_ar_asset_ratio").val(calculatedRatioNumeric);
                                                var newRatioValue = $("#_ar_asset_ratio").val();
                                                console.log(\'Set _ar_asset_ratio from\', oldRatioValue, \'to\', newRatioValue);
                                            } else {
                                                console.log(\'WARNING: #_ar_asset_ratio field not found!\');
                                            }
                                            
                                            if ($("#_ar_asset_ratio_select").length) {
                                                var oldRatioSelectValue = $("#_ar_asset_ratio_select").val();
                                                $("#_ar_asset_ratio_select").val(calculatedRatioNumeric);
                                                var newRatioSelectValue = $("#_ar_asset_ratio_select").val();
                                                console.log(\'Set _ar_asset_ratio_select from\', oldRatioSelectValue, \'to\', newRatioSelectValue);
                                                
                                                // Trigger the change event to update size options
                                                $("#_ar_asset_ratio_select").trigger(\'change\');
                                                console.log(\'Triggered change event on _ar_asset_ratio_select\');
                                            } else {
                                                console.log(\'WARNING: #_ar_asset_ratio_select field not found!\');
                                            }
                                            
                                            if ($("#_ar_asset_size").length) {
                                                var oldSizeValue = $("#_ar_asset_size").val();
                                                $("#_ar_asset_size").val(\'' . $ar_size . '\');
                                                var newSizeValue = $("#_ar_asset_size").val();
                                                console.log(\'Set ar_asset_size from\', oldSizeValue, \'to\', newSizeValue);
                                            } else {
                                                console.log(\'WARNING: #ar_asset_size field not found!\');
                                            }
                                            
                                            // Update orientation field if it exists
                                            if ($("#_ar_asset_orientation").length) {
                                                var oldOrientationValue = $("#_ar_asset_orientation").val();
                                                // Convert server orientation format to form format
                                                var formOrientation = (calculatedOrientation === \'p\') ? \'portrait\' : \'landscape\';
                                                $("#_ar_asset_orientation").val(formOrientation);
                                                var newOrientationValue = $("#_ar_asset_orientation").val();
                                                console.log(\'Set _ar_asset_orientation from\', oldOrientationValue, \'to\', newOrientationValue);
                                            } else {
                                                console.log(\'WARNING: #_ar_asset_orientation field not found!\');
                                            }
                                            
                                            // Size options will be updated automatically by the change event trigger above
                                            
                                            // DEBUG: Check values immediately after setting
                                            console.log(\'=== VALUES IMMEDIATELY AFTER SETTING ===\');
                                            if ($("#_ar_asset_ratio").length) {
                                                console.log(\'_ar_asset_ratio current value:\', $("#_ar_asset_ratio").val());
                                            }
                                            if ($("#_ar_asset_ratio_select").length) {
                                                console.log(\'_ar_asset_ratio_select current value:\', $("#_ar_asset_ratio_select").val());
                                            }
                                            if ($("#ar_asset_size").length) {
                                                console.log(\'ar_asset_size current value:\', $("#ar_asset_size").val());
                                            }
                                            
                                            // Perform single consolidated update after all form fields are set
                                            setTimeout(function() {
                                                console.log(\'=== PERFORMING SINGLE MODEL VIEWER UPDATE ===\');
                                                
                                                // Extract image URL from the server response
                                                var imageUrl = newUrl;
                                                if (newUrl.includes(\'ar-gallery.php\') && newUrl.includes(\'url=\')) {
                                                    try {
                                                        var galleryUrlParams = new URLSearchParams(newUrl.split(\'?\')[1] || \'\');
                                                        var extractedImageUrl = galleryUrlParams.get(\'url\');
                                                        if (extractedImageUrl) {
                                                            imageUrl = decodeURIComponent(extractedImageUrl);
                                                        }
                                                    } catch (e) {
                                                        console.log(\'Failed to extract image URL:\', e);
                                                        imageUrl = newUrl; // fallback to original URL
                                                    }
                                                }
                                                
                                                // Get current dimensions from the original response
                                                var urlParams = new URLSearchParams(newUrl.split(\'?\')[1] || \'\');
                                                var width = urlParams.get(\'width\') || \'300\';
                                                var height = urlParams.get(\'height\') || \'144\';
                                                var nonce = urlParams.get(\'_wpnonce\') || \'\';
                                                
                                                // Build the final URL with all correct parameters
                                                var baseUrl = newUrl.split(\'?\')[0];
                                                var finalUrl = baseUrl + \'?url=\' + encodeURIComponent(imageUrl) + 
                                                             \'&width=\' + width + \'&height=\' + height + 
                                                             \'&ratio=\' + calculatedRatio + \'&o=\' + calculatedOrientation +
                                                             \'&f=\' + framedValue + \'&fc=\' + frameColor + \'&opacity=\' + frameOpacity;
                                                             
                                                if (nonce) {
                                                    finalUrl += \'&_wpnonce=\' + nonce;
                                                }
                                                
                                                // Single model viewer update
                                                if (modelViewer && modelViewer.tagName === \'MODEL-VIEWER\') {
                                                    console.log(\'Updating model viewer from:\', modelViewer.src);
                                                    console.log(\'To final URL:\', finalUrl);
                                                    modelViewer.src = finalUrl;
                                                    
                                                    // Also update poster if it exists
                                                    if (modelViewer.poster) {
                                                        modelViewer.poster = finalUrl;
                                                    }
                                                }
                                                
                                                console.log(\'=== MODEL VIEWER UPDATE COMPLETE ===\');
                                            }, 300);
                                            
                                            // Form fields have been updated, model viewer will be updated via timeout above
                                            console.log(\'=== FORM FIELD UPDATES COMPLETE ===\');
                                        } else {
                                            console.error(\'Failed to process image. Response:\', response);
                                            alert(\'Failed to process image. Please try again.\');
                                        }
                                    },
                                    error: function(xhr, status, error) {
                                        console.error(\'AJAX error:\', error);
                                        console.error(\'AJAX status:\', status);
                                        console.error(\'AJAX status code:\', xhr.status);
                                        console.error(\'AJAX response headers:\', xhr.getAllResponseHeaders());
                                        console.error(\'AJAX response text (first 500 chars):\', xhr.responseText.substring(0, 500));
                                        
                                        // Check if it\'s a 400 error (like the direct URL test)
                                        if (xhr.status === 400) {
                                            alert(\'Server returned 400 Bad Request. This might be due to request size or format issues.\');
                                        } else {
                                            alert(\'Failed to process image. Status: \' + xhr.status + \' Error: \' + error);
                                        }
                                    }
                                });
                            } else {
                                console.error(\'Failed to get fresh nonce for image processing:\', nonceResponse);
                                alert(\'Failed to get security token. Please try again.\');
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error(\'Failed to get nonce for image processing:\', error);
                            alert(\'Failed to get security token: \' + error);
                        }
                    });
                } // Added missing closing brace
            });
        </script>';

        //popup

        $popup_output ='
            <div id="ar_popup_'.$model_array['model_id'].'" class="ar_popup">
                <div class="ar_popup-content">
                    '.$model_viewer.'
                </div>
            </div>';

        /*$model_viewer = $model_viewer.$popup_output;

            add_action( 'wp_footer', function( $arg ) use ( $popup_output,$model_array ) {
                echo wp_kses($popup_output, ar_allowed_html());
                ?>
                <script>  
                    jQuery(document).ready(function(){       
                        var options = {                                                   
                            ar_x: <?php echo $model_array['ar_x'] ? esc_html($model_array['ar_x']) : "''";?>,
                            ar_y: <?php echo $model_array['ar_y'] ? esc_html($model_array['ar_y']) : "''";?>,
                            ar_z: <?php echo $model_array['ar_z'] ? esc_html($model_array['ar_z']) : "''";?>,
                            ar_pop: '<?php echo esc_html($model_array['ar_pop']);?>',
                            ar_dimensions_units: '<?php echo esc_html($model_array['ar_dimensions_units']);?>',
                            ar_hide_fullscreen: 'false',
                            ar_model_list: <?php echo count($model_array['ar_model_list']);?>,
                            ar_variants: '<?php echo esc_html($model_array['ar_variants']); ?>',
                            id: <?php echo esc_html($model_array['ar_model_atts']['id']);?>,
                        };
                        
                        var model_<?php echo esc_html($model_array['model_id']);?> = ARModelViewer('<?php echo esc_html($model_array['model_id']);?>',options);
                    });

                </script>
                <?php
            } );
            
        */

        if ($atts == 'modelviewer'){
            return $model_viewer;
        }
        // Handle options and hide attributes
        $final_options_output = $ar_options_output;
        
        // If 'all' is in hidden elements, hide the entire options section
        if (in_array('all', $hidden_elements)) {
            $final_options_output = '';
        } else {
            // Hide specific elements based on hide attribute
            if (in_array('options', $hidden_elements)) {
                $final_options_output = '';
            }
        }
        
        if (isset($atts['options'])){
            if ($atts['options'] == 'top'){
                return $input_field . $final_options_output . $model_viewer;
            }elseif ($atts['options'] == 'bottom'){
                return $input_field . $model_viewer . $final_options_output;
            }elseif ($atts['options'] == 'none'){
                return $input_field . $model_viewer;
            }
        }else{
            return $input_field . $final_options_output . $model_viewer;
        }
    }
}

