<?php
declare(strict_types=1);

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

/**
 * Thank You (post-checkout confirmation) element renderer.
 *
 * Phase 1, step 12. Renders the order-received block — a wrapper
 * around the `[instinctor_order_received]` shortcode + a small
 * scoped CSS block that applies the panel's text/icon colors and
 * border radius.
 *
 * Pre-extraction notes:
 *   - Frontend used id prefix `or-`; editor used `prev-or-`. Unified
 *     to `or-` in both (prefix doesn't matter — selectors are scoped
 *     to the id, not a class).
 *   - Frontend wraps with class `impulse-order-received-block` and
 *     emits animation + visibility classes; editor doesn't.
 *     → Preserved frontend behaviour; editor renders the bare wrapper
 *     (entrance animations + visibility classes are frontend-only
 *     elsewhere in the codebase).
 *   - Both register/use the shortcode `instinctor_order_received` and
 *     pass settings via $GLOBALS['impulse_order_received_settings'].
 */
function impulse_element_render_receipt($el, array $settings, string $context): string {
    if (is_object($el)) $el = (array) $el;
    $elId     = preg_replace('/[^A-Za-z0-9_-]/', '', (string) ($el['id'] ?? '0'));
    $isEditor = ($context === 'editor');

    $maxWidth  = intval($settings['section_max_width'] ?? 300);
    $textColor = (string) ($settings['text_color'] ?? '#1d2327');
    $iconColor = (string) ($settings['icon_color'] ?? '#999999');
    $radius    = intval($settings['border_radius'] ?? 8);

    $animAttrs = (!$isEditor && function_exists('impulse_get_animation_attrs'))
        ? impulse_get_animation_attrs($settings)
        : ['class' => '', 'style' => ''];
    $visClass = (!$isEditor && function_exists('impulse_get_visibility_classes'))
        ? impulse_get_visibility_classes($settings)
        : '';

    $orId  = 'or-' . esc_attr((string) $elId);
    $sel   = '#' . $orId;
    $maxS  = $maxWidth > 0 ? 'max-width:' . $maxWidth . 'px;margin:0 auto;' : '';

    $css  = $sel . ' .instinctor-order-received{' . $maxS . 'color:' . esc_attr($textColor) . '}';
    $css .= $sel . ' .instinctor-success-icon{color:' . esc_attr($iconColor) . '}';
    $css .= $sel . ' .instinctor-btn-primary{background:' . esc_attr($textColor) . ';color:' . esc_attr($iconColor) . '}';
    $css .= $sel . ' .instinctor-order-section{border-radius:' . $radius . 'px}';
    if (function_exists('wp_add_inline_style')) {
        wp_add_inline_style('instinctor-page-inline', $css);
    }

    $GLOBALS['impulse_order_received_settings'] = $settings;

    // Frontend: ensure shortcode exists (auto-register if missing).
    if (!$isEditor && function_exists('shortcode_exists') && !shortcode_exists('instinctor_order_received')) {
        if (function_exists('add_shortcode')) {
            add_shortcode('instinctor_order_received', function () {
                ob_start();
                $tpl = INSTINCTOR_PLUGIN_DIR . 'templates/shortcodes/order-received.php';
                if (file_exists($tpl)) include $tpl;
                return ob_get_clean();
            });
        }
    }

    $wrapCls = 'impulse-order-received-block';
    if (!empty($animAttrs['class'])) $wrapCls .= ' ' . $animAttrs['class'];
    if ($visClass !== '')            $wrapCls .= ' ' . $visClass;
    $wrapStyle = 'width:100%' . (!empty($animAttrs['style']) ? ';' . $animAttrs['style'] : '');

    ob_start();
    echo '<div id="' . esc_attr($orId) . '" class="' . esc_attr($wrapCls) . '" style="' . esc_attr($wrapStyle) . '">';
    if (function_exists('do_shortcode')) {
        echo do_shortcode('[instinctor_order_received]');
    } else {
        // Standalone fallback: include the template directly.
        $tpl = INSTINCTOR_PLUGIN_DIR . 'templates/shortcodes/order-received.php';
        if (file_exists($tpl)) include $tpl;
    }
    echo '</div>';

    unset($GLOBALS['impulse_order_received_settings']);

    return ob_get_clean();
}
