<?php
/**
 * Frontend rendering, assets, and shortcode.
 *
 * @package EyewearVirtualTryOn
 */

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

/**
 * Render the AR try-on button.
 *
 * @param WC_Product|null $product Product object.
 * @param string          $context Render context.
 * @return void
 */
function eyewvitr_render_button($product, $context = 'single') {
    static $rendered_products = [];

    $settings = eyewvitr_get_settings();
    $product  = eyewvitr_get_product($product);

    if ($settings['api_key'] === '' || !$product || !eyewvitr_is_product_enabled($product)) {
        return;
    }

    $render_key = $context . ':' . $product->get_id();

    if (isset($rendered_products[$render_key])) {
        return;
    }

    $rendered_products[$render_key] = true;

    $wc_product_id = (string) $product->get_id();
    $product_name  = $product->get_name();
    $image_url     = eyewvitr_get_product_image_url($product);

    if ($image_url === '') {
        return;
    }

    $frame_width   = get_post_meta($product->get_id(), '_eyewvitr_frame_width', true);
    $lens_height   = get_post_meta($product->get_id(), '_eyewvitr_lens_height', true);
    $temple_length = get_post_meta($product->get_id(), '_eyewvitr_temple_length', true);
    $external_id   = eyewvitr_get_external_product_id($product);

    $classes = 'eyewvitr-button';

    if ($context === 'loop') {
        $classes .= ' eyewvitr-button--loop';
    }

    $label = $settings['button_text'] !== '' ? $settings['button_text'] : __('Try Virtual Try-On', 'tryonixs-virtual-try-on-for-eyewear-stores');

    printf(
        '<button type="button" class="%1$s" data-product-id="%2$s" data-product-id-default="%2$s" data-external-id="%3$s" data-product-name="%4$s" data-image-url="%5$s" data-image-url-default="%5$s" data-frame-width="%6$s" data-lens-height="%7$s" data-temple-length="%8$s" aria-label="%9$s"><span class="eyewvitr-button__icon" aria-hidden="true"></span><span class="eyewvitr-button__label">%10$s</span></button>',
        esc_attr($classes),
        esc_attr($wc_product_id),
        esc_attr($external_id),
        esc_attr($product_name),
        esc_attr($image_url),
        esc_attr((string) $frame_width),
        esc_attr((string) $lens_height),
        esc_attr((string) $temple_length),
        esc_attr(
            sprintf(
                /* translators: %s: product name */
                __('Try on %s in AR', 'tryonixs-virtual-try-on-for-eyewear-stores'),
                $product_name
            )
        ),
        esc_html($label)
    );
}

/**
 * @return void
 */
function eyewvitr_loop_product_button() {
    eyewvitr_render_button(null, 'loop');
}

/**
 * @return void
 */
function eyewvitr_single_product_button_summary_fallback() {
    eyewvitr_render_button(null, 'single');
}

/**
 * @return void
 */
function eyewvitr_single_product_button_in_form() {
    $settings = eyewvitr_get_settings();

    if ($settings['button_position'] !== 'before_add_to_cart') {
        return;
    }

    eyewvitr_render_button(null, 'single');
}

/**
 * @return void
 */
function eyewvitr_single_product_button_after_form() {
    $settings = eyewvitr_get_settings();

    if ($settings['button_position'] !== 'after_add_to_cart') {
        return;
    }

    eyewvitr_render_button(null, 'single');
}

/**
 * Limit script loading to pages that can show the button.
 *
 * @return bool
 */
function eyewvitr_should_enqueue_assets() {
    if (!eyewvitr_is_woocommerce_active()) {
        return function_exists('is_singular') && is_singular();
    }

    if (function_exists('is_woocommerce') && is_woocommerce()) {
        return true;
    }

    if (function_exists('is_front_page') && is_front_page()) {
        return true;
    }

    if (function_exists('is_singular') && is_singular('product')) {
        return true;
    }

    return (bool) apply_filters('eyewvitr_should_enqueue_assets', false);
}

/**
 * Register front-end assets.
 *
 * @return void
 */
