<?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']);
    }

    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');
    }

    /** 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');
    }

    /** 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> '.__('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());
        $ttl     = $left ? sprintf(__('%sh %sm left','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>'.__('Cache TTL','searchshifter').':</strong> <code>'.$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 (!isset($_POST['ssqa_nonce']) || !wp_verify_nonce($_POST['ssqa_nonce'],'ssqa_save_pairs')) return;
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
        if (!current_user_can('edit_post',$post_id)) return;

        $q = isset($_POST['ssqa']['q']) ? (array) $_POST['ssqa']['q'] : [];
        $a = isset($_POST['ssqa']['a']) ? (array) $_POST['ssqa']['a'] : [];

        $out = [];
        $n   = max(count($q), count($a));
        for ($i=0; $i<$n; $i++){
            $qq = isset($q[$i]) ? wp_strip_all_tags($q[$i]) : '';
            $aa = isset($a[$i]) ? wp_kses_post($a[$i]) : '';
            if ($qq === '' || $aa === '') continue;
            $out[] = ['q'=>$qq, 'a'=>$aa];
        }
        update_post_meta($post_id, self::META_PAIRS, $out);
    }

    /** AJAX: Build schema NOW (bypass cache) and refresh preview/TTL. */
    // SS_QA_Admin_UI::ajax_build_schema
public static function ajax_build_schema() {
    $post_id = isset($_POST['id']) ? (int) $_POST['id'] : 0;
    $nonce   = isset($_POST['nonce']) ? (string) $_POST['nonce'] : '';
    if (!$post_id || !wp_verify_nonce($nonce,'ssqa_build_'.$post_id)) wp_send_json_error(['error'=>'bad_nonce'], 403);
    if (!current_user_can('edit_post', $post_id)) wp_send_json_error(['error'=>'forbidden'], 403);

    if (!class_exists('SS_Licensing') || !SS_Licensing::is_active()) {
        wp_send_json_error(['error'=>'readonly'], 403);
    }

    // Drop only cache & error flags; keep last-known-good JSON
    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 (DOING_AJAX makes generate_schema bypass cache)
    if (class_exists('SS_Schema') && method_exists('SS_Schema','generate_schema')) {
        SS_Schema::generate_schema($post_id);
    } else {
        do_action('ss_generate_schema', $post_id);
    }

    // Read whatever is currently stored (new or preserved)
    $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;

        $post_id = isset($_GET['post']) ? (int) $_GET['post'] : 0;
        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($st['msg']));

        delete_transient('ss_schema_status_' . $post_id);
    }

//     public static function show_schema_error_notice() {
//     if (!function_exists('get_current_screen')) return;
//     $s = get_current_screen();
//     if (!$s) return;

//     // Only on the Q&A edit screen (NOT on post-new.php)
//     if ($s->base !== 'post' || $s->post_type !== 'ss_qa') return;

//     $post_id = isset($_GET['post']) ? (int) $_GET['post'] : 0;
//     if ($post_id <= 0) return; // hide on "Add New" where no ID exists yet

//     // If we already have JSON saved, hide the error banner
//     $json = get_post_meta($post_id, '_ss_schema_json', true);
//     if (!empty($json)) return;

//     $err = get_post_meta($post_id, '_ss_schema_error', true);
//     if (!$err) return;

//     printf(
//         '<div class="notice notice-error"><p>%s: <code>%s</code></p></div>',
//         esc_html__('Schema build failed', 'searchshifter'),
//         esc_html($err)
//     );
// }


    /** 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;
    }
}
