<?php
/**
 * Custom Post Type: vunelix_widget
 *
 * Registers CPT + meta boxes for widget settings.
 * Settings saved to post_meta → shortcode reads by post ID.
 */

defined('ABSPATH') || exit;

class Vunelix_Post_Type {

    const POST_TYPE = 'vunelix_widget';
    const META_KEY  = '_vunelix_settings';
    const TYPE_KEY  = '_vunelix_widget_type';

    public static function init() {
        add_action('init', [__CLASS__, 'register']);
        add_action('add_meta_boxes', [__CLASS__, 'add_meta_boxes']);
        add_action('save_post_' . self::POST_TYPE, [__CLASS__, 'save_meta'], 10, 2);
        add_action('admin_enqueue_scripts', [__CLASS__, 'enqueue_assets']);

        // Shortcode column in All Widgets list
        add_filter('manage_' . self::POST_TYPE . '_posts_columns', [__CLASS__, 'add_columns']);
        add_action('manage_' . self::POST_TYPE . '_posts_custom_column', [__CLASS__, 'render_columns'], 10, 2);
    }

    /**
     * Register Custom Post Type
     */
    public static function register() {
        register_post_type(self::POST_TYPE, [
            'labels' => [
                'name'               => 'Vunelix Widgets',
                'singular_name'      => 'Widget',
                'add_new'            => 'Add New Widget',
                'add_new_item'       => 'Add New Widget',
                'edit_item'          => 'Edit Widget',
                'new_item'           => 'New Widget',
                'view_item'          => 'View Widget',
                'search_items'       => 'Search Widgets',
                'not_found'          => 'No widgets found',
                'not_found_in_trash' => 'No widgets found in Trash',
                'all_items'          => 'All Widgets',
                'menu_name'          => 'Vunelix Widgets',
            ],
            'public'             => false,
            'show_ui'            => true,
            'show_in_menu'       => false,
            'menu_icon'          => 'dashicons-chart-area',
            'menu_position'      => 30,
            'supports'           => ['title'],
            'capability_type'    => 'post',
            'has_archive'        => false,
            'exclude_from_search'=> true,
            'publicly_queryable' => false,
        ]);
    }

    /**
     * Enqueue admin assets on our CPT pages only
     */
    public static function enqueue_assets($hook) {
        $screen = get_current_screen();
        if (!$screen) return;
        $is_cpt = $screen->post_type === self::POST_TYPE;
        $is_vunelix_page = strpos($screen->id, 'vunelix') !== false;
        if (!$is_cpt && !$is_vunelix_page) return;

        // Disable WP heartbeat on our pages (unnecessary ajax calls)
        wp_deregister_script('heartbeat');

        wp_enqueue_style('vunelix-admin', VUNELIX_PLUGIN_URL . 'assets/css/admin.css', [], VUNELIX_VERSION);
        wp_enqueue_script('vunelix-admin', VUNELIX_PLUGIN_URL . 'assets/js/admin.js', [], VUNELIX_VERSION, true);

        // Inject runtime URLs for the widget preview (admin loads widget JS
        // dynamically when "Apply Changes" is clicked — those modules read
        // these globals to find the API, the local CSS bundles, and lang JSON).
        $api_url = trailingslashit(VUNELIX_API_URL);
        $bootstrap = sprintf(
            'window.VUNELIX_API_URL=%s;window.VUNELIX_CSS_URL=%s;window.JS_URL=%s;',
            wp_json_encode($api_url),
            wp_json_encode(VUNELIX_PLUGIN_URL . 'assets/css/widget-runtime/'),
            wp_json_encode($api_url . 'assets/js/')
        );
        wp_add_inline_script('vunelix-admin', $bootstrap, 'before');

        // Make admin.js a module so it can import screener-data.js
        add_filter('script_loader_tag', function($tag, $handle) {
            if ($handle === 'vunelix-admin') {
                return str_replace(' src=', ' type="module" src=', $tag);
            }
            return $tag;
        }, 10, 2);

        $langCommon = vunelix_load_lang('common');
        wp_localize_script('vunelix-admin', 'vunelix', [
            'widgets'      => vunelix_get_widgets(),
            'groups'       => vunelix_get_widget_groups(),
            'commonFields' => vunelix_common_fields(),
            'countries'    => $langCommon['countries'] ?? [],
            'cdnUrl'       => VUNELIX_CDN_URL,
            'version'      => VUNELIX_VERSION,
            'postType'     => self::POST_TYPE,
            'savedType'    => get_post_meta(get_the_ID(), self::TYPE_KEY, true),
            'savedSettings'=> get_post_meta(get_the_ID(), self::META_KEY, true) ?: [],
        ]);
    }

    /**
     * Add meta boxes
     */
    public static function add_meta_boxes() {
        // Widget Type selector
        add_meta_box(
            'vnx_widget_type',
            'Widget Type',
            [__CLASS__, 'render_type_box'],
            self::POST_TYPE,
            'normal',
            'high'
        );

        // Live Preview
        add_meta_box(
            'vnx_preview',
            'Live Preview',
            [__CLASS__, 'render_preview_box'],
            self::POST_TYPE,
            'normal',
            'high'
        );

        // Widget Settings (dynamic fields)
        add_meta_box(
            'vnx_settings',
            'Widget Settings',
            [__CLASS__, 'render_settings_box'],
            self::POST_TYPE,
            'normal',
            'default'
        );

        // Shortcode (sidebar)
        add_meta_box(
            'vnx_shortcode',
            'Widget Shortcode',
            [__CLASS__, 'render_shortcode_box'],
            self::POST_TYPE,
            'side',
            'high'
        );
    }

