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

/**
 * Hide all other plugin notices on Glossary page
 */
add_action( 'admin_init', function () {

    add_action( 'in_admin_header', function () {
        global $wp_filter;

        $page = isset( $_GET['page'] )
            ? sanitize_text_field( wp_unslash( $_GET['page'] ) )
            : '';

        if ( 'searchshifter-glossary' !== $page ) {
            return;
        }

        if (
            ! isset( $_GET['_wpnonce'] ) ||
            ! wp_verify_nonce(
                sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ),
                'searchshifter_glossary_page'
            )
        ) {
            return;
        }

        unset( $wp_filter['admin_notices'] );
        unset( $wp_filter['all_admin_notices'] );
    }, 1 );

    /* ---------------------------
       LOAD GLOSSARY
    ---------------------------- */
    $searchshifter_option_key = 'ss_glossary_terms';
    $searchshifter_glossary   = get_option( $searchshifter_option_key, [] );

    /* ---------------------------
       DELETE TERM (already correct)
    ---------------------------- */
    if (
        isset( $_GET['delete'], $_GET['_wpnonce'] ) &&
        wp_verify_nonce(
            sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ),
            'searchshifter_delete_glossary'
        )
    ) {
        $searchshifter_index = absint( $_GET['delete'] );

        if ( isset( $searchshifter_glossary[ $searchshifter_index ] ) ) {
            unset( $searchshifter_glossary[ $searchshifter_index ] );

            update_option(
                $searchshifter_option_key,
                array_values( $searchshifter_glossary )
            );

            echo '<div class="notice notice-success is-dismissible">
                    <p><strong>Deleted successfully.</strong></p>
                </div>';
        }
    }


} );


/* ---------------------------
   ADD / EDIT TERM
---------------------------- */
if ( isset( $_POST['ss_save_glossary'] ) ) {

    // 🔐 Nonce verification
    if (
        ! isset( $_POST['ss_glossary_nonce'] ) ||
        ! wp_verify_nonce(
            sanitize_text_field( wp_unslash( $_POST['ss_glossary_nonce'] ) ),
            'ss_glossary_nonce_action'
        )
    ) {
        return;
    }

    // 🧼 Initialize variables (avoid undefined + global warnings)
    $searchshifter_term        = '';
    $searchshifter_definition  = '';
    $searchshifter_same_as     = '';
    $searchshifter_edit_index  = -1;

    if ( isset( $_POST['term'] ) ) {
        $searchshifter_term = sanitize_text_field(
            wp_unslash( $_POST['term'] )
        );
    }

    if ( isset( $_POST['definition'] ) ) {
        $searchshifter_definition = sanitize_textarea_field(
            wp_unslash( $_POST['definition'] )
        );
    }

    if ( isset( $_POST['same_as'] ) ) {
        $searchshifter_same_as = esc_url_raw(
            wp_unslash( $_POST['same_as'] )
        );
    }

    if ( isset( $_POST['edit_index'] ) ) {
        $searchshifter_edit_index = absint(
            wp_unslash( $_POST['edit_index'] )
        );
    }

    if ( $searchshifter_term && $searchshifter_definition ) {

        $searchshifter_entry = array(
            'term'       => $searchshifter_term,
            'definition' => $searchshifter_definition,
            'same_as'    => $searchshifter_same_as,
        );

        if (
            $searchshifter_edit_index >= 0 &&
            isset( $glossary[ $searchshifter_edit_index ] )
        ) {
            // UPDATE
            $searchshifter_glossary[ $searchshifter_edit_index ] = $searchshifter_entry;

            echo '<div class="notice notice-success is-dismissible">
                    <p><strong>Glossary term updated.</strong></p>
                  </div>';

        } else {
            // ADD NEW
            if ( $is_pro ) {

                // PRO = unlimited
                $searchshifter_glossary[] = $searchshifter_entry;

                echo '<div class="notice notice-success is-dismissible">
                        <p><strong>Glossary term added.</strong></p>
                      </div>';

            } else {

                // FREE = max 10
                if ( count( $searchshifter_glossary ) < 10 ) {

                    $searchshifter_glossary[] = $searchshifter_entry;

                    echo '<div class="notice notice-success is-dismissible">
                            <p><strong>Glossary term added.</strong></p>
                          </div>';

                } else {

                    echo '<div class="notice notice-warning is-dismissible">
                            <p><strong>Free version limit reached (10 terms).</strong></p>
                          </div>';
                }
            }
        }

        update_option( $option_key, $searchshifter_glossary );

    } else {

        echo '<div class="notice notice-error is-dismissible">
                <p><strong>Please enter both a Term and Definition.</strong></p>
              </div>';
    }
}


/* ---------------------------
   EDIT MODE
---------------------------- */
$searchshifter_edit_item = null;

if ( isset( $_GET['edit'] ) ) {

    $searchshifter_edit_index = absint( $_GET['edit'] );

    if ( $searchshifter_edit_index >= 0 ) {

        $searchshifter_glossary = get_option( $option_key, array() );

        if ( isset( $searchshifter_glossary[ $searchshifter_edit_index ] ) ) {

            $searchshifter_edit_item           = $searchshifter_glossary[ $searchshifter_edit_index ];
            $searchshifter_edit_item['index']  = $searchshifter_edit_index;
        }
    }
}
?>

<style>
#wpbody-content { padding-right: 0 !important; }

.ss-glossary-wrap { padding: 0 20px 40px; }

.ss-glossary-form {
    background: #fff;
    border: 1px solid #ccd0d4;
    padding: 20px;
    border-radius: 6px;
    margin-bottom: 25px;
}

.ss-glossary-form input, 
.ss-glossary-form textarea {
    width: 100%;
    padding: 7px;
    margin-bottom: 10px;
}

