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

$searchshifter_faq_items = get_option( 'ss_faq_items', array() );

if ( isset( $_POST['ss_save_faq_item'] ) ) {

    // 🔐 Nonce verification (PHPCS-safe)
    if (
        ! isset( $_POST['ss_faq_nonce'] ) ||
        ! wp_verify_nonce(
            sanitize_text_field( wp_unslash( $_POST['ss_faq_nonce'] ) ),
            'ss_save_faq_item'
        )
    ) {
        return;
    }

    // 🧼 Initialize prefixed variables
    $searchshifter_question = '';
    $searchshifter_answer   = '';

    if ( isset( $_POST['question'] ) ) {
        $searchshifter_question = sanitize_text_field(
            wp_unslash( $_POST['question'] )
        );
    }

    if ( isset( $_POST['answer'] ) ) {
        $searchshifter_answer = sanitize_textarea_field(
            wp_unslash( $_POST['answer'] )
        );
    }

    if ( ! $searchshifter_question || ! $searchshifter_answer ) {
        return;
    }

    // 📦 Load existing FAQ items safely
    $searchshifter_faq_items = get_option( 'ss_faq_items', array() );

    $searchshifter_faq_items[] = array(
        'question' => $searchshifter_question,
        'answer'   => $searchshifter_answer,
    );

    update_option( 'ss_faq_items', $searchshifter_faq_items );
}


if (isset($_GET['delete'])) {
    unset($searchshifter_faq_items[(int) $_GET['delete']]);
    update_option('ss_faq_items', $faq_items);
}
?>
<div class="wrap">
    <h1>FAQ Manager</h1>
    <form method="post">
        <?php wp_nonce_field('save_faq_item'); ?>
        <table>
            <tr><td><input type="text" name="question" placeholder="Question" required style="width:400px;"></td></tr>
            <tr><td><textarea name="answer" placeholder="Answer" style="width:400px;height:100px;"></textarea></td></tr>
        </table>
        <?php submit_button('Add FAQ'); ?>
    </form>

    <h2>Current FAQs</h2>
    <table class="widefat striped">
        <thead><tr><th>Question</th><th>Answer</th><th>Actions</th></tr></thead>
        <tbody>
        <?php foreach ( $searchshifter_faq_items as $searchshifter_index => $searchshifter_faq_item ) : ?>
            <tr>
              <td><?php echo esc_html( $faq['question'] ); ?></td>
<td><?php echo esc_html( $faq['answer'] ); ?></td>


              <td>
                <a href="<?php echo esc_url( add_query_arg(
                    array(
                        'page'   => 'searchshifter-faq',
                        'delete' => $i,
                    ),
                    admin_url( 'admin.php' )
                ) ); ?>">
                    Delete
                </a>
            </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>
