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

/**
 * Hide all other plugin notices on Glossary page
 */
add_action('in_admin_header', function() {
    global $wp_filter;

    if (isset($_GET['page']) && $_GET['page'] === 'searchshifter-glossary') {
        unset($wp_filter['admin_notices']);
        unset($wp_filter['all_admin_notices']);
    }
}, 1);

// Load glossary
$option_key = 'ss_glossary_terms';
$glossary   = get_option($option_key, []);

// Load license (Pro / Free detection)
$license      = SS_Licensing::get_cached_status();
$current_plan = strtolower($license['plan'] ?? 'free');
$is_pro       = in_array($current_plan, ['pro','authority','elite'], true);

/* ---------------------------
   DELETE TERM
---------------------------- */
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $index = (int) $_GET['delete'];
    if (isset($glossary[$index])) {
        unset($glossary[$index]);
        $glossary = array_values($glossary);
        update_option($option_key, $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'])) {
    check_admin_referer('ss_glossary_nonce_action', 'ss_glossary_nonce');

    $term        = sanitize_text_field($_POST['term']);
    $definition  = sanitize_textarea_field($_POST['definition']);
    $same_as     = esc_url_raw($_POST['same_as']);
    $edit_index  = isset($_POST['edit_index']) ? (int)$_POST['edit_index'] : -1;

    if ($term && $definition) {
        $entry = compact('term','definition','same_as');

        if ($edit_index >= 0 && isset($glossary[$edit_index])) {
            // Update term
            $glossary[$edit_index] = $entry;
            echo '<div class="notice notice-success is-dismissible"><p><strong>Glossary term updated.</strong></p></div>';

        } else {
            // ADD NEW TERM
            if ($is_pro) {
                // PRO = unlimited
                $glossary[] = $entry;
                echo '<div class="notice notice-success is-dismissible"><p><strong>Glossary term added.</strong></p></div>';

            } else {
                // FREE = max 10
                if (count($glossary) < 10) {
                    $glossary[] = $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, $glossary);

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

/* ---------------------------
   EDIT MODE
---------------------------- */
$edit_item = null;
if (isset($_GET['edit']) && is_numeric($_GET['edit'])) {
    $index = (int) $_GET['edit'];
    if (isset($glossary[$index])) {
        $edit_item = $glossary[$index];
        $edit_item['index'] = $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;">
            (<?= $is_pro ? 'Pro Version' : 'Free Version' ?>)
        </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>You can add <strong><?= 10 - count($glossary) ?></strong> more terms in Free version.</p>
            </div>
        <?php endif; ?>

    <?php endif; ?>

    <!-- ADD / EDIT FORM -->
    <div id="add" class="ss-glossary-form">
        <h2><?= $edit_item ? 'Edit Term' : 'Add New Term' ?></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="<?= $edit_item ? esc_attr($edit_item['term']) : '' ?>">

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

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

            <?php if ($edit_item): ?>
                <input type="hidden" name="edit_index" value="<?= $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>Term</th>
                    <th>Definition</th>
                    <th>SameAs</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($glossary as $i => $item): ?>
                    <tr>
                        <td><strong><?= $i + 1 ?></strong></td>
                        <td><strong><?= esc_html($item['term']) ?></strong></td>
                        <td><?= esc_html($item['definition']) ?></td>
                        <td>
                            <?php if ($item['same_as']): ?>
                                <a href="<?= esc_url($item['same_as']) ?>" target="_blank"><?= esc_html($item['same_as']) ?></a>
                            <?php else: ?>
                                <em>—</em>
                            <?php endif; ?>
                        </td>
                        <td>
                            <a href="?page=searchshifter-glossary&edit=<?= $i ?>" class="button button-small">Edit</a>
                            <a href="?page=searchshifter-glossary&delete=<?= $i ?>" 
                               onclick="return confirm('Delete this term?');"
                               class="button button-small button-link-delete">Delete</a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

    <?php else: ?>
        <p>No glossary terms yet.</p>
    <?php endif; ?>
</div>
