<?php
/**
 * CalcsLive Physical Quantity Shortcodes
 *
 * Handles [calcslive_qty], [calcslive_qty_pair], and [calcslive_qty_triplet] shortcodes
 * for rendering interactive unit-aware physical quantities.
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

class CalcsLive_PQ_Shortcode {

    /**
     * Track whether any PQ shortcode was used on the current page
     */
    private static $enqueued = false;

    /**
     * Register all PQ shortcodes
     */
    public static function register() {
        add_shortcode('calcslive_qty', array(__CLASS__, 'render_qty'));
        add_shortcode('calcslive_qty_pair', array(__CLASS__, 'render_qty_pair'));
        add_shortcode('calcslive_qty_triplet', array(__CLASS__, 'render_qty_triplet'));
    }

    /**
     * Enqueue the PQ web component script (once per page)
     */
    private static function maybe_enqueue_script() {
        if (self::$enqueued) {
            return;
        }

        wp_enqueue_script(
            'calcslive-pq',
            CALCSLIVE_PLUGIN_URL . 'assets/js/pq.umd.js',
            array(),
            CALCSLIVE_PQ_VERSION,
            true
        );

        self::$enqueued = true;
    }

    /**
     * Render [calcslive_qty] shortcode
     *
     * Usage: [calcslive_qty value="2" unit="lbm" dp="2"]
     *
     * @param array $atts Shortcode attributes
     * @return string HTML output
     */
    public static function render_qty($atts) {
        $atts = shortcode_atts(array(
            'value'          => '',
            'unit'           => '',
            'dp'             => '2',
            'show_unit_arrow' => 'true',
        ), $atts, 'calcslive_qty');

        if (empty($atts['value']) || empty($atts['unit'])) {
            return self::render_error('calcslive_qty requires value and unit attributes');
        }

        self::maybe_enqueue_script();

        $attrs = self::build_attrs(array(
            'value'           => floatval($atts['value']),
            'unit'            => sanitize_text_field($atts['unit']),
            'decimal-places'  => intval($atts['dp']),
            'show-unit-arrow' => $atts['show_unit_arrow'],
        ));

        return '<uc-qty ' . $attrs . '></uc-qty>';
    }

    /**
     * Render [calcslive_qty_pair] shortcode
     *
     * Usage: [calcslive_qty_pair values="10x20" unit="cm" dp="2"]           // x-format: dimensions
     *        [calcslive_qty_pair values="(10, 20)" unit="cm" dp="2"]        // tuple: coordinates or range
     *
     * @param array $atts Shortcode attributes
     * @return string HTML output
     */
    public static function render_qty_pair($atts) {
        $atts = shortcode_atts(array(
            'values'          => '',
            'unit'            => '',
            'dp'              => '2',
            'show_unit_arrow' => 'true',
        ), $atts, 'calcslive_qty_pair');

        if (empty($atts['values']) || empty($atts['unit'])) {
            return self::render_error('calcslive_qty_pair requires values and unit attributes');
        }

        self::maybe_enqueue_script();

        $attrs = self::build_attrs(array(
            'values'          => sanitize_text_field($atts['values']),
            'unit'            => sanitize_text_field($atts['unit']),
            'decimal-places'  => intval($atts['dp']),
            'show-unit-arrow' => $atts['show_unit_arrow'],
        ));

        return '<uc-qty-pair ' . $attrs . '></uc-qty-pair>';
    }

    /**
     * Render [calcslive_qty_triplet] shortcode
     *
     * Usage: [calcslive_qty_triplet values="10x20x30" unit="cm" dp="2"]     // x-format: L x W x H
     *        [calcslive_qty_triplet values="(10, 20, 30)" unit="cm" dp="2"] // tuple: coordinates
     *
     * @param array $atts Shortcode attributes
     * @return string HTML output
     */
    public static function render_qty_triplet($atts) {
        $atts = shortcode_atts(array(
            'values'          => '',
            'unit'            => '',
            'dp'              => '2',
            'show_unit_arrow' => 'true',
        ), $atts, 'calcslive_qty_triplet');

        if (empty($atts['values']) || empty($atts['unit'])) {
            return self::render_error('calcslive_qty_triplet requires values and unit attributes');
        }

        self::maybe_enqueue_script();

        $attrs = self::build_attrs(array(
            'values'          => sanitize_text_field($atts['values']),
            'unit'            => sanitize_text_field($atts['unit']),
            'decimal-places'  => intval($atts['dp']),
            'show-unit-arrow' => $atts['show_unit_arrow'],
        ));

        return '<uc-qty-triplet ' . $attrs . '></uc-qty-triplet>';
    }

    /**
     * Build HTML attribute string from an associative array
     *
     * @param array $attrs Attribute key-value pairs
     * @return string HTML attributes
     */
    private static function build_attrs($attrs) {
        $parts = array();
        foreach ($attrs as $key => $value) {
            $parts[] = esc_attr($key) . '="' . esc_attr($value) . '"';
        }
        return implode(' ', $parts);
    }

    /**
     * Render error message (admin-only)
     *
     * @param string $message Error message
     * @return string HTML output or empty string
     */
    private static function render_error($message) {
        if (!current_user_can('edit_posts')) {
            return '';
        }
        return '<span style="color: #721c24; background: #f8d7da; padding: 2px 6px; border-radius: 3px; font-size: 0.85em;">'
            . esc_html($message)
            . '</span>';
    }
}