    /**
     * Meta Box: Widget Type selector
     */
    public static function render_type_box($post) {
        wp_nonce_field('vunelix_save', 'vunelix_nonce');
        $current_type = get_post_meta($post->ID, self::TYPE_KEY, true);
        $widgets = vunelix_get_widgets();
        $groups = vunelix_get_widget_groups();
        ?>
        <div class="vnx-type-selector">
            <p class="vnx-type-hint">
                <span class="dashicons dashicons-arrow-down-alt"></span>
                Select a widget type below, then configure its settings and preview it live.
            </p>
            <select name="vnx_widget_type" id="vnxWidgetType" class="vnx-type-select">
                <option value="">— Choose Widget Type —</option>
                <?php foreach ($groups as $groupLabel => $slugs): ?>
                <optgroup label="<?php echo esc_attr($groupLabel); ?>">
                    <?php foreach ($slugs as $slug):
                        $w = $widgets[$slug] ?? null;
                        if (!$w) continue;
                    ?>
                    <option value="<?php echo esc_attr($slug); ?>" <?php selected($current_type, $slug); ?>>
                        <?php echo esc_html($w['name']); ?>
                    </option>
                    <?php endforeach; ?>
                </optgroup>
                <?php endforeach; ?>
            </select>
            <p class="vnx-type-desc" id="vnxTypeDesc"></p>
        </div>
        <?php
    }

    /**
     * Meta Box: Live Preview
     */
    public static function render_preview_box($post) {
        ?>
        <div id="vnxPreviewBox" class="vnx-preview-box">
            <p class="vnx-preview-placeholder" id="vnxPreviewPlaceholder">Select a widget type and click <strong>Apply Changes</strong> to preview.</p>
        </div>
        <div class="vnx-preview-actions">
            <button type="button" class="button button-primary" id="vnxApplyBtn">Apply Changes</button>
        </div>
        <?php
    }

    /**
     * Meta Box: Widget Settings (rendered by JS based on selected type)
     */
    public static function render_settings_box($post) {
        ?>
        <div id="vnxSettings" class="vnx-settings-wrap">
            <p class="vnx-settings-placeholder" id="vnxSettingsPlaceholder">Select a widget type above to see available settings.</p>
        </div>
        <div class="vnx-preview-actions vnx-preview-actions-bottom" id="vnxApplyBtnBottom" style="display:none;">
            <button type="button" class="button button-primary vnx-apply-bottom-btn">Apply Changes</button>
        </div>
        <!-- Hidden field to store all settings as JSON -->
        <input type="hidden" name="vnx_settings_json" id="vnxSettingsJson" value="<?php echo esc_attr(wp_json_encode(get_post_meta($post->ID, self::META_KEY, true) ?: new stdClass)); ?>">
        <?php
    }

    /**
     * Meta Box: Shortcode display (sidebar)
     */
    public static function render_shortcode_box($post) {
        $shortcode = '[vunelix id="' . $post->ID . '"]';
        ?>
        <div class="vnx-shortcode-box">
            <p>Copy &amp; paste this shortcode into any page or post:</p>
            <div class="vnx-shortcode-field">
                <input type="text" value="<?php echo esc_attr($shortcode); ?>" readonly id="vnxShortcodeField" onclick="this.select();">
                <button type="button" class="button" id="vnxCopyShortcode">Copy</button>
            </div>
        </div>
        <?php
    }

    /**
     * Save meta on post save
     */
    public static function save_meta($post_id, $post) {
        if (!isset($_POST['vunelix_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['vunelix_nonce'])), 'vunelix_save')) return;
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
        if (!current_user_can('edit_post', $post_id)) return;

        // Save widget type
        if (isset($_POST['vnx_widget_type'])) {
            update_post_meta($post_id, self::TYPE_KEY, sanitize_text_field(wp_unslash($_POST['vnx_widget_type'])));
        }

        // Save settings JSON
        if (isset($_POST['vnx_settings_json'])) {
            $json = sanitize_text_field(wp_unslash($_POST['vnx_settings_json']));
            $settings = json_decode($json, true);
            if (is_array($settings)) {
                // Sanitize each value
                $clean = [];
                foreach ($settings as $key => $val) {
                    $key = sanitize_key($key);
                    // Disallow arbitrary CSS/style/script/html injection via settings
                    if (in_array($key, ['custom_css', 'custom_js', 'custom_html', 'style', 'script'], true)) continue;
                    $clean[$key] = sanitize_text_field($val);
                }
                update_post_meta($post_id, self::META_KEY, $clean);
            }
        }
    }

    /**
     * Add shortcode column to All Widgets list
     */
    public static function add_columns($columns) {
        $new = [];
        foreach ($columns as $key => $label) {
            $new[$key] = $label;
            if ($key === 'title') {
                $new['vnx_type'] = 'Widget Type';
                $new['vnx_shortcode'] = 'Shortcode';
            }
        }
        return $new;
    }

    /**
     * Render custom columns
     */
    public static function render_columns($column, $post_id) {
        if ($column === 'vnx_type') {
            $type = get_post_meta($post_id, self::TYPE_KEY, true);
            $widgets = vunelix_get_widgets();
            echo esc_html($widgets[$type]['name'] ?? $type ?: '—');
        }
        if ($column === 'vnx_shortcode') {
            echo '<code>[vunelix id="' . intval($post_id) . '"]</code>';
        }
    }
}
