<?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> ' . 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 ) {

        // ---- Nonce check ----
        $nonce = isset( $_POST['ssqa_nonce'] )
            ? sanitize_text_field( wp_unslash( $_POST['ssqa_nonce'] ) )
            : '';

        if ( ! $nonce || ! wp_verify_nonce( $nonce, 'ssqa_save_pairs' ) ) {
            return;
        }

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

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

        // ---- Read + unslash ----
        /** @phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized */
        $raw_q = isset( $_POST['ssqa']['q'] ) ? wp_unslash( $_POST['ssqa']['q'] ) : [];
        $raw_a = isset( $_POST['ssqa']['a'] ) ? wp_unslash( $_POST['ssqa']['a'] ) : [];
        /** @phpcs:enable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized */


        // ---- Sanitize arrays explicitly (PHPCS REQUIRED) ----
        $q = [];
        foreach ( (array) $raw_q as $value ) {
            $q[] = sanitize_text_field( $value );
        }

        $a = [];
        foreach ( (array) $raw_a as $value ) {
            $a[] = wp_kses_post( $value );
        }

        // ---- Build output ----
        $out = [];
        $n   = max( count( $q ), count( $a ) );

        for ( $i = 0; $i < $n; $i++ ) {

            $qq = $q[ $i ] ?? '';
            $aa = $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() {

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