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

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

global $ar_plugin_id;

    extract(get_screen_type());

    $ar_model_id = $model_array['model_id'];

    if (strpos($ar_model_id, ',') !== false) {
        $ar_model_id_array = explode(',', $ar_model_id);
        $ar_model_id = str_replace(" ","",implode("_",$ar_model_id_array));
    }

    $instance_id = isset($instance_id) ? $instance_id : ($model_array['instance_id'] ?? wp_unique_id('ar_instance_'));

    //wp_die('HERE - '.$ar_model_id);

    $output_atts = '';
    if (($model_array['ar_prompt']==true)){
       $output_atts .= ' interaction-prompt="none"  ';
    }
    if($model_array['ar_rotate']!=true){
       $output_atts .= ' auto-rotate ';
    }
    if($model_array['ar_poster']!=''){
       $output_poster = $model_array['ar_poster'];
    }else{
        $output_poster = esc_url( get_the_post_thumbnail_url($model_array['model_id']) );
    }
    $output_html = '';
    
    $glb_file = sanitize_text_field($model_array['glb_file']);

    // For gallery-builder (2D artwork) models, default AR placement to floor for maximum Android WebXR
    // compatibility and a visible placement reticle.
    if (strpos($glb_file, 'ar-gallery.php') !== false && empty($model_array['ar_placement'])) {
        $model_array['ar_placement'] = ' ar-placement="floor" ';
    }
    
    $ar_hide_gallery_sizes = get_option('ar_hide_gallery_sizes');

    if (empty($ar_hide_gallery_sizes)) {
        // Parse the URL to get its components
        $url_components = wp_parse_url($glb_file);
        if (isset($url_components['query'])){
            // Extract the query string (the part after the ? in the URL)
            $query_string = $url_components['query'];
            
            // Parse the query string into an associative array
            parse_str($query_string, $query_parts);
            
            if (isset($query_parts['url'])){
                // Now $query_parts will contain the parts of the URL as an associative array
                $url = $query_parts['url']; 
                $ratio = $query_parts['ratio']; 
                $orientation = $query_parts['o']; 
                $framed = isset($query_parts['f']) ? $query_parts['f'] : '';
                $frame_color = isset($query_parts['fc']) ? $query_parts['fc'] : '';
                $wpnonce = esc_html(wp_create_nonce( 'ar_secure_nonce' )); 
                $asset_image = $url;
                $model_array = $this->read_json_and_populate_gallery_selector($model_array, $ratio, $orientation, $framed, $frame_color, $wpnonce, $model_array['id'], $url);
            }
        }
    }
    
    // Handle iOS AR scaling for disable resizing
    $ios_src_url = ar_get_secure_model_url($model_array['usdz_file']);
    $glb_src_url = ar_get_secure_model_url($model_array['glb_file']);

    // Check if disable resizing is enabled (check both original value and processed string)
    $ar_resizing_enabled = false;
    if (isset($model_array['ar_resizing'])) {
        // Check if it's the processed string (contains 'ar-scale="fixed"')
        if (strpos($model_array['ar_resizing'], 'ar-scale="fixed"') !== false) {
            $ar_resizing_enabled = true;
        }
        // Or check if it's the original numeric value
        elseif ($model_array['ar_resizing'] == 1) {
            $ar_resizing_enabled = true;
        }
    }

    if ($ar_resizing_enabled) {
        if (!empty($ios_src_url)) {
            $ios_src_url .= '#allowsContentScaling=0';
        }
        if (!empty($glb_src_url)) {
            $glb_src_url .= '#allowsContentScaling=0';
        }
    }

    // Add canonicalWebPageURL fragment to ios-src if it's set
    if (!empty($ios_src_url)) {
        // Get the product/page URL
        $canonical_url = '';
        if (!empty($model_array['ar_model_atts']['id'])) {
            $canonical_url = get_permalink($model_array['ar_model_atts']['id']);
        } elseif (!empty($model_array['id'])) {
            $canonical_url = get_permalink($model_array['id']);
        } elseif (!empty($ar_model_id)) {
            $canonical_url = get_permalink($ar_model_id);
        }
        
        // If we couldn't get a permalink, use the current page URL
        if (empty($canonical_url)) {
            $canonical_url = get_permalink();
        }
        
        // Add the canonicalWebPageURL fragment
        if (!empty($canonical_url)) {
            $separator = (strpos($ios_src_url, '#') !== false) ? '&' : '#';
            $ios_src_url .= $separator . 'canonicalWebPageURL=' . urlencode($canonical_url);
        }
    }

    $is_gallery_builder = (strpos($glb_file, 'ar-gallery.php') !== false);

    if ($is_gallery_builder) {
        // Match the user-upload model-viewer output: keep attributes minimal.
        $output_atts  = ($model_array['ar_placement'] ?? '') . '
        ios-src="' . $ios_src_url . '"
        src="' . $glb_src_url . '"
        alt="AR Display 3D model"
        class="ardisplay_viewer ar_model_user_upload"
        quick-look-browsers="safari chrome" ';
    } else {
        $output_atts .= $model_array['ar_placement'].' 
        ios-src="'.$ios_src_url.'" 
        src="'.$glb_src_url.'" 
        '. $model_array['skybox_file'].'
        '. $model_array['ar_environment'].'
        '. $model_array['ar_qr_image'].'
        '. $model_array['ar_qr_destination'].'
        '. $model_array['ar_resizing'].'
        '. $model_array['ar_field_of_view'].'
        '. $ar_zoom_in_output.'
        '. $ar_zoom_out_output.'
        '. $model_array['ar_camera_orbit'].'
        '. $model_array['ar_exposure'].'
        '. $model_array['ar_shadow_intensity'].'
        '. $model_array['ar_shadow_softness'].'
        '. $model_array['ar_environment_image'].' 
        '. $model_array['ar_emissive'].' 
        '. $model_array['ar_light_color'].' 
        poster="'.$output_poster.'"
        alt="AR Display 3D model" 
        class="ar-display-model-viewer" 
        quick-look-browsers="safari chrome" 
        '.$model_array['ar_autoplay'];
        if ($model_array['ar_animation_selection'] !=''){
            $output_atts .=' animation-name="'.$model_array['ar_animation_selection'].'" ';
        }
        $output_atts .= $model_array['ar_disable_zoom'];
    }

