<?php
/**
 * Shared helpers and settings.
 *
 * @package EyewearVirtualTryOn
 */

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

/**
 * Text domain helper (must stay a literal string in translation calls).
 *
 * @return string
 */
function eyewvitr_textdomain() {
    return 'tryonixs-virtual-try-on-for-eyewear-stores';
}

/**
 * Safely read a string option.
 *
 * @param string $key     Option key.
 * @param string $default Default value.
 * @return string
 */
function eyewvitr_get_option($key, $default = '') {
    $value = get_option($key, $default);

    if (is_string($value) || is_numeric($value)) {
        return (string) $value;
    }

    return (string) $default;
}

/**
 * Whether WooCommerce is available.
 *
 * @return bool
 */
function eyewvitr_is_woocommerce_active() {
    return class_exists('WooCommerce') && function_exists('WC');
}

/**
 * Plugin settings with defaults.
 *
 * @return array<string, mixed>
 */
function eyewvitr_get_settings() {
    return [
        'api_key'         => eyewvitr_get_option('eyewvitr_api_key', ''),
        'app_url'         => eyewvitr_get_option('eyewvitr_app_url', 'https://tryonixs.com'),
        'sdk_url'         => eyewvitr_get_option('eyewvitr_sdk_url', 'https://tryonixs.com/tryonixs-sdk.js'),
        'button_text'     => eyewvitr_get_option('eyewvitr_button_text', 'Try Virtual Try-On'),
        'button_position' => eyewvitr_get_option('eyewvitr_button_position', 'before_add_to_cart'),
        'show_on_shop'    => eyewvitr_get_option('eyewvitr_show_on_shop', 'yes') === 'yes',
    ];
}

/**
 * Whether the store has a connected API key.
 *
 * @return bool
 */
function eyewvitr_is_connected() {
    return eyewvitr_get_option('eyewvitr_api_key', '') !== '';
}

/**
 * Setup checklist for dashboard/onboarding.
 *
 * @return array<string, bool>
 */
function eyewvitr_get_setup_status() {
    $connected = eyewvitr_is_connected();
    $has_products = false;

    if (eyewvitr_is_woocommerce_active()) {
        $query = new WP_Query([
            'post_type'              => 'product',
            'post_status'            => 'publish',
            'posts_per_page'         => 1,
            'fields'                 => 'ids',
            'no_found_rows'          => true,
            'update_post_meta_cache' => false,
            'update_post_term_cache' => false,
        ]);
        $has_products = $query->post_count > 0;
        wp_reset_postdata();
    }

    $used = (int) get_option('eyewvitr_tryon_opens', 0) > 0;

    return [
        'account'   => true,
        'connected' => $connected,
        'products'  => $connected && $has_products,
        'launched'  => $connected && $used,
    ];
}

/**
 * Resolve external / Tryonixs product ID for the AR service.
 *
 * @param WC_Product $product Product object.
 * @return string
 */
function eyewvitr_get_external_product_id($product) {
    $custom_id = get_post_meta($product->get_id(), '_eyewvitr_product_id', true);

    if ($custom_id !== '') {
        return (string) $custom_id;
    }

    $sku = $product->get_sku();
    if ($sku !== '') {
        return (string) $sku;
    }

    return 'wc_' . $product->get_id();
}

/**
 * Normalize image URL to absolute.
 *
 * @param string $url Image URL.
 * @return string
 */
function eyewvitr_normalize_image_url($url) {
    $url = esc_url_raw($url);

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

    if (strpos($url, 'http://') !== 0 && strpos($url, 'https://') !== 0) {
        $url = home_url($url);
    }

    return $url;
}

/**
 * Get the current WooCommerce product object.
 *
 * @param WC_Product|null $product Product object.
 * @return WC_Product|null
 */
function eyewvitr_get_product($product = null) {
    if (is_object($product) && method_exists($product, 'get_id')) {
        return $product;
    }

    global $product;

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

    if (!function_exists('wc_get_product')) {
        return null;
    }

    $post_id = get_the_ID();

    if ($post_id) {
        return wc_get_product($post_id);
    }

    return null;
}

/**
 * Resolve frame image URL for try-on.
 *
 * @param WC_Product|null $product Product object.
 * @return string
 */
function eyewvitr_get_product_image_url($product) {
    $product = eyewvitr_get_product($product);

    if (!$product) {
        return '';
    }

    $custom_url = get_post_meta($product->get_id(), '_eyewvitr_image_url', true);

    if ($custom_url !== '') {
        return eyewvitr_normalize_image_url($custom_url);
    }

    $image_id = $product->get_image_id();

    if (!$image_id) {
        $image_id = (int) get_post_thumbnail_id($product->get_id());
    }

    if (!$image_id && method_exists($product, 'get_gallery_image_ids')) {
        $gallery_ids = $product->get_gallery_image_ids();

        if (!empty($gallery_ids)) {
            $image_id = (int) $gallery_ids[0];
        }
    }

    if (!$image_id) {
        return '';
    }

    $url = wp_get_attachment_url($image_id);

    if (!$url && function_exists('wp_get_attachment_image_url')) {
        $url = wp_get_attachment_image_url($image_id, 'full');
    }

    return $url ? eyewvitr_normalize_image_url($url) : '';
}

/**
 * Whether try-on should render for this product.
 *
 * @param WC_Product|null $product Product object.
 * @return bool
 */
function eyewvitr_is_product_enabled($product) {
    $product = eyewvitr_get_product($product);

    if (!$product) {
        return false;
    }

    $enabled = get_post_meta($product->get_id(), '_eyewvitr_enabled', true);

    if ($enabled === 'no') {
        return false;
    }

    if (method_exists($product, 'get_status') && $product->get_status() !== 'publish') {
        return false;
    }

    return eyewvitr_get_product_image_url($product) !== '';
}

/**
 * Sanitize button position.
 *
 * @param string $value Button position.
 * @return string
 */
function eyewvitr_sanitize_button_position($value) {
    $allowed = ['before_add_to_cart', 'after_add_to_cart'];

    return in_array($value, $allowed, true) ? $value : 'before_add_to_cart';
}

/**
 * Sanitize yes/no option.
 *
 * @param string $value Yes/no value.
 * @return string
 */
function eyewvitr_sanitize_yes_no($value) {
    return $value === 'yes' ? 'yes' : 'no';
}
