<?php
/**
 * CalcsLive Shortcode Handler
 *
 * Handles the [calcslive] shortcode for embedding articles.
 */

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

class CalcsLive_Shortcode {

    /**
     * Register the shortcode
     */
    public static function register() {
        add_shortcode('calcslive', array(__CLASS__, 'render'));
    }

    /**
     * Render the shortcode
     *
     * @param array $atts Shortcode attributes
     * @return string HTML output
     */
    public static function render($atts) {
        // Parse attributes with defaults
        $atts = shortcode_atts(array(
            'id'     => '',
            'width'  => get_option('calcslive_default_width', '100%'),
            'height' => get_option('calcslive_default_height', '600'),
            'key'    => get_option('calcslive_api_key', ''),
            'domain' => get_option('calcslive_domain', ''),
        ), $atts, 'calcslive');

        // Validate required attributes
        if (empty($atts['id'])) {
            return self::render_error(__('CalcsLive: Article ID is required. Usage: [calcslive id="YOUR_ARTICLE_ID"]', 'calcslive-article-embed'));
        }

        if (empty($atts['key'])) {
            if (current_user_can('manage_options')) {
                return self::render_error(__('CalcsLive: API key not configured. Please set your API key in Settings &rarr; CalcsLive.', 'calcslive-article-embed'));
            }
            return self::render_error(__('CalcsLive: This embed is not properly configured.', 'calcslive-article-embed'));
        }

        // Sanitize attributes
        $article_id = sanitize_text_field($atts['id']);
        $api_key = sanitize_text_field($atts['key']);
        $domain = sanitize_text_field($atts['domain']);
        $width = self::sanitize_dimension($atts['width']);
        $height = self::sanitize_dimension($atts['height']);

        // Build embed URL
        $embed_url = self::build_embed_url($article_id, $api_key, $domain);

        // Generate unique ID for this embed
        $embed_id = 'calcslive-embed-' . wp_rand(1000, 9999);

        // Render the iframe
        return self::render_iframe($embed_id, $embed_url, $width, $height, $article_id);
    }

    /**
     * Build the embed URL
     *
     * @param string $article_id Article ID
     * @param string $api_key API key
     * @param string $domain Domain
     * @return string Embed URL
     */
    private static function build_embed_url($article_id, $api_key, $domain) {
        $url = CALCSLIVE_EMBED_BASE_URL . urlencode($article_id);

        $params = array(
            'key' => $api_key,
        );

        if (!empty($domain)) {
            $params['domain'] = $domain;
        }

        return add_query_arg($params, $url);
    }

    /**
     * Sanitize dimension value
     *
     * @param string $value Dimension value
     * @return string Sanitized value
     */
    private static function sanitize_dimension($value) {
        $value = trim($value);

        // If it's a percentage, keep it
        if (preg_match('/^\d+%$/', $value)) {
            return $value;
        }

        // If it's a number, treat as pixels
        if (is_numeric($value)) {
            return intval($value) . 'px';
        }

        // If it has px suffix, validate and keep
        if (preg_match('/^\d+px$/', $value)) {
            return $value;
        }

        // Default fallback
        return '100%';
    }

    /**
     * Render the iframe HTML
     *
     * @param string $embed_id Unique embed ID
     * @param string $url Embed URL
     * @param string $width Width
     * @param string $height Height
     * @param string $article_id Article ID for fallback link
     * @return string HTML output
     */
    private static function render_iframe($embed_id, $url, $width, $height, $article_id) {
        $fallback_url = 'https://www.calcslive.com/view/' . urlencode($article_id);

        ob_start();
        ?>
        <div id="<?php echo esc_attr($embed_id); ?>" class="calcslive-embed-container">
            <iframe
                src="<?php echo esc_url($url); ?>"
                width="<?php echo esc_attr($width); ?>"
                height="<?php echo esc_attr($height); ?>"
                frameborder="0"
                loading="lazy"
                allow="clipboard-write"
                style="border: none; max-width: 100%;"
                title="<?php esc_attr_e('CalcsLive Article', 'calcslive-article-embed'); ?>">
                <?php
                printf(
                    /* translators: %s: fallback URL */
                    esc_html__('Your browser does not support iframes. View this article at %s', 'calcslive-article-embed'),
                    '<a href="' . esc_url($fallback_url) . '">' . esc_html($fallback_url) . '</a>'
                );
                ?>
            </iframe>
        </div>
        <?php
        return ob_get_clean();
    }

    /**
     * Render error message
     *
     * @param string $message Error message
     * @return string HTML output
     */
    private static function render_error($message) {
        return '<div class="calcslive-embed-error" style="padding: 20px; background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 4px; color: #721c24;">'
            . wp_kses_post($message)
            . '</div>';
    }
}