?>
    <div id="ardisplay_viewer_<?php echo esc_html($ar_model_id); ?>" class="ardisplay_viewer<?php echo esc_html($model_array['ar_pop']).esc_html($model_array['ar_hide_model']); ?>" data-ar-instance="<?php echo esc_attr($instance_id); ?>" data-ar-plugin="<?php echo esc_attr( $ar_plugin_id ); ?>">
        <model-viewer id="model_<?php echo esc_html($ar_model_id); ?>" camera-controls data-ar-instance="<?php echo esc_attr($instance_id); ?>" data-ar-plugin="<?php echo esc_attr( $ar_plugin_id ); ?>" <?php echo wp_kses($hotspot_js_click, ar_allowed_html()).' '.wp_kses($show_ar, ar_allowed_html()). ' '.wp_kses($output_atts, ar_allowed_html()); ?>>
    <?php if ($model_array['ar_animation'] !=''){     
        // Get play button URL with proper fallback handling empty strings
        $play_btn_url = !empty($play_btn) ? $play_btn : (!empty($model_array['play_btn']) ? $model_array['play_btn'] : plugins_url("assets/images/ar-play-btn.png", dirname(__FILE__)));
    ?>
            <div class="ar-animation-btn-container"><button id="animationButton_<?php echo esc_html($ar_model_id); ?>" slot="hotspot-one" data-position="..." data-normal="..." class="ar-button-animation" type="button"><img src="<?php echo esc_url($play_btn_url); ?>" class="ar-button-animation" id="ar-button-animation_<?php echo esc_html($ar_model_id);?>" style="<?php echo esc_html($play_hide); ?>"></button></div>
    <?php
    }
    // Match user-upload AR activation: rely on <model-viewer> internal ar-button handling
    // by rendering ONLY the slot="ar-button" button without data-id/data-alt.
    if ( $is_gallery_builder ) {
        if ($model_array['ar_view_file']==''){
            if ($ar_whitelabel!=true){
                ?>
                <button slot="ar-button" data-plugin="<?php echo esc_attr( $ar_plugin_id ); ?>" class="ar-button ar-button-default <?php echo esc_html($model_array['ar_hide_arview']);?>" id="ar-button_<?php echo esc_html($ar_model_id);?>"><img id="ar-img_<?php echo esc_html($ar_model_id);?>" src="<?php echo esc_url( plugins_url( "assets/images/ar-view-btn.png", dirname(__FILE__) ) );?>" class="ar-button-img"></button>
                <?php
            }
        } else {
            ?>
            <button slot="ar-button" data-plugin="<?php echo esc_attr( $ar_plugin_id ); ?>" class="ar-button <?php echo esc_html($model_array['ar_hide_arview']);?>" id="ar-button_<?php echo esc_html($ar_model_id);?>"><img id="ar-img_<?php echo esc_html($ar_model_id);?>" src="<?php echo esc_url($model_array['ar_view_file']);?>" class="ar-button-img"></button>
            <?php
        }
    } else {
        if ($model_array['ar_view_file']==''){
            if ($ar_whitelabel!=true){
                if($model_array['ar_alternative_id'] && ( ($isMob) OR ($isTab) OR ($isIPhone) OR ($isIPad) OR ($isAndroid) )){
                    ?>
                    <button data-id="<?php echo esc_html($ar_model_id);?>" data-alt="<?php echo esc_html($model_array['ar_alternative_id']);?>" data-plugin="<?php echo esc_attr( $ar_plugin_id ); ?>" class="ar-button ar-button-default <?php echo esc_html($model_array['ar_hide_arview']);?>" id="ar-button_<?php echo esc_html($ar_model_id);?>"><img id="ar-img_<?php echo esc_html($ar_model_id);?>" src="<?php echo esc_url( plugins_url( "assets/images/ar-view-btn.png", dirname(__FILE__) ) );?>" class="ar-button-img"></button>

                    <button slot="ar-button" data-id="<?php echo esc_html($ar_model_id);?>" data-alt="<?php echo esc_html($model_array['ar_alternative_id']);?>" data-plugin="<?php echo esc_attr( $ar_plugin_id ); ?>" class="ar-button ar-button-default <?php echo esc_html($model_array['ar_hide_arview']);?>" id="ar-button_<?php echo esc_html($ar_model_id);?>"><img id="ar-img_<?php echo esc_html($ar_model_id);?>" src="<?php echo esc_url( plugins_url( "assets/images/ar-view-btn.png", dirname(__FILE__) ) );?>" class="ar-button-img"></button>
                <?php
                } else {
                ?>
                    <button slot="ar-button" data-id="<?php echo esc_html($ar_model_id);?>" data-plugin="<?php echo esc_attr( $ar_plugin_id ); ?>" class="ar-button ar-button-default <?php echo esc_html($model_array['ar_hide_arview']);?>" id="ar-button_<?php echo esc_html($ar_model_id);?>"><img id="ar-img_<?php echo esc_html($ar_model_id);?>" src="<?php echo esc_url( plugins_url( "assets/images/ar-view-btn.png", dirname(__FILE__) ) );?>" class="ar-button-img"></button>
                <?php
                }
            }
        }else{
            if($model_array['ar_alternative_id'] && ( ($isMob) OR ($isTab) OR ($isIPhone) OR ($isIPad) OR ($isAndroid) )){
                ?>
                <button data-id="<?php echo esc_html($ar_model_id);?>" data-alt="<?php echo esc_html($model_array['ar_alternative_id']);?>" data-plugin="<?php echo esc_attr( $ar_plugin_id ); ?>" class="ar-button <?php echo esc_html($model_array['ar_hide_arview']);?>" id="ar-button_<?php echo esc_html($ar_model_id);?><?php echo esc_html($ar_model_id);?>"><img id="ar-img_<?php echo esc_html($ar_model_id);?>" src="<?php echo esc_url($model_array['ar_view_file']);?>" class="ar-button-img"></button>

                <button slot="ar-button" style="display:none;" data-id="<?php echo esc_html($ar_model_id);?>" data-plugin="<?php echo esc_attr( $ar_plugin_id ); ?>" class="ar-button <?php echo esc_html($model_array['ar_hide_arview']);?>" id="ar-button_<?php echo esc_html($ar_model_id);?>"><img id="ar-img_<?php echo esc_html($ar_model_id);?>" src="<?php echo esc_url($model_array['ar_view_file']);?>" class="ar-button-img"></button>
            <?php
            } else {
            ?>
                <button slot="ar-button" data-id="<?php echo esc_html($ar_model_id);?>" data-plugin="<?php echo esc_attr( $ar_plugin_id ); ?>" class="ar-button <?php echo esc_html($model_array['ar_hide_arview']);?>" id="ar-button_<?php echo esc_html($ar_model_id);?>"><img id="ar-img_<?php echo esc_html($ar_model_id);?>" src="<?php echo esc_url($model_array['ar_view_file']);?>" class="ar-button-img"></button>
            <?php
            }
        }    
    }

    
    if (!isset($model_array['ar_hide_fullscreen'])){
        $model_array['ar_hide_fullscreen'] ='';
    }
    //CTA Button
    if (($model_array['ar_cta']!='')AND($model_array['ar_cta_url']!='')){
    ?>
        <div class="ar-cta-button-container">
            <center><a href="<?php echo esc_html($model_array['ar_cta_url']);?>"><button slot="ar-cta-button" class="ar_cta_button button" id="ar-cta-button"><?php echo esc_html($model_array['ar_cta']);?></button></a></center>
        </div>
    <?php
    }
    //Hotspots
    if ($model_array['ar_hotspots']!=''){
        foreach ($model_array['ar_hotspots']['annotation'] as $k => $v){
            if ($model_array['ar_hotspots']['link'][$k] !=''){
                $v = '<a href="'.$model_array['ar_hotspots']['link'][$k].'" target="_blank">'.$v.'</a>';
            }
            $output_html.='<button slot="hotspot-'.($k-1).'" class="hotspot" id="hotspot-'.$k.'" data-position="'.$model_array['ar_hotspots']['data-position'][$k].'" data-normal="'.$model_array['ar_hotspots']['data-normal'][$k].'"><div class="annotation">'.$v.'</div></button>';
        }
    }
    if ($model_array['ar_hide_qrcode']==''){
        $ar_qr_display = 'block';
    }else{
        $ar_qr_display = 'none';
    }
    
    if (isset($model_array['ar_gallery_selector'])) {
        $output_html = ''; // Initialize the output HTML string
        $output_html .= '
            <div class="ar_gallery_selector">
                <select id="scale">';
    
        $model_types = explode(',', $model_array['ar_gallery_selector']);
    
        // Iterate through the array and display the values
        for ($i = 0; $i < count($model_types); $i += 2) {
            // Even keys are the value, odd keys are the option's title
            $value = esc_attr($model_types[$i]);         // Even index - escape for attributes
            $title = esc_html($model_types[$i + 1]);     // Odd index - escape for HTML content
    
            // Append the option tag with the correct value and title
            $output_html .= '<option value="' . $value . '">' . $title . '</option>';
        }
    
        $output_html .= '</select>
            </div>';
    }
    
    echo wp_kses($output_html, ar_allowed_html());

    ?>
    <?php
    if (isset($ar_qr_image_data)){
    ?>
        <div class="ar-qrcode-btn-container hide_on_devices">
        <button id="ar-qrcode_<?php echo esc_html($ar_model_id);?>" type="button" class="ar-qrcode hide_on_devices" onclick="this.classList.toggle('ar-qrcode-large');" style="display: <?php echo esc_html($ar_qr_display);?>; background-image: url(<?php echo esc_attr($ar_qr_image_data);?>);"></button>
        </div>
    <?php
    } else {
    ?>
        <div class="ar-qrcode-btn-container hide_on_devices"><div>
    
    <?php
    }

    echo wp_kses($output, ar_allowed_html());


   

    ?>

    </model-viewer>

    <?php 
    $_suffix = $model_array['variation_id'] ? '_var_'.$model_array['variation_id'] : '';
    $_ar_material_states = get_post_meta( $model_array['id'], '_ar_material_states'.$_suffix, true );
    ?>
    <input type="hidden" name="_ar_material_states<?php echo esc_html($_suffix); ?>"  id="_ar_material_states<?php echo esc_html($_suffix); ?>" value="<?php echo esc_html($_ar_material_states); ?>" data-ar-instance="<?php echo esc_attr($instance_id); ?>">


    <?php
    if(!$model_array['ar_pop']) { ?>
        <script> 
        <?php
            // Animation button logic (combined for both buttons)
            if ($model_array['ar_animation'] == true) { ?>
                    jQuery(document).ready(function() {
                        // Function to handle play/pause functionality for both buttons
                        function toggleAnimation(buttonSelector, model, button) {
                            if (model.paused) {
                                // Change the button icon to the play button
                                button.attr('src', '<?php echo esc_url($model_array['play_btn']); ?>');
                                // Play the model
                                model.play();
                                // Enable auto-rotation when the model plays
                                model.setAttribute('auto-rotate', 'true'); // Enable auto-rotation
                                // Ensure rotation-per-second is either not set or reset when playing
                                model.removeAttribute('rotation-per-second'); // Ensure it starts rotating
                                // Enable interaction prompt when playing
                                model.setAttribute('interaction-prompt', 'auto'); // Enable interaction prompt
                            } else {
                                // Change the button icon to the pause button
                                button.attr('src', '<?php echo esc_url($model_array['pause_btn']); ?>');
                                // Pause the model
                                model.pause();
                                // Disable auto-rotation when the model pauses
                                model.removeAttribute('auto-rotate'); // Disable auto-rotation
                                // Stop the model from rotating by setting rotation-per-second to 0
                                model.setAttribute('rotation-per-second', '0'); // Stop rotation when paused
                                // Disable interaction prompt when paused
                                model.removeAttribute('interaction-prompt'); // Disable interaction prompt
                            }
                        }

                        // Button for the main model
                        jQuery('#animationButton_<?php echo esc_html($ar_model_id); ?>').on('click', function() {
                            var model = model_<?php echo esc_html($model_array['model_id']); ?>;
                            var button = jQuery('#ar-button-animation_<?php echo esc_html($ar_model_id); ?>');
                            toggleAnimation(this, model, button);
                        });
            
                        // Button for the pop model
                        jQuery('#animationButton_<?php echo esc_html($ar_model_id); ?>_pop').on('click', function() {
                            var model = model_<?php echo esc_html($model_array['model_id']); ?>_pop;
                            var button = jQuery('#ar-button-animation_<?php echo esc_html($ar_model_id); ?>_pop');
                            toggleAnimation(this, model, button);
                        });
                    });
            <?php } ?>

        
            
            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']);?>',
                    suffix: '<?php echo esc_html($_suffix ?? ''); ?>',
                    ar_dimensions_units: '<?php echo esc_html($model_array['ar_dimensions_units']);?>',
                    ar_hide_fullscreen: <?php echo $model_array['ar_hide_fullscreen'] ? 'true' : '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($ar_model_id);?>',
                    instanceId: '<?php echo esc_js($instance_id); ?>',
                    pluginId: '<?php echo esc_js( $ar_plugin_id ? $ar_plugin_id : 'ar-for-wordpress' ); ?>',
                };
                
                var model_<?php echo esc_html($ar_model_id);?> = ARModelViewer('<?php echo esc_html($ar_model_id);?>',options);
            });

        </script>
    <?php } ?>

    </div>