<?php
if (!defined('ABSPATH')) exit;

/**
 * Class SS_External_Validation
 *
 * Provides an Authority-only external validation field group for glossary terms:
 *  - External source URL
 *  - Source label
 *  - Optional notes
 *
 * Saved as postmeta:
 *  _ss_external_validation => array( 'url' => '', 'label' => '', 'notes' => '' )
 */
class SS_External_Validation {
    const META_KEY = '_ss_external_validation';
    const NONCE    = 'ss_external_validation_nonce';

    public static function init() {
        add_action('add_meta_boxes', [__CLASS__, 'add_meta_box']);
        add_action('save_post_ss_glossary', [__CLASS__, 'save_meta'], 10, 1);
        add_filter('the_content', [__CLASS__, 'maybe_append_frontend_html'], 20);

        // Optional: Add a column to glossary admin list for quick visibility
        add_filter('manage_ss_glossary_posts_columns', [__CLASS__, 'admin_columns']);
        add_action('manage_ss_glossary_posts_custom_column', [__CLASS__, 'admin_columns_render'], 10, 2);
    }

    private static function plan() {
        if (!class_exists('SS_Licensing')) return 'free';
        $data = SS_Licensing::get_cached_status();
        return strtolower($data['plan'] ?? 'free');
    }

    public static function add_meta_box() {
        add_meta_box(
            'ss_external_validation',
            __('External Validation', 'searchshifter'),
            [__CLASS__, 'render_meta_box'],
            'ss_glossary',
            'side',
            'default'
        );
    }

    public static function render_meta_box($post) {
        $plan = self::plan();
        $data = get_post_meta($post->ID, self::META_KEY, true) ?: ['url'=>'','label'=>'','notes'=>''];

        // Nonce
        wp_nonce_field(self::NONCE, self::NONCE);

        if ($plan !== 'authority' && $plan !== 'elite') {
            // Locked fallback UI
            echo '<div style="background:#fff8e5;border-left:4px solid #dba617;padding:10px;border-radius:4px;">';
            echo '<p style="margin:0 0 8px;"><strong>Authority Feature</strong></p>';
            echo '<p style="margin:0 0 8px;">This feature is available on the <strong>Authority</strong> plan.</p>';
            echo '<p style="margin:0;"><a href="https://searchshifter.ai/pricing" target="_blank" class="button button-primary">Upgrade to Authority</a></p>';
            echo '</div>';
            return;
        }

        // Render fields for Authority plan
        $url   = esc_attr($data['url'] ?? '');
        $label = esc_attr($data['label'] ?? '');
        $notes = esc_textarea($data['notes'] ?? '');

        echo '<p><label for="ss_ev_url"><strong>' . esc_html__('External Source URL', 'searchshifter') . '</strong></label></p>';
        echo '<input type="url" id="ss_ev_url" name="ss_ev_url" value="' . $url . '" placeholder="https://example.com" style="width:100%;margin-bottom:8px;" />';

        echo '<p><label for="ss_ev_label"><strong>' . esc_html__('Source Label', 'searchshifter') . '</strong></label></p>';
        echo '<input type="text" id="ss_ev_label" name="ss_ev_label" value="' . $label . '" placeholder="Wikipedia / Research Paper / Organization" style="width:100%;margin-bottom:8px;" />';

        echo '<p><label for="ss_ev_notes"><strong>' . esc_html__('Notes (optional)', 'searchshifter') . '</strong></label></p>';
        echo '<textarea id="ss_ev_notes" name="ss_ev_notes" rows="4" style="width:100%;">' . $notes . '</textarea>';

        echo '<p class="description" style="margin-top:8px;">' .
             esc_html__('Enter an authoritative external source for this term. Visible publicly if the site setting allows.', 'searchshifter') .
             '</p>';
    }