.ss-glossary-table tbody tr:hover {
    background: #f9f9f9;
}
</style>

<div class="wrap ss-glossary-wrap">

    <h1 class="ss-glossary-title">
        <span class="dashicons dashicons-book-alt" style="color:#2271b1;font-size:22px;"></span>
        SearchShifter™ Glossary 
        <small style="font-weight:400;color:#777;">
         (<?php
            echo esc_html(
                $is_pro
                    ? __( 'Pro Version', 'searchshifter' )
                    : __( 'Free Version', 'searchshifter' )
            );
        ?>)

        </small>
    </h1>

    <!-- ADD BUTTON -->
    <?php if (!$edit_item && ($is_pro || count($glossary) < 10)): ?>
        <p><a href="#add" class="button button-primary">+ Add New Term</a></p>
    <?php endif; ?>

    <!-- Notices (Free Only) -->
    <?php if (!$is_pro): ?>

        <?php if (count($glossary) >= 10): ?>
            <div class="notice notice-warning">
                <p><strong>You’ve reached the 10-term limit for Free version.</strong><br>
                Upgrade to PRO for unlimited glossary entries.</p>
            </div>

        <?php else: ?>
            <div class="notice notice-info">
                <p>
                    <?php
                    printf(
                        /* translators: %d: number of remaining glossary terms */
                        esc_html__( 'You can add %d more terms in Free version.', 'searchshifter' ),
                        esc_html( 10 - count( $searchshifter_glossary ) )
                    );
                    ?>
                </p>
            </div>
        <?php endif; ?>

    <?php endif; ?>

    <!-- ADD / EDIT FORM -->
    <div id="add" class="ss-glossary-form">
      <h2>
            <?php
            echo esc_html(
                $edit_item
                    ? __( 'Edit Term', 'searchshifter' )
                    : __( 'Add New Term', 'searchshifter' )
            );
            ?>
      </h2>


        <form method="post">
            <?php wp_nonce_field('ss_glossary_nonce_action', 'ss_glossary_nonce'); ?>

            <label>Term</label>
            <input type="text" name="term" required 
                   value="<?php echo $edit_item ? esc_attr( $edit_item['term'] ) : ''; ?>">


            <label>Definition</label>
            <textarea name="definition" rows="3" required><?php echo $edit_item ? esc_textarea( $edit_item['definition'] ) : ''; ?></textarea>

            <label>SameAs (Optional)</label>
            <input type="url" name="same_as" 
                   value="<?php echo $edit_item ? esc_attr( $edit_item['same_as'] ) : ''; ?>"
                   placeholder="https://example.com">

            <?php if ($edit_item): ?>
               <input type="hidden" name="edit_index" value="<?php echo esc_attr( $edit_item['index'] ); ?>">
            <?php endif; ?>

            <?php submit_button($edit_item ? 'Update Term' : 'Add Term', 'primary', 'ss_save_glossary'); ?>
        </form>
    </div>

    <!-- GLOSSARY TABLE -->
    <h2>Glossary Terms</h2>

<?php if ( ! empty( $glossary ) ) : ?>
    <table class="widefat fixed striped ss-glossary-table">
        <thead>
            <tr>
                <th>#</th>
                <th><?php esc_html_e( 'Term', 'searchshifter' ); ?></th>
                <th><?php esc_html_e( 'Definition', 'searchshifter' ); ?></th>
                <th><?php esc_html_e( 'SameAs', 'searchshifter' ); ?></th>
                <th><?php esc_html_e( 'Actions', 'searchshifter' ); ?></th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ( $searchshifter_glossary as $searchshifter_index => $searchshifter_item ) : ?>

                <?php
                $searchshifter_edit_url = add_query_arg(
                    array(
                        'page' => 'searchshifter-glossary',
                        'edit' => $searchshifter_index,
                    ),
                    admin_url( 'admin.php' )
                );

                $searchshifter_delete_url = wp_nonce_url(
                    add_query_arg(
                        array(
                            'page'   => 'searchshifter-glossary',
                            'delete' => $searchshifter_index,
                        ),
                        admin_url( 'admin.php' )
                    ),
                    'searchshifter_delete_glossary'
                );
                ?>


                <tr>
                    <td><strong><?php echo esc_html( $i + 1 ); ?></strong></td>

                    <td>
                        <strong><?php echo esc_html( $item['term'] ); ?></strong>
                    </td>

                    <td>
                        <?php echo esc_html( $item['definition'] ); ?>
                    </td>

                    <td>
                        <?php if ( ! empty( $item['same_as'] ) ) : ?>
                            <a href="<?php echo esc_url( $item['same_as'] ); ?>" target="_blank" rel="noopener noreferrer">
                                <?php echo esc_html( $item['same_as'] ); ?>
                            </a>
                        <?php else : ?>
                            <em>—</em>
                        <?php endif; ?>
                    </td>

                    <td>
                        <a href="<?php echo esc_url( $edit_url ); ?>" class="button button-small">
                            <?php esc_html_e( 'Edit', 'searchshifter' ); ?>
                        </a>

                        <a href="<?php echo esc_url( $delete_url ); ?>"
                           onclick="return confirm('<?php echo esc_js( __( 'Delete this term?', 'searchshifter' ) ); ?>');"
                           class="button button-small button-link-delete">
                            <?php esc_html_e( 'Delete', 'searchshifter' ); ?>
                        </a>
                    </td>
                </tr>

            <?php endforeach; ?>
        </tbody>
    </table>

<?php else : ?>
    <p><?php esc_html_e( 'No glossary terms yet.', 'searchshifter' ); ?></p>
<?php endif; ?>

</div>
