<?php
/**
 * Shortcode: [vunelix id="123"]
 *
 * Reads widget type + settings from DB → outputs custom element with data-* attrs.
 * User only sees [vunelix id="X"] — all settings stored in post meta.
 */

defined('ABSPATH') || exit;

class Vunelix_Shortcode {

    public static function init() {
        add_shortcode('vunelix', [__CLASS__, 'render']);
    }

    public static function render($atts) {
        $atts = shortcode_atts(['id' => 0, 'widget' => ''], $atts, 'vunelix');

        // Support both [vunelix id="X"] (DB) and legacy [vunelix widget="ticker" ...] (inline)
        $post_id = intval($atts['id']);

        if ($post_id > 0) {
            return self::render_from_db($post_id);
        }

        // Legacy inline shortcode fallback
        if (!empty($atts['widget'])) {
            return self::render_inline($atts);
        }

        return '<!-- Vunelix: missing id or widget attribute -->';
    }

    /**
     * Render from database (primary method)
     */
    private static function render_from_db($post_id) {
        $post = get_post($post_id);
        if (!$post || $post->post_type !== 'vunelix_widget' || $post->post_status !== 'publish') {
            return '<!-- Vunelix: widget not found or not published -->';
        }

        $widget_type = get_post_meta($post_id, '_vunelix_widget_type', true);
        $settings    = get_post_meta($post_id, '_vunelix_settings', true);

        if (!$widget_type) return '<!-- Vunelix: no widget type set -->';

        $widgets = vunelix_get_widgets();
        if (!isset($widgets[$widget_type])) return '<!-- Vunelix: unknown widget type -->';

        $widget    = $widgets[$widget_type];
        $component = $widget['component'];
        $jsFile    = $widget['js'];

        // Register JS for footer enqueue
        global $vunelix_widgets_used;
        if (!isset($vunelix_widgets_used)) $vunelix_widgets_used = [];
        $vunelix_widgets_used[$widget_type] = $jsFile;

        // Keys that are never allowed as widget attributes (no CSS/style/script/html injection)
        $blocked = ['custom_css', 'custom_js', 'custom_html', 'style', 'script'];

        // Build data-* attributes from saved settings
        $dataAttrs = '';
        if (is_array($settings)) {
            foreach ($settings as $key => $val) {
                if ($val === '') continue;
                $key = sanitize_key($key);
                if (in_array($key, $blocked, true)) continue;
                $attrName = 'data-' . str_replace('_', '-', $key);
                $dataAttrs .= ' ' . $attrName . '="' . esc_attr($val) . '"';
            }
        }

        return '<' . esc_html($component) . $dataAttrs . '></' . esc_html($component) . '>';
    }

    /**
     * Legacy inline shortcode fallback: [vunelix widget="ticker" theme="dark" ...]
     */
    private static function render_inline($atts) {
        $slug = sanitize_text_field($atts['widget']);
        $widgets = vunelix_get_widgets();
        if (!isset($widgets[$slug])) return '<!-- Vunelix: unknown widget -->';

        $widget    = $widgets[$slug];
        $component = $widget['component'];

        global $vunelix_widgets_used;
        if (!isset($vunelix_widgets_used)) $vunelix_widgets_used = [];
        $vunelix_widgets_used[$slug] = $widget['js'];

        // Keys that are never allowed as widget attributes (no CSS/style/script/html injection)
        $blocked = ['custom_css', 'custom_js', 'custom_html', 'style', 'script'];

        $dataAttrs = '';
        foreach ($atts as $key => $val) {
            if ($key === 'widget' || $key === 'id' || $val === '') continue;
            $key = sanitize_key($key);
            if (in_array($key, $blocked, true)) continue;
            $attrName = 'data-' . str_replace('_', '-', $key);
            $dataAttrs .= ' ' . $attrName . '="' . esc_attr($val) . '"';
        }

        return '<' . esc_html($component) . $dataAttrs . '></' . esc_html($component) . '>';
    }
}