    public static function save_meta($post_id) {
        // Basic capability + autosave checks
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
        if (!current_user_can('edit_post', $post_id)) return;

        if (empty($_POST[self::NONCE]) || !wp_verify_nonce($_POST[self::NONCE], self::NONCE)) return;

        // Only Authority can save (prevent low-tier submissions)
        $plan = self::plan();
        if ($plan !== 'authority' && $plan !== 'elite') {
            // remove any existing meta if downgrade
            delete_post_meta($post_id, self::META_KEY);
            return;
        }

        $url   = isset($_POST['ss_ev_url']) ? esc_url_raw(trim($_POST['ss_ev_url'])) : '';
        $label = isset($_POST['ss_ev_label']) ? sanitize_text_field(trim($_POST['ss_ev_label'])) : '';
        $notes = isset($_POST['ss_ev_notes']) ? wp_kses_post(trim($_POST['ss_ev_notes'])) : '';

        // Minimal validation: empty object removes meta
        if (empty($url) && empty($label) && empty($notes)) {
            delete_post_meta($post_id, self::META_KEY);
            return;
        }

        $data = [
            'url'   => $url,
            'label' => $label,
            'notes' => $notes
        ];

        update_post_meta($post_id, self::META_KEY, $data);
    }

    /**
     * Front-end rendering helper.
     * Appends the external validation block to glossary single content if allowed.
     * It respects a site option "ss_external_validation_public" (boolean) — fallback true.
     */
    public static function maybe_append_frontend_html($content) {
        if (!is_singular('ss_glossary')) return $content;

        global $post;

        // Check site-level toggle (option not created? default true)
        $public = get_option('ss_external_validation_public', '1');
        if (!$public || $public === '0') return $content;

        $data = get_post_meta($post->ID, self::META_KEY, true);
        if (empty($data) || empty($data['url']) && empty($data['label']) && empty($data['notes'])) {
            return $content;
        }

        // Build block
        $label = !empty($data['label']) ? esc_html($data['label']) : esc_html__('External Reference', 'searchshifter');
        $url   = !empty($data['url']) ? esc_url($data['url']) : '';
        $notes = !empty($data['notes']) ? wpautop(wp_kses_post($data['notes'])) : '';

        $html  = '<div class="ss-external-validation" style="margin-top:22px;padding:14px;border:1px solid #e6e6e6;border-radius:6px;background:#fafafa;">';
        $html .= '<h3 style="margin-top:0;margin-bottom:8px;font-size:16px;">' . $label . '</h3>';
        if ($url) {
            $html .= '<p><a href="' . $url . '" target="_blank" rel="nofollow noopener noreferrer">' . $url . '</a></p>';
        }
        if ($notes) {
            $html .= '<div class="ss-external-notes" style="margin-top:8px;color:#444;">' . $notes . '</div>';
        }
        $html .= '</div>';

        // Append to end of content
        return $content . $html;
    }

    // --------------------------
    // Admin list column helpers
    // --------------------------
    public static function admin_columns($cols) {
        $cols_before = [];
        foreach ($cols as $k => $v) {
            $cols_before[$k] = $v;
            if ($k === 'title') {
                // insert our column after title
                $cols_before['external_validation'] = __('External Validation','searchshifter');
            }
        }
        return $cols_before;
    }

    public static function admin_columns_render($column, $post_id) {
        if ($column !== 'external_validation') return;
        $d = get_post_meta($post_id, self::META_KEY, true);
        if (empty($d) || (empty($d['url']) && empty($d['label']))) {
            echo '<span style="color:#777;">—</span>';
            return;
        }
        $label = !empty($d['label']) ? esc_html($d['label']) : '';
        $url   = !empty($d['url']) ? esc_url($d['url']) : '';
        if ($label && $url) {
            echo '<a href="' . $url . '" target="_blank" rel="noopener noreferrer" style="text-decoration:none;">' . $label . '</a>';
        } elseif ($label) {
            echo esc_html($label);
        } elseif ($url) {
            echo '<a href="' . $url . '" target="_blank" rel="noopener noreferrer" style="text-decoration:none;">' . esc_html($url) . '</a>';
        }
    }
}

// initialize
SS_External_Validation::init();
