<?php
/**
 * Template vars:
 * - $file_url
 * - $atts
 * - $model_id
 */

if (! defined('ABSPATH')) {
    exit;
}

$modelora_settings = get_option('modelora_settings', []);
$modelora_preset = sanitize_key((string) ($atts['preset'] ?? ($modelora_settings['default_preset'] ?? 'studio')));
$modelora_camera_orbit = (string) get_post_meta($model_id, '_modelora_camera_orbit', true);
$modelora_camera_target = (string) get_post_meta($model_id, '_modelora_camera_target', true);

if (
    $modelora_camera_orbit === ''
    || strpos($modelora_camera_orbit, 'Array') !== false
    || strpos($modelora_camera_orbit, 'NaN') !== false
    || strpos($modelora_camera_orbit, 'INF') !== false
    || strlen($modelora_camera_orbit) > 120
) {
    // Auto radius gives stable framing across very large/tiny models.
    $modelora_camera_orbit = '0deg 75deg auto';
}

if (
    $modelora_camera_target === ''
    || strpos($modelora_camera_target, 'Array') !== false
    || strpos($modelora_camera_target, 'NaN') !== false
    || strpos($modelora_camera_target, 'INF') !== false
    || strlen($modelora_camera_target) > 120
) {
    $modelora_camera_target = 'auto auto auto';
}
$modelora_enable_ar = ! empty($atts['ar']);
$modelora_auto_rotate = ! empty($atts['autoplay']);
$modelora_background_raw = strtolower(trim((string) ($atts['background'] ?? '1')));
$modelora_background_enabled = ! in_array($modelora_background_raw, ['0', 'false', 'off', 'no'], true);
$modelora_bg_color = sanitize_hex_color((string) ($atts['bg_color'] ?? ''));
$modelora_bg_image = esc_url_raw((string) ($atts['bg_image'] ?? ''));
$modelora_trace_id = isset($trace_id) ? (string) $trace_id : '';
$modelora_render_source = ! empty($atts['product_id']) ? 'product' : 'shortcode';

wp_enqueue_style('modelora-viewer');
wp_enqueue_script('modelora-model-viewer');
wp_enqueue_script('modelora-viewer');

$modelora_viewer_attrs = [
    'class' => 'modelora-model-viewer',
    'src' => esc_url($file_url),
    'camera-controls' => 'true',
    'camera-orbit' => esc_attr($modelora_camera_orbit),
    'camera-target' => esc_attr($modelora_camera_target),
    'field-of-view' => 'auto',
    'interaction-prompt' => 'none',
    'touch-action' => 'pan-y',
    'shadow-intensity' => '1',
    'exposure' => '1',
    'data-model-id' => (string) $model_id,
    'data-preset' => $modelora_preset,
    'data-ar-enabled' => $modelora_enable_ar ? '1' : '0',
    'data-trace-id' => $modelora_trace_id,
    'data-render-source' => $modelora_render_source,
    'loading' => ! empty($modelora_settings['lazy_load']) ? 'lazy' : 'eager',
    'reveal' => 'auto', // Auto-reveal so it doesn't wait for a click (since we use a CSS skeleton)
];

if (! empty($modelora_settings['auto_lod'])) {
    $modelora_viewer_attrs['camera-controls'] = 'true';
}

if ($modelora_auto_rotate) {
    $modelora_viewer_attrs['auto-rotate'] = 'true';
}

if ($modelora_enable_ar) {
    $modelora_viewer_attrs['ar'] = 'true';
    $modelora_viewer_attrs['ar-modes'] = 'scene-viewer quick-look webxr';
}

$modelora_viewer_attrs = apply_filters('modelora_viewer_attributes', $modelora_viewer_attrs, $model_id, $atts);
$modelora_shell_classes = 'modelora-viewer-shell' . ($modelora_background_enabled ? '' : ' modelora-no-bg');
?>

<div
    class="<?php echo esc_attr($modelora_shell_classes); ?>"
    data-preset="<?php echo esc_attr($modelora_preset); ?>"
    data-bg-color="<?php echo esc_attr((string) $modelora_bg_color); ?>"
    data-bg-image="<?php echo esc_attr((string) $modelora_bg_image); ?>"
>
    <div class="modelora-skeleton" aria-hidden="true"></div>
    <model-viewer
        <?php foreach ($modelora_viewer_attrs as $modelora_key => $modelora_value) : ?>
            <?php
            if (! is_string($modelora_key) || $modelora_key == '') {
                continue;
            }

            if (is_bool($modelora_value)) {
                $modelora_attr_value = $modelora_value ? 'true' : 'false';
            } elseif (is_scalar($modelora_value)) {
                $modelora_attr_value = (string) $modelora_value;
            } elseif (is_object($modelora_value) && method_exists($modelora_value, '__toString')) {
                $modelora_attr_value = (string) $modelora_value;
            } else {
                continue;
            }
            ?>
            <?php echo esc_attr($modelora_key); ?>="<?php echo esc_attr($modelora_attr_value); ?>"
        <?php endforeach; ?>
    >
    </model-viewer>
    
    <div class="modelora-debug-panel" style="display:none; padding:15px; background:#fff1f1; color:#9b1d1d; border-radius:12px; margin-top:20px;">
        <strong>Debug Error Info:</strong>
        <p class="modelora-error-msg"></p>
        <p>Attempted URL: <code><?php echo esc_url($file_url); ?></code></p>
    </div>

    <div class="modelora-toolbar" role="group" aria-label="Model Controls">
        <button type="button" class="modelora-btn" data-modelora-action="reset-view"><?php esc_html_e('Reset', 'modelora-3d-product-viewer'); ?></button>
        <?php if ($modelora_enable_ar) : ?>
            <button type="button" class="modelora-btn" data-modelora-action="ar"><?php esc_html_e('AR', 'modelora-3d-product-viewer'); ?></button>
        <?php endif; ?>
    </div>
</div>

