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

class SS_QA_Admin_UI
{
    // const META_PAIRS   = '_ss_qa_pairs';    // array of ['q'=>..,'a'=>..]
    const META_JSON    = '_ss_schema_json'; // minified JSON-LD
    const META_SIG     = '_ss_schema_sig';  // signature (optional)

    public static function init() {
        add_action('add_meta_boxes',        [__CLASS__,'metaboxes']);
        add_action('save_post_ss_qa',       [__CLASS__,'save'], 10, 2);
        add_action('admin_enqueue_scripts', [__CLASS__,'enqueue']);
        add_action('wp_ajax_ss_build_schema',[__CLASS__,'ajax_build_schema']);

        // clean editor chrome
        add_action('admin_head-post.php',     [__CLASS__, 'clean_editor_chrome']);
        add_action('admin_head-post-new.php', [__CLASS__, 'clean_editor_chrome']);

        // show success/error after build/save
        add_action('admin_notices', [__CLASS__, 'post_notices']);

        add_action('init', function() {
            remove_post_type_support('ss_qa', 'editor');
        });
    }

    public static function clean_editor_chrome() {
        if (!function_exists('get_current_screen')) return;
        $s = get_current_screen();
        if (!$s || $s->post_type !== 'ss_qa') return;

        remove_meta_box('commentstatusdiv',   'ss_qa', 'normal');
        remove_meta_box('commentsdiv',        'ss_qa', 'normal');
        remove_meta_box('trackbacksdiv',      'ss_qa', 'normal');
        remove_meta_box('authordiv',          'ss_qa', 'normal');
        remove_meta_box('revisionsdiv',       'ss_qa', 'normal');
        remove_meta_box('slugdiv',            'ss_qa', 'normal');
        remove_meta_box('postcustom',         'ss_qa', 'normal');
        remove_meta_box('pageparentdiv',      'ss_qa', 'side');

        echo '<style>
            #edit-slug-box{
                display:none !important;
            }
            </style>';
    }

    /** Only load on ss_qa screens. */
    public static function enqueue($hook) {
        if (!function_exists('get_current_screen')) return;
        $s = get_current_screen();
        if (!$s || $s->post_type !== 'ss_qa') return;

        wp_enqueue_style('dashicons');
        wp_add_inline_style('wp-admin', self::css());
        wp_add_inline_script('jquery-core', self::js());
    }

    public static function metaboxes() {
        // add_meta_box('ssqa_pairs',  __('Q&A Pairs','searchshifter'), [__CLASS__,'box_pairs'],  'ss_qa','normal','high');
        add_meta_box('ssqa_schema', __('Schema / Cache','searchshifter'), [__CLASS__,'box_schema'],'ss_qa','side','default');
        add_meta_box(
            'ssqa_answer',
            'Answer',
            [__CLASS__, 'box_answer'],
            'ss_qa',
            'normal',
            'high'
        );
    }

    public static function box_answer($post){

        echo '<div style="background:#f0f6ff;padding:10px 14px;border-left:4px solid #2271b1;margin-bottom:15px;">
        <strong>Quick Rule:</strong> Write questions naturally and give a clear, direct answer.
        </div>';

        echo '<p style="color:#666;font-size:13px;margin-bottom:8px;">
        Start with a direct answer in the first sentence. Keep it clear and concise (2–3 sentences). Avoid promotional or vague language.
        </p>';

        $value = get_post_meta($post->ID, '_ss_qa_answer', true);

        echo '<textarea name="ss_qa_answer" style="width:100%;height:120px;">'
            . esc_textarea($value) .
        '</textarea>';


        echo '<div style="margin-top:10px;padding:10px;background:#f9f9f9;border:1px solid #ddd;">
        <strong>Example:</strong><br>
        <span style="color:#2e7d32;">✔ AI visibility is how easily your content is discovered and used by AI systems.</span><br>
        <span style="color:#c62828;">✘ At our company, we specialize in improving AI visibility for clients.</span>
        </div>';
    }

    /** Repeater UI for Q/A pairs. */
    // public static function box_pairs(\WP_Post $post) {
    //     wp_nonce_field('ssqa_save_pairs','ssqa_nonce');
    //     $pairs = (array) get_post_meta($post->ID, self::META_PAIRS, true);

    //     echo '<div class="ssqa-repeater">';
    //     echo '<table class="widefat striped fixed"><thead><tr>';
    //     echo '<th style="width:45%;">Question</th><th style="width:55%;">Answer</th><th style="width:36px;"></th>';
    //     echo '</tr></thead><tbody id="ssqa-rows">';

    //     if (empty($pairs)) $pairs = [['q'=>'','a'=>'']];

    //     foreach ($pairs as $row){
    //         $q = isset($row['q']) ? $row['q'] : '';
    //         $a = isset($row['a']) ? $row['a'] : '';
    //         printf(
    //             '<tr class="ssqa-row">
    //                 <td><input type="text"  name="ssqa[q][]" value="%s" class="widefat" /></td>
    //                 <td><textarea name="ssqa[a][]" rows="3" class="widefat">%s</textarea></td>
    //                 <td><button type="button" class="button-link ssqa-del-row" title="Remove"><span class="dashicons dashicons-trash"></span></button></td>
    //             </tr>',
    //             esc_attr($q), esc_textarea($a)
    //         );
    //     }

    //     echo '</tbody></table>';
    //     echo '<p><button type="button" class="button button-secondary" id="ssqa-add-row"><span class="dashicons dashicons-plus-alt2" style="vertical-align:-3px;"></span> ' . esc_html__('Add pair', 'searchshifter') . '</button></p>';
    //     echo '</div>';
    // }

    public static function box_schema(\WP_Post $post) {
        $lic   = class_exists('SS_Licensing') ? SS_Licensing::get_cached_status() : ['active'=>false];
        $json  = (string) get_post_meta($post->ID, self::META_JSON, true);
        $err   = (string) get_post_meta($post->ID, '_ss_schema_error', true);
        $tried = (int) get_post_meta($post->ID, '_ss_schema_attempted', true);

        // TTL readout
        $timeout = (int) get_option('_transient_timeout_ss_last_schema_build_'.$post->ID, 0);
        $left    = max(0, $timeout - time());
        // translators: %1$d = hours, %2$d = minutes
        $ttl = $left
            ? sprintf(
                // translators: %1$d = hours, %2$d = minutes
                __('%1$dh %2$dm', 'searchshifter'),
                floor($left / 3600),
                floor(($left % 3600) / 60)
            )
            : __('not cached', 'searchshifter');

        if (empty($lic['active'])) {
            echo '<div class="notice notice-warning"><p>'.esc_html__('License inactive — read-only.','searchshifter').'</p></div>';
        }

        // Show error ONLY when: not auto-draft, we tried to build, there is an error, and no JSON
        if ($post->post_status !== 'auto-draft' && $tried && $err !== '' && $json === '') {
            echo '<div class="notice notice-error"><p>'.esc_html__('Schema build failed: ','searchshifter').'<code>'.esc_html($err).'</code></p></div>';
        }

        echo '<p><strong>' . esc_html__('Cache TTL', 'searchshifter') . ':</strong> <code>' . esc_html($ttl) . '</code></p>';

        echo '<textarea id="ssqa-json" readonly rows="10" style="width:100%;font-family:monospace;">';
        echo esc_textarea($json);
        echo '</textarea>';

        echo '<input type="hidden" id="ssqa-nonce" value="'.esc_attr(wp_create_nonce('ssqa_build_'.$post->ID)).'">';
    }

    /** Save pairs. */
    public static function save( $post_id, \WP_Post $post ) {

        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
            return;
        }

        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            return;
        }

        if (isset($_POST['ss_qa_answer'])) {
            update_post_meta(
                $post_id,
                '_ss_qa_answer',
                sanitize_textarea_field($_POST['ss_qa_answer'])
            );
        }
    }

    /** AJAX: Build schema NOW (bypass cache) and refresh preview/TTL. */
    // SS_QA_Admin_UI::ajax_build_schema
    public static function ajax_build_schema() {

        // ---- Read + unslash + sanitize inputs ----
        $post_id = isset( $_POST['id'] )
            ? absint( wp_unslash( $_POST['id'] ) )
            : 0;


        $nonce = isset( $_POST['nonce'] )
            ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) )
            : '';

        // ---- Validate nonce ----
        if ( ! $post_id || ! $nonce || ! wp_verify_nonce( $nonce, 'ssqa_build_' . $post_id ) ) {
            wp_send_json_error(
                [ 'error' => esc_html__( 'Invalid nonce.', 'searchshifter' ) ],
                403
            );
        }

        // ---- Capability check ----
        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            wp_send_json_error(
                [ 'error' => esc_html__( 'Permission denied.', 'searchshifter' ) ],
                403
            );
        }

        // ---- License check ----
        if ( ! class_exists( 'SS_Licensing' ) || ! SS_Licensing::is_active() ) {
            wp_send_json_error(
                [ 'error' => esc_html__( 'License inactive.', 'searchshifter' ) ],
                403
            );
        }

        // ---- Reset cache / flags ----
        delete_transient( 'ss_last_schema_build_' . $post_id );
        delete_post_meta( $post_id, '_ss_schema_error' );
        delete_post_meta( $post_id, '_ss_schema_attempted' );

        // ---- Force rebuild ----
        if ( class_exists( 'SS_Schema' ) && method_exists( 'SS_Schema', 'generate_schema' ) ) {
            SS_Schema::generate_schema( $post_id );
        } else {
            do_action( 'searchshifter_generate_schema', $post_id );
        }

        // ---- Read result ----
        $json    = (string) get_post_meta( $post_id, self::META_JSON, true );
        $timeout = (int) get_option( '_transient_timeout_ss_last_schema_build_' . $post_id, 0 );
        $left    = max( 0, $timeout - time() );
        $ttl     = $left
            ? sprintf( '%dh %dm', floor( $left / 3600 ), floor( ( $left % 3600 ) / 60 ) )
            : 'not cached';

        if ( $json === '' ) {
            wp_send_json_error(
                [ 'error' => 'build_failed', 'ttl' => $ttl ]
            );
        }

        wp_send_json_success(
            [ 'json' => $json, 'ttl' => $ttl ]
        );
    }


    /** Show one-time success/error notice on the Q&A editor */
    public static function post_notices(){
        if (!function_exists('get_current_screen')) return;
        $s = get_current_screen();
        if (!$s || $s->post_type !== 'ss_qa') return;

        /** @phpcs:disable WordPress.Security.NonceVerification.Recommended */
        // Read-only admin context: current post ID
        $post_id = isset( $_GET['post'] )
            ? absint( wp_unslash( $_GET['post'] ) )
            : 0;
        /** @phpcs:enable WordPress.Security.NonceVerification.Recommended */
        if (!$post_id) return;

        $st = get_transient('ss_schema_status_' . $post_id);
        if (!$st || empty($st['msg'])) return;

        $class = (!empty($st['type']) && $st['type'] === 'success') ? 'updated' : 'error';
        printf(
            '<div class="notice notice-%s"><p>%s</p></div>',
            esc_attr($class),
            esc_html((string) $st['msg'])
        );


        delete_transient('ss_schema_status_' . $post_id);
    }

    /** Tiny CSS */
    private static function css() {
          return <<<'CSS'
        .ssqa-repeater .ssqa-row td { vertical-align: top; }
        #ssqa-json { margin-top:6px; }
        CSS;
    }

            /** Tiny JS (pairs repeater + AJAX build) */
            private static function js() {
                return <<<'JS'
                jQuery(function($){
                    // repeater
                    $('#ssqa-add-row').on('click', function(){
                        var $row = $('<tr class="ssqa-row">\
                            <td><input type="text" name="ssqa[q][]" class="widefat"></td>\
                            <td><textarea name="ssqa[a][]" rows="3" class="widefat"></textarea></td>\
                            <td><button type="button" class="button-link ssqa-del-row" title="Remove"><span class="dashicons dashicons-trash"></span></button></td>\
                        </tr>');
                        $('#ssqa-rows').append($row);
                    });
                    $(document).on('click','.ssqa-del-row', function(){ $(this).closest('tr').remove(); });

                    // copy JSON
                    $('#ssqa-copy-json').on('click', function(){
                        var t = $('#ssqa-json').val();
                        if (!t) return;
                        navigator.clipboard.writeText(t);
                        var $btn = $(this);
                        $btn.prop('disabled', true).text('Copied');
                        setTimeout(function(){ $btn.prop('disabled', false).text('Copy JSON'); }, 900);
                    });

                    // build (AJAX)
                    $('#ssqa-build').on('click', function(){
                        var $btn = $(this);
                        var id   = $btn.data('id');
                        var n    = $('#ssqa-nonce').val();
                        $btn.prop('disabled', true).text('Building…');

                        $.post(ajaxurl, {action:'ss_build_schema', id:id, nonce:n}).done(function(resp){
                            if (resp && resp.success){
                                $('#ssqa-json').val(resp.data.json || '');
                                $('#ssqa-copy-json').prop('disabled', !resp.data.json);
                                $btn.text('Built ✓');
                            } else {
                                var msg = (resp && resp.data && resp.data.error) ? resp.data.error : 'Failed';
                                alert(msg);
                                $btn.text('Build Schema');
                            }
                        }).fail(function(){
                            alert('Request failed');
                            $btn.text('Build Schema');
                        }).always(function(){
                            setTimeout(function(){ $btn.prop('disabled', false).text('Build Schema'); }, 800);
                        });
                    });
                });
                JS;
            }

    
}

add_filter('enter_title_here', function ($title, $post) {
    if ($post->post_type === 'ss_qa') {
        return 'Write the question as a real person would ask (e.g., "What is AI visibility?")';
    }
    return $title;
}, 10, 2);

// ✅ ADD THIS LINE
SS_QA_Admin_UI::init();