function eyewvitr_enqueue_sdk() {
    $settings = eyewvitr_get_settings();

    if ($settings['api_key'] === '') {
        return;
    }

    if (!eyewvitr_should_enqueue_assets()) {
        return;
    }

    wp_enqueue_style(
        'eyewvitr',
        EYEWVITR_PLUGIN_URL . 'assets/tryonixs.css',
        [],
        EYEWVITR_VERSION
    );

    wp_enqueue_script(
        'eyewvitr-sdk',
        $settings['sdk_url'],
        [],
        EYEWVITR_SDK_VERSION,
        true
    );

    wp_enqueue_script(
        'eyewvitr',
        EYEWVITR_PLUGIN_URL . 'assets/tryonixs.js',
        ['jquery', 'eyewvitr-sdk'],
        EYEWVITR_VERSION,
        true
    );

    wp_localize_script(
        'eyewvitr',
        'eyewvitrConfig',
        [
            'apiKey'     => $settings['api_key'],
            'appUrl'     => $settings['app_url'],
            'sdkVersion' => EYEWVITR_SDK_VERSION,
            'ajaxUrl'    => admin_url('admin-ajax.php'),
            'nonce'      => wp_create_nonce('eyewvitr_frontend'),
            'i18n'       => [
                'missingImage' => __('This product does not have a frame image configured for AR try-on.', 'tryonixs-virtual-try-on-for-eyewear-stores'),
                'opening'      => __('Opening Virtual Try-On…', 'tryonixs-virtual-try-on-for-eyewear-stores'),
                'missingId'    => __('Product ID is missing. Unable to open AR try-on.', 'tryonixs-virtual-try-on-for-eyewear-stores'),
            ],
        ]
    );
}
add_action('wp_enqueue_scripts', 'eyewvitr_enqueue_sdk');

/**
 * Track try-on open events (for review eligibility).
 *
 * @return void
 */
function eyewvitr_ajax_track_open() {
    check_ajax_referer('eyewvitr_frontend', 'nonce');

    $count = (int) get_option('eyewvitr_tryon_opens', 0);
    update_option('eyewvitr_tryon_opens', $count + 1, false);

    wp_send_json_success(['count' => $count + 1]);
}
add_action('wp_ajax_eyewvitr_track_open', 'eyewvitr_ajax_track_open');
add_action('wp_ajax_nopriv_eyewvitr_track_open', 'eyewvitr_ajax_track_open');

/**
 * WooCommerce hooks.
 *
 * @return void
 */
function eyewvitr_register_woocommerce_hooks() {
    if (!eyewvitr_is_woocommerce_active()) {
        return;
    }

    $settings = eyewvitr_get_settings();

    add_action('woocommerce_before_add_to_cart_button', 'eyewvitr_single_product_button_in_form', 20);
    add_action('woocommerce_after_add_to_cart_button', 'eyewvitr_single_product_button_after_form', 20);
    add_action('woocommerce_single_product_summary', 'eyewvitr_single_product_button_summary_fallback', 45);

    if ($settings['show_on_shop']) {
        add_action('woocommerce_after_shop_loop_item', 'eyewvitr_loop_product_button', 25);
    }

    add_action('woocommerce_product_options_general_product_data', 'eyewvitr_product_options');
    add_action('woocommerce_process_product_meta', 'eyewvitr_save_product_meta');
}
add_action('plugins_loaded', 'eyewvitr_register_woocommerce_hooks');

/**
 * Shortcode: [eyewvitr_button id="123"]
 *
 * @param array<string, mixed> $atts Shortcode attributes.
 * @return string
 */
function eyewvitr_button_shortcode($atts) {
    if (!eyewvitr_is_woocommerce_active() || !function_exists('wc_get_product')) {
        return '';
    }

    $atts    = shortcode_atts(['id' => 0], $atts, 'eyewvitr_button');
    $product = null;

    if (!empty($atts['id'])) {
        $product = wc_get_product((int) $atts['id']);
    }

    if (!$product) {
        global $product;
    }

    if (!is_object($product) || !method_exists($product, 'get_id')) {
        return '';
    }

    ob_start();
    eyewvitr_render_button($product, 'shortcode');

    return ob_get_clean();
}
add_shortcode('eyewvitr_button', 'eyewvitr_button_shortcode');

/**
 * Load assets when shortcode is present.
 *
 * @param array<int, WP_Post> $posts Posts.
 * @return array<int, WP_Post>
 */
function eyewvitr_shortcode_enqueue($posts) {
    if (empty($posts) || is_admin()) {
        return $posts;
    }

    foreach ($posts as $post) {
        if (!is_object($post) || empty($post->post_content)) {
            continue;
        }

        if (has_shortcode($post->post_content, 'eyewvitr_button')) {
            add_filter('eyewvitr_should_enqueue_assets', '__return_true');
            break;
        }
    }

    return $posts;
}
add_filter('the_posts', 'eyewvitr_shortcode_enqueue');
