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

class SS_Glossary_Limit {

    const MAX_FREE_TERMS = 10;

    public static function init() {

        add_action('admin_init', [__CLASS__, 'block_new_term']);
        add_action('admin_notices', [__CLASS__, 'show_message']);
        add_action('admin_head', [__CLASS__, 'hide_add_new_buttons']);

        // Hide or replace sidebar menu item
        add_action('admin_menu', [__CLASS__, 'maybe_lock_sidebar_menu'], 99);
    }

    // 1. Block direct access to: post-new.php?post_type=ss_glossary
    public static function block_new_term() {

        if ( ! self::is_free_plan() ) {
            return;
        }

        $count = (int) wp_count_posts( 'ss_glossary' )->publish;

        if ( $count < self::MAX_FREE_TERMS ) {
            return;
        }

        /** @phpcs:disable WordPress.Security.NonceVerification.Recommended */
        $post_type = isset( $_GET['post_type'] )
            ? sanitize_key( wp_unslash( $_GET['post_type'] ) )
            : '';

        $action = isset( $_GET['action'] )
            ? sanitize_key( wp_unslash( $_GET['action'] ) )
            : '';
        /** @phpcs:enable WordPress.Security.NonceVerification.Recommended */

        if ( $post_type === 'ss_glossary' && $action === 'add' ) {
            wp_safe_redirect(
                admin_url( 'edit.php?post_type=ss_glossary&term_limit=1' )
            );
            exit;
        }
    }


        // 2. Show friendly usage message
    public static function show_message() {

        if ( ! self::is_free_plan() ) {
            return;
        }

        $count = (int) wp_count_posts( 'ss_glossary' )->publish;

        /** @phpcs:disable WordPress.Security.NonceVerification.Recommended */
        $post_type = isset( $_GET['post_type'] )
            ? sanitize_key( wp_unslash( $_GET['post_type'] ) )
            : '';
        /** @phpcs:enable WordPress.Security.NonceVerification.Recommended */

        if ( $post_type !== 'ss_glossary' ) {
            return;
        }

        $remaining = max( 0, self::MAX_FREE_TERMS - $count );

        echo '<div class="notice notice-info is-dismissible">
            <p>
                <strong>Glossary Usage:</strong> You can add 
                <strong>' . esc_html( $remaining ) . '</strong> more glossary terms 
                out of your Free plan limit of <strong>' . esc_html( self::MAX_FREE_TERMS ) . '</strong>.
            </p>
        </div>';
    }


    // 3. Hide Add New buttons in list screen
    public static function hide_add_new_buttons() {

        if (!self::is_free_plan()) return;

        $count = (int) wp_count_posts('ss_glossary')->publish;

        if ($count < self::MAX_FREE_TERMS) return;

        echo "<style>
            .page-title-action { display:none !important; }
            /* Hide submenu 'Add New Term' */
            #adminmenu a[href*='post-new.php?post_type=ss_glossary'] {
                display:none !important;
            }
        </style>";
    }

    // 4. Replace sidebar menu with locked upgrade link
    public static function maybe_lock_sidebar_menu() {

        if (!self::is_free_plan()) return;

        global $submenu;

        $count = (int) wp_count_posts('ss_glossary')->publish;

        if ($count < self::MAX_FREE_TERMS) return;

        if (isset($submenu['edit.php?post_type=ss_glossary'])) {
            foreach ($submenu['edit.php?post_type=ss_glossary'] as $key => $item) {

                if (strpos($item[2], 'post-new.php?post_type=ss_glossary') !== false) {

                    // Replace with LOCKED menu item
                    $submenu['edit.php?post_type=ss_glossary'][$key] = [
                        '🔒 Add New Term (Upgrade Required)',
                        'manage_options',
                        'https://searchshifter.ai/pricing',
                    ];
                }
            }
        }
    }

    private static function is_free_plan() {

        if (!class_exists('SS_Licensing')) return true;

        $license = SS_Licensing::get_cached_status();
        $plan = strtolower($license['plan'] ?? 'free');

        return ($plan === 'free');
    }
}
