<?php

/**
 * Plugin Name:         The 9 Dollar Menu Valet
 * Plugin URI:          https://www.the-9-dollar-plugins.com/
 * Description:         Hide and reorder your WordPress admin menu items — no code required. Clean up the sidebar in seconds.
 * Version:             1.4
 * Author:              The 9 Dollar Plugins
 * Author URI:          https://www.the-9-dollar-plugins.com
 * License:             GPLv2 or later
 * License URI:         https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * Text Domain:         the-9-dollar-menu-valet
 * Domain Path:         /languages
 * Requires at least:   5.5
 * Requires PHP:        7.4
 *
 * Commercial License: See terms.txt for commercial terms of use
 */
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}
// ── Freemius bootstrap ────────────────────────────────────────────────────────
if ( ! function_exists( 't9p_tmv_fs' ) ) {
    // Create a helper function for easy SDK access.
    function t9p_tmv_fs() {
        global $t9p_tmv_fs;
        if ( ! isset( $t9p_tmv_fs ) ) {
            // Include Freemius SDK.
            require_once dirname( __FILE__ ) . '/vendor/freemius/start.php';
            $t9p_tmv_fs = fs_dynamic_init( array(
                    'id'               => '25644',
                    'slug'             => 'the-9-dollar-menu-valet',
                    'premium_slug'     => 'the-9-dollar-menu-valet-pro',
                    'type'             => 'plugin',
                    'public_key'       => 'pk_a95ca81216c79a4101a925bb093f5',
                    'is_premium'       => false,
                    'premium_suffix'   => 'PRO',
                    'has_addons'       => false,
                    'has_paid_plans'   => true,
                    'is_org_compliant' => true,
                    'has_affiliation'  => 'all',
                    'menu'             => array(
                            'slug'    => 'the-9-dollar-menu-valet',
                            'support' => false,
                    ),
                    'is_live'          => true,
            ) );
        }

        return $t9p_tmv_fs;
    }

    // Init Freemius.
    t9p_tmv_fs();
    // Signal that SDK was initiated.
    do_action( 't9p_tmv_fs_loaded' );
}
// ── Constants ─────────────────────────────────────────────────────────────
define( 'T9P_TMV_VERSION', '1.4' );
define( 'T9P_TMV_PLUGIN_FILE', __FILE__ );
define( 'T9P_TMV_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'T9P_TMV_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
define( 'T9P_TMV_OPTION_KEY', 't9p_tmv_settings' );
define( 'T9P_TMV_SLUG', 'the-9-dollar-menu-valet' );

// ── Lifecycle: activation, deactivation ───────────────────────────────────
register_activation_hook( T9P_TMV_PLUGIN_FILE, 't9p_tmv_activate' );
register_deactivation_hook( T9P_TMV_PLUGIN_FILE, 't9p_tmv_deactivate' );
function t9p_tmv_activate() {
    if ( ! get_option( T9P_TMV_OPTION_KEY ) ) {
        add_option( T9P_TMV_OPTION_KEY, array(
                'hidden_items'        => array(),
                'menu_order'          => array(),
                'delete_on_uninstall' => false,
        ) );
    }
    if ( ! get_option( 't9p_tmv_activated_at' ) ) {
        add_option( 't9p_tmv_activated_at', time(), '', 'no' );
    }
}

function t9p_tmv_deactivate() {
}

// ── Uninstall ─────────────────────────────────────────────────────────────
t9p_tmv_fs()->add_action( 'after_uninstall', 't9p_tmv_fs_uninstall_cleanup' );
function t9p_tmv_fs_uninstall_cleanup() {
    delete_option( 't9p_tmv_activated_at' );
    delete_option( 't9p_tmv_review_dismissed' );
    $settings = get_option( T9P_TMV_OPTION_KEY, array() );
    if ( empty( $settings['delete_on_uninstall'] ) ) {
        return;
    }
    if ( ! is_multisite() ) {
        t9p_tmv_delete_all_data();
    } else {
        foreach (
                get_sites( array(
                        'fields' => 'ids',
                        'number' => 0,
                ) ) as $site_id
        ) {
            switch_to_blog( $site_id );
            t9p_tmv_delete_all_data();
            restore_current_blog();
        }
    }
}

function t9p_tmv_delete_all_data() {
    global $wpdb;
    delete_option( T9P_TMV_OPTION_KEY );
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s", $wpdb->esc_like( '_transient_t9p_tmv_' ) . '%', $wpdb->esc_like( '_transient_timeout_t9p_tmv_' ) . '%' ) );
}

// ── Settings ──────────────────────────────────────────────────────────────
/** @return array */
function t9p_tmv_get_settings() {
    $defaults = array(
            'hidden_items'        => array(),
            'menu_order'          => array(),
            'delete_on_uninstall' => false,
    );

    return wp_parse_args( get_option( T9P_TMV_OPTION_KEY, array() ), $defaults );
}

function t9p_tmv_save_settings( array $settings ) {
    return update_option( T9P_TMV_OPTION_KEY, $settings, false );
}

// ── Apply settings to live admin menu ─────────────────────────────────────
global $t9p_tmv_menu_snapshot_raw;
$t9p_tmv_menu_snapshot_raw = array();
add_action( 'admin_menu', 't9p_tmv_capture_menu_snapshot', 9998 );
function t9p_tmv_capture_menu_snapshot() {
    global $menu, $submenu, $t9p_tmv_menu_snapshot_raw;
    $t9p_tmv_menu_snapshot_raw = array(
            'menu'    => $menu,
            'submenu' => $submenu,
    );
}

add_action( 'admin_menu', 't9p_tmv_apply_hidden_items', 9999 );
function t9p_tmv_apply_hidden_items() {
    global $menu, $submenu;
    $hidden_items = t9p_tmv_get_settings()['hidden_items'] ?? array();
    if ( empty( $hidden_items ) ) {
        return;
    }
    foreach ( $menu as $pos => $item ) {
        if ( in_array( $item[2] ?? '', $hidden_items, true ) ) {
            unset( $menu[ $pos ] );
        }
    }
    foreach ( $hidden_items as $slug ) {
        if ( strpos( $slug, 'sub::' ) !== 0 ) {
            unset( $submenu[ $slug ] );
        }
    }
    foreach ( $submenu as $parent_slug => $subs ) {
        foreach ( $subs as $pos => $sub ) {
            if ( in_array( 'sub::' . ( $sub[2] ?? '' ), $hidden_items, true ) ) {
                unset( $submenu[ $parent_slug ][ $pos ] );
            }
        }
    }
}

add_filter( 'custom_menu_order', '__return_true' );
add_filter( 'menu_order', 't9p_tmv_filter_menu_order' );
/**
 * Returns saved order merged with any newly registered slugs.
 *
 * @param array $default
 *
 * @return array
 */
function t9p_tmv_filter_menu_order( $default ) {
    $menu_order = t9p_tmv_get_settings()['menu_order'] ?? array();
    if ( empty( $menu_order ) ) {
        return $default;
    }
    $merged = $menu_order;
    foreach ( $default as $slug ) {
        if ( ! in_array( $slug, $merged, true ) ) {
            $merged[] = $slug;
        }
    }

    return $merged;
}

// ── Admin menu registration ───────────────────────────────────────────────
add_action( 'admin_menu', 't9p_tmv_register_menu' );
function t9p_tmv_register_menu() {
    add_menu_page( __( 'Menu Valet', 'the-9-dollar-menu-valet' ), __( 'Menu Valet', 'the-9-dollar-menu-valet' ), 'manage_options', 'the-9-dollar-menu-valet', 't9p_tmv_render_admin_page', 'data:image/svg+xml;base64,' . base64_encode( '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path fill="#a7aaad" d="M4 4h6v2H4V4zm0 5h6v2H4V9zm0 5h6v2H4v-2zM14 3l3 3h-2v3h-2V6h-2l3-3zm0 14l-3-3h2v-3h2v3h2l-3 3z"/></svg>' ), 26 );
}

// ── Assets ────────────────────────────────────────────────────────────────
add_action( 'admin_head', function () {
    $screen = get_current_screen();
    if ( ! $screen || $screen->id !== 'toplevel_page_the-9-dollar-menu-valet' ) {
        return;
    }
    include T9P_TMV_PLUGIN_DIR . 'assets/icons.svg';
} );
add_action( 'admin_enqueue_scripts', 't9p_tmv_enqueue_assets' );
/** @param string $hook */
function t9p_tmv_enqueue_assets( $hook ) {
    if ( 'toplevel_page_the-9-dollar-menu-valet' !== $hook ) {
        return;
    }
    wp_enqueue_style( 't9p-tmv-style', T9P_TMV_PLUGIN_URL . 't9p-tmv-style.css', array(), filemtime( T9P_TMV_PLUGIN_DIR . 't9p-tmv-style.css' ) );
    wp_enqueue_script( 'jquery-ui-sortable' );
    wp_enqueue_script( 't9p-tmv-script', T9P_TMV_PLUGIN_URL . 't9p-tmv-script.js', array(
            'jquery',
            'jquery-ui-sortable'
    ), filemtime( T9P_TMV_PLUGIN_DIR . 't9p-tmv-script.js' ), true );
    wp_localize_script( 't9p-tmv-script', 't9pTmvValet', array(
            'ajax_url'    => admin_url( 'admin-ajax.php' ),
            'nonce'       => wp_create_nonce( 't9p_tmv_nonce' ),
            'menu_width'  => (int) ( t9p_tmv_get_settings()['menu_width'] ?? 0 ),
            'text_saved'  => __( 'Settings saved.', 'the-9-dollar-menu-valet' ),
            'text_error'  => __( 'An error occurred. Please try again.', 'the-9-dollar-menu-valet' ),
            'text_saving' => __( 'Saving…', 'the-9-dollar-menu-valet' ),
            'text_rename' => __( 'Rename', 'the-9-dollar-menu-valet' ),
            'text_save'   => __( 'Save', 'the-9-dollar-menu-valet' ),
    ) );
}

// ── Admin page renderer ───────────────────────────────────────────────────
function t9p_tmv_render_admin_page() {
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'the-9-dollar-menu-valet' ) );
    }
    $settings            = t9p_tmv_get_settings();
    $hidden_items        = $settings['hidden_items'] ?? array();
    $saved_order         = $settings['menu_order'] ?? array();
    $delete_on_uninstall = ! empty( $settings['delete_on_uninstall'] );
    global $menu, $submenu, $t9p_tmv_menu_snapshot_raw;
    $raw_menu      = $t9p_tmv_menu_snapshot_raw['menu'] ?? $menu;
    $raw_submenu   = $t9p_tmv_menu_snapshot_raw['submenu'] ?? $submenu;
    $menu_snapshot = t9p_tmv_build_menu_snapshot( $raw_menu, $raw_submenu, $saved_order );
    ?>

    <div class="wrap">
        <div class="t9p-tmv-header">
            <h1>
                <?php esc_html_e( 'The 9 Dollar Menu Valet', 'the-9-dollar-menu-valet' ); ?>
            </h1>
            <div class="t9p-tmv-logo"><a href="https://www.the-9-dollar-plugins.com/?tmv=1" target="_blank"
                                         rel="noopener noreferrer"> <img src="<?php
                    echo esc_url( T9P_TMV_PLUGIN_URL . 'assets/the-9-dollar-plugins.png' ); ?>" width="300" height="300"
                                                                         alt="The 9 Dollar Plugins"> </a></div>
        </div>
        <div class="t9p-tmv-topforms-grid">
            <?php
            if ( t9p_tmv_fs()->is_not_paying() ) {
                ?>
                <div class="t9p-tmv-topform-style">
                    <p><span class="t9p-tmv-pro-bagde">PRO</span>
                        <?php
                        esc_html_e( 'Adds a live search field to the very top of your WordPress admin sidebar. Start typing to instantly filter all menu and submenu items — ideal for sites with many plugins and a long admin menu.', 'the-9-dollar-menu-valet' );
                        ?>
                    </p>
                </div>
                <div class="t9p-tmv-topform-style">
                    <label>
                        <?php
                        esc_html_e( 'Live search in admin menu', 'the-9-dollar-menu-valet' );
                        ?>
                    </label>
                    <select disabled="disabled" class="t9p-tmv-topform-style">
                        <option>
                            <?php
                            esc_html_e( 'Show live search in menu', 'the-9-dollar-menu-valet' );
                            ?>
                        </option>
                    </select>
                    <p><a href="<?php
                        echo esc_url( t9p_tmv_fs()->checkout_url() );
                        ?>" class="t9p-tmv-upsell-link" rel="noopener noreferrer">
                            <?php
                            esc_html_e( 'Unlock with PRO', 'the-9-dollar-menu-valet' );
                            ?>
                        </a></p>
                </div>
                <div class="t9p-tmv-topforms-divider"></div>
                <div class="t9p-tmv-topform-style">
                    <p><span class="t9p-tmv-pro-bagde">PRO</span>
                        <?php
                        esc_html_e( 'Adjusts the width of your WordPress admin sidebar beyond the default 160 px. Drag the slider to find the perfect fit for your screen — especially useful when plugin menu labels are long or wrap to a second line. Changes apply immediately across your entire admin area.', 'the-9-dollar-menu-valet' );
                        ?>
                    </p>
                </div>
                <div class="t9p-tmv-topform-style">
                    <label>
                        <?php
                        esc_html_e( 'Custom Sidebar Width', 'the-9-dollar-menu-valet' );
                        ?>
                    </label>
                    <div class="t9p-tmv-width-wrap t9p-tmv-width-disabled">
                        <input type="range" class="t9p-tmv-width-slider" min="160" max="380" step="1" value="160"
                               disabled>
                        <span class="t9p-tmv-width-value">160px</span></div>
                    <p><a href="<?php
                        echo esc_url( t9p_tmv_fs()->checkout_url() );
                        ?>" class="t9p-tmv-upsell-link" rel="noopener noreferrer">
                            <?php
                            esc_html_e( 'Unlock with PRO', 'the-9-dollar-menu-valet' );
                            ?>
                        </a></p>
                </div>
                <div class="t9p-tmv-topforms-divider"></div>
                <?php
            }
            ?>
            <div class="t9p-tmv-topform-style">
                <p>
                    <?php
                    esc_html_e( 'If set to "Yes", all plugin data — including saved settings, hidden items and custom menu order — will be permanently and irreversibly deleted from the database when the plugin is uninstalled. This cannot be undone.', 'the-9-dollar-menu-valet' );
                    ?>
                </p>
            </div>
            <div class="t9p-tmv-topform-style">
                <label for="t9p-tmv-delete-select">
                    <?php
                    esc_html_e( 'Delete data on uninstall', 'the-9-dollar-menu-valet' );
                    ?>
                </label>
                <select id="t9p-tmv-delete-select" class="t9p-tmv-topform-style">
                    <option value="0" <?php
                    selected( $delete_on_uninstall, false );
                    ?>>
                        <?php
                        esc_html_e( 'No — keep data in database', 'the-9-dollar-menu-valet' );
                        ?>
                    </option>
                    <option value="1" <?php
                    selected( $delete_on_uninstall, true );
                    ?>>
                        <?php
                        esc_html_e( 'Yes — delete everything irreversibly', 'the-9-dollar-menu-valet' );
                        ?>
                    </option>
                </select>
            </div>
        </div>
        <div class="t9p-tmv-split-wrapper">
            <div class="t9p-tmv-left">
                <p class="t9p-tmv-intro">
                    <svg class="icon icon-blue">
                        <use href="#icon-info"></use>
                    </svg>
                    <?php
                    esc_html_e( 'Tick a top-level item to hide it — its sub-items are hidden and locked automatically. Untick them individually only when the parent is visible. Drag the ⠿ handle to reorder. All changes save instantly; click "Apply Changes" to reload the sidebar.', 'the-9-dollar-menu-valet' );
                    ?>
                </p>
                <div id="t9p-tmv-status-msg" class="t9p-tmv-status" aria-live="polite"></div>
                <button id="t9p-tmv-apply-btn" class="button button-primary" style="display:none;">
                    <?php
                    esc_html_e( 'Apply Changes', 'the-9-dollar-menu-valet' );
                    ?>
                </button>
                <table class="widefat" id="t9p-tmv-menu-table">
                    <thead>
                    <tr>
                        <th class="t9p-tmv-checkbox-col"><?php
                            esc_html_e( 'Hide Top-level menu item', 'the-9-dollar-menu-valet' );
                            ?></th>
                        <th><?php
                            esc_html_e( 'Hide Submenu item', 'the-9-dollar-menu-valet' );
                            ?></th>
                        <th><?php
                            esc_html_e( 'Slug / URL', 'the-9-dollar-menu-valet' );
                            ?></th>
                        <th class="t9p-tmv-rename-col"> <?php
                            esc_html_e( 'Rename', 'the-9-dollar-menu-valet' );
                            ?>
                            <?php
                            if ( t9p_tmv_fs()->is_not_paying() ) {
                                ?>
                                <span class="t9p-tmv-pro-bagde">PRO</span>
                                <?php
                            }
                            ?>
                        </th>
                        <th class="t9p-tmv-drag-col"><?php
                            esc_html_e( 'Order', 'the-9-dollar-menu-valet' );
                            ?></th>
                    </tr>
                    </thead>
                    <tbody id="t9p-tmv-sortable">
                    <?php
                    foreach ( $menu_snapshot as $item ) {
                        $slug          = $item['slug'];
                        $label         = $item['label'];
                        $is_sep        = $item['separator'];
                        $sub           = $item['submenu'];
                        $checked       = ( in_array( $slug, $hidden_items, true ) ? 'checked' : '' );
                        $parent_hidden = in_array( $slug, $hidden_items, true );
                        $row_id        = 'row-' . sanitize_html_class( $slug );
                        $display_label = $label;
                        $has_rename    = false;
                        ?>
                        <?php
                        if ( $is_sep ) {
                            ?>
                            <tr class="t9p-tmv-separator-row" data-slug="<?php
                            echo esc_attr( $slug );
                            ?>">
                                <td class="t9p-tmv-checkbox-col"><input type="checkbox" class="t9p-tmv-hide-cb"
                                                                        data-slug="<?php
                                                                        echo esc_attr( $slug );
                                                                        ?>" <?php
                                    echo esc_attr( $checked );
                                    ?>>
                                    <em>
                                        <?php
                                        esc_html_e( '— Separator —', 'the-9-dollar-menu-valet' );
                                        ?>
                                    </em></td>
                                <td colspan="3"></td>
                                <td class="t9p-tmv-drag-col"><span class="t9p-tmv-drag-handle" title="<?php
                                    esc_attr_e( 'Drag to reorder', 'the-9-dollar-menu-valet' );
                                    ?>"> <svg class="icon icon-black">
              <use href="#icon-grip-vertical"></use>
              </svg> </span></td>
                            </tr>
                            <?php
                        } else {
                            ?>
                            <tr id="<?php
                            echo esc_attr( $row_id );
                            ?>"
                                class="t9p-tmv-menu-row<?php
                                echo( $parent_hidden ? ' t9p-tmv-row-hidden' : '' );
                                echo( $slug === T9P_TMV_SLUG ? ' t9p-tmv-own-item' : '' );
                                ?>"
                                data-slug="<?php
                                echo esc_attr( $slug );
                                ?>">
                                <td class="t9p-tmv-checkbox-col"><input type="checkbox"
                                                                        class="t9p-tmv-hide-cb t9p-tmv-parent-cb"
                                                                        data-slug="<?php
                                                                        echo esc_attr( $slug );
                                                                        ?>"
                                            <?php
                                            echo esc_attr( $checked );
                                            ?>>
                                    <strong> <span class="t9p-tmv-label-text"
                                                   data-slug="<?php
                                                   echo esc_attr( $slug );
                                                   ?>"
                                                   data-original="<?php
                                                   echo esc_attr( $label );
                                                   ?>"
										      <?php
                                              echo( $has_rename ? 'title="' . esc_attr( $label ) . '"' : ( ( $slug === T9P_TMV_SLUG ? 'title="' . esc_attr__( 'This is Menu Valet itself — be careful: changes here affect this plugin\'s own menu entry.', 'the-9-dollar-menu-valet' ) . '"' : '' ) ) );
                                              ?>>
              <?php
              echo esc_html( $display_label );
              ?>
              </span> </strong></td>
                                <td class="t9p-tmv-label-col" data-label="<?php
                                esc_attr_e( 'Menu Item', 'the-9-dollar-menu-valet' );
                                ?>"><?php
                                    if ( ! empty( $sub ) ) {
                                        ?>
                                        <ul class="t9p-tmv-submenu-list">
                                            <?php
                                            foreach ( $sub as $sub_item ) {
                                                $sub_is_hidden  = $parent_hidden || in_array( 'sub::' . $sub_item['slug'], $hidden_items, true );
                                                $sub_display    = $sub_item['label'];
                                                $sub_has_rename = false;
                                                ?>
                                                <li>
                                                    <label>
                                                        <input type="checkbox"
                                                               class="t9p-tmv-hide-cb t9p-tmv-sub-cb"
                                                               data-slug="<?php
                                                               echo esc_attr( $sub_item['slug'] );
                                                               ?>"
                                                                <?php
                                                                echo( $sub_is_hidden ? 'checked' : '' );
                                                                ?>
                                                                <?php
                                                                echo( $parent_hidden ? 'disabled' : '' );
                                                                ?>>
                                                        <span class="t9p-tmv-label-text"
                                                              data-slug="sub::<?php
                                                              echo esc_attr( $sub_item['slug'] );
                                                              ?>"
                                                              data-original="<?php
                                                              echo esc_attr( $sub_item['label'] );
                                                              ?>"
														      <?php
                                                              echo( $sub_has_rename ? 'title="' . esc_attr( $sub_item['label'] ) . '"' : '' );
                                                              ?>>
                    <?php
                    echo esc_html( $sub_display );
                    ?>
                    </span> </label>
                                                </li>
                                                <?php
                                            }
                                            ?>
                                        </ul>
                                        <?php
                                    }
                                    ?></td>
                                <td class="t9p-tmv-slug-col" data-label="<?php
                                esc_attr_e( 'Slug / URL', 'the-9-dollar-menu-valet' );
                                ?>"><code>
                                        <?php
                                        echo esc_html( $slug );
                                        ?>
                                    </code></td>
                                <td class="t9p-tmv-rename-col" data-label="<?php
                                esc_attr_e( 'Rename', 'the-9-dollar-menu-valet' );
                                ?>">
                                    <button class="button t9p-tmv-rename-btn"
                                            data-slug="<?php
                                            echo esc_attr( $slug );
                                            ?>"
                                            <?php
                                            echo( t9p_tmv_fs()->is_not_paying() ? 'disabled' : '' );
                                            ?>>
                                        <?php
                                        esc_html_e( 'Rename', 'the-9-dollar-menu-valet' );
                                        ?>
                                    </button>
                                    <?php
                                    if ( t9p_tmv_fs()->is_not_paying() ) {
                                        ?>
                                        <span class="t9p-tmv-pro-bagde t9p-tmv-rename-bagde-mobile">PRO</span>
                                        <?php
                                    }
                                    ?></td>
                                <td class="t9p-tmv-drag-col" data-label="<?php
                                esc_attr_e( 'Order', 'the-9-dollar-menu-valet' );
                                ?>"><span class="t9p-tmv-drag-handle" title="<?php
                                    esc_attr_e( 'Drag to reorder', 'the-9-dollar-menu-valet' );
                                    ?>"> <svg class="icon icon-black">
              <use href="#icon-grip-vertical"></use>
              </svg> </span></td>
                            </tr>
                            <?php
                        }
                        ?>
                        <?php
                    }
                    ?>
                    </tbody>
                </table>
            </div>
            <div class="t9p-tmv-right">
                <?php
                if ( t9p_tmv_fs()->is_not_paying() ) {
                    ?>
                    <div class="t9p-tmv-orderbox">
                        <h3>
                            <svg class="icon">
                                <use href="#icon-key-round"></use>
                            </svg>
                            <?php
                            esc_html_e( 'License Information', 'the-9-dollar-menu-valet' );
                            ?>
                        </h3>
                        <p><strong>
                                <?php
                                /* translators: %s: version number */
                                echo esc_html( sprintf( 'The 9 Dollar Menu Valet LITE %s', sprintf( __( 'Version %s', 'the-9-dollar-menu-valet' ), T9P_TMV_VERSION ) ) );
                                ?>
                            </strong></p>
                        <ul>
                            <li>
                                <svg class="icon">
                                    <use href="#icon-circle-arrow-right"></use>
                                </svg>
                                <?php
                                esc_html_e( 'License status:', 'the-9-dollar-menu-valet' );
                                ?>
                                <?php
                                esc_html_e( 'No license required — LITE is free', 'the-9-dollar-menu-valet' );
                                ?>
                            </li>
                            <li>
                                <svg class="icon">
                                    <use href="#icon-circle-arrow-right"></use>
                                </svg>
                                <?php
                                esc_html_e( 'Expiration date:', 'the-9-dollar-menu-valet' );
                                ?>
                                <?php
                                esc_html_e( 'Unlimited', 'the-9-dollar-menu-valet' );
                                ?>
                            </li>
                        </ul>
                        <a href="<?php
                        echo esc_url( t9p_tmv_fs()->get_upgrade_url() );
                        ?>" target="_blank" rel="noopener noreferrer" class="t9p-tmv-orderbox-link">
                            <svg class="icon">
                                <use href="#icon-zap"></use>
                            </svg>
                            <?php
                            esc_html_e( 'Upgrade to PRO', 'the-9-dollar-menu-valet' );
                            ?>
                        </a></div>
                    <div class="t9p-tmv-orderbox">
                        <h3>
                            <svg class="icon">
                                <use href="#icon-gem"></use>
                            </svg>
                            <?php
                            esc_html_e( 'Get PRO Version', 'the-9-dollar-menu-valet' );
                            ?>
                        </h3>
                        <p><strong>
                                <svg class="icon">
                                    <use href="#icon-circle-gauge"></use>
                                </svg>
                                <?php
                                esc_html_e( 'Take it to the next level with PRO', 'the-9-dollar-menu-valet' );
                                ?>
                            </strong></p>
                        <ul>
                            <li>
                                <svg class="icon">
                                    <use href="#icon-check"></use>
                                </svg>
                                <?php
                                esc_html_e( 'Live search field inside the admin sidebar menu', 'the-9-dollar-menu-valet' );
                                ?>
                            </li>
                            <li>
                                <svg class="icon">
                                    <use href="#icon-check"></use>
                                </svg>
                                <?php
                                esc_html_e( 'Rename any menu or submenu item', 'the-9-dollar-menu-valet' );
                                ?>
                            </li>
                            <li>
                                <svg class="icon">
                                    <use href="#icon-check"></use>
                                </svg>
                                <?php
                                esc_html_e( 'Custom Sidebar Width — adjust the menu width with a slider', 'the-9-dollar-menu-valet' );
                                ?>
                            </li>
                            <li>
                                <svg class="icon">
                                    <use href="#icon-check"></use>
                                </svg>
                                <?php
                                esc_html_e( 'No ads', 'the-9-dollar-menu-valet' );
                                ?>
                            </li>
                            <li>
                                <svg class="icon">
                                    <use href="#icon-check"></use>
                                </svg>
                                <?php
                                esc_html_e( 'Priority support via ticket system', 'the-9-dollar-menu-valet' );
                                ?>
                            </li>
                        </ul>
                        <p><a href="<?php
                            echo esc_url( t9p_tmv_fs()->get_upgrade_url() );
                            ?>" target="_blank" rel="noopener noreferrer" class="t9p-tmv-orderbox-link">
                                <svg class="icon">
                                    <use href="#icon-zap"></use>
                                </svg>
                                <?php
                                esc_html_e( 'Upgrade now', 'the-9-dollar-menu-valet' );
                                ?>
                            </a></p>
                    </div>
                    <div class="t9p-tmv-orderbox">
                        <h3>
                            <svg class="icon">
                                <use href="#icon-thumbs-up"></use>
                            </svg>
                            <?php
                            esc_html_e( 'Like the Plugin?', 'the-9-dollar-menu-valet' );
                            ?>
                        </h3>
                        <p class="t9p-tmv-bmc"><img src="<?php
                            echo esc_url( T9P_TMV_PLUGIN_URL . 'assets/buy-me-a-beer.jpg' );
                            ?>" width="165" height="39" alt="Buy me a Beer"></p>
                        <p><a href="https://buymeacoffee.com/t.9.p" target="_blank" rel="noopener noreferrer"
                              class="t9p-tmv-orderbox-link">
                                <svg class="icon">
                                    <use href="#icon-beer"></use>
                                </svg>
                                <?php
                                esc_html_e( 'Grab me a Beer', 'the-9-dollar-menu-valet' );
                                ?>
                            </a></p>
                    </div>
                    <?php
                }
                ?>
                <div class="t9p-tmv-orderbox">
                    <h3>
                        <svg class="icon">
                            <use href="#icon-lightbulb"></use>
                        </svg>
                        <?php
                        esc_html_e( 'Feature Ideas', 'the-9-dollar-menu-valet' );
                        ?>
                    </h3>
                    <p>
                        <?php
                        esc_html_e( 'Your idea could shape the next update. Share a feature you\'d love to see and help decide what we build next.', 'the-9-dollar-menu-valet' );
                        ?>
                    </p>
                    <p><a href="<?php
                        echo esc_url( 'https://' . T9P_TMV_SLUG . '.fider.io/' );
                        ?>" target="_blank" rel="noopener noreferrer" class="t9p-tmv-orderbox-link">
                            <svg class="icon">
                                <use href="#icon-pencil"></use>
                            </svg>
                            <?php
                            esc_html_e( 'Submit your Idea', 'the-9-dollar-menu-valet' );
                            ?>
                        </a></p>
                </div>
                <div class="t9p-tmv-orderbox">
                    <h3>
                        <svg class="icon">
                            <use href="#icon-headset"></use>
                        </svg>
                        <?php
                        esc_html_e( 'Support', 'the-9-dollar-menu-valet' );
                        ?>
                    </h3>
                    <?php
                    if ( t9p_tmv_fs()->is_not_paying() ) {
                        ?>
                        <p>
                            <?php
                            esc_html_e( 'For our LITE versions, support is available exclusively via wordpress.org. Priority support via our ticket system is unfortunately only available if you have purchased a PRO version. The licence key is required to use the ticket system', 'the-9-dollar-menu-valet' );
                            ?>
                        </p>
                        <p><a href="<?php
                            echo esc_url( 'https://wordpress.org/support/plugin/' . T9P_TMV_SLUG . '/' );
                            ?>" target="_blank" rel="noopener noreferrer" class="t9p-tmv-orderbox-link">
                                <svg class="icon">
                                    <use href="#icon-link"></use>
                                </svg>
                                <?php
                                esc_html_e( 'Visit wordpress.org', 'the-9-dollar-menu-valet' );
                                ?>
                            </a></p>
                        <?php
                    }
                    ?>
                </div>
                <div class="t9p-tmv-orderbox">
                    <h3>
                        <svg class="icon">
                            <use href="#icon-share"></use>
                        </svg>
                        <?php
                        esc_html_e( 'Connect with us', 'the-9-dollar-menu-valet' );
                        ?>
                    </h3>
                    <ul>
                        <li>
                            <svg class="icon">
                                <use href="#icon-link"></use>
                            </svg>
                            <strong>Website:</strong> <a href="https://www.the-9-dollar-plugins.com/?tmv=1"
                                                         target="_blank" rel="noopener noreferrer">the-9-dollar-plugins.com</a>
                        </li>
                        <li>
                            <svg class="icon">
                                <use href="#icon-facebook"></use>
                            </svg>
                            <strong>Facebook:</strong> <a href="https://www.facebook.com/profile.php?id=61577312939942"
                                                          target="_blank" rel="noopener noreferrer">The 9 Dollar
                                Plugins</a></li>
                    </ul>
                </div>
                <div class="t9p-tmv-bottom">
                    <h3>
                        <?php
                        esc_html_e( 'Pluggy wishes you a perfect day', 'the-9-dollar-menu-valet' );
                        ?>
                    </h3>
                    <p><img src="<?php
                        echo esc_url( T9P_TMV_PLUGIN_URL . 'assets/the-9-dollar-plugins-mascot.png' );
                        ?>" width="200" height="300" alt="Pluggy"></p>
                </div>
            </div>
        </div>
        <div style="clear:both;"></div>
    </div>
    <?php
}

// ── Menu snapshot builder ─────────────────────────────────────────────────
/**
 * Builds an ordered snapshot array from raw $menu / $submenu globals.
 *
 * @param array $menu
 * @param array $submenu
 * @param array $saved_order
 *
 * @return array[]
 */
function t9p_tmv_build_menu_snapshot( array $menu, array $submenu, array $saved_order ) {
    $items = array();
    ksort( $menu );
    foreach ( $menu as $item ) {
        $slug = $item[2] ?? '';
        $sep  = strpos( $slug, 'separator' ) === 0;
        $subs = array();
        if ( ! $sep && isset( $submenu[ $slug ] ) ) {
            foreach ( $submenu[ $slug ] as $sub ) {
                $raw_label     = $sub[0] ?? '';
                $display_label = trim( wp_strip_all_tags( preg_replace( '/<span\\b[^>]*>.*?<\\/span>/is', '', $raw_label ) ) );
                if ( '' === $display_label ) {
                    continue;
                }
                $subs[] = array(
                        'label' => $display_label,
                        'slug'  => $sub[2] ?? '',
                );
            }
        }
        $items[] = array(
                'slug'      => $slug,
                'label'     => ( wp_strip_all_tags( $item[0] ?? '' ) ?: $slug ),
                'separator' => $sep,
                'submenu'   => $subs,
        );
    }
    if ( ! empty( $saved_order ) ) {
        usort( $items, function ( $a, $b ) use ( $saved_order ) {
            $pa = array_search( $a['slug'], $saved_order, true );
            $pb = array_search( $b['slug'], $saved_order, true );

            return ( ( false === $pa ? 999 : $pa ) ) - ( ( false === $pb ? 999 : $pb ) );
        } );
    }

    return $items;
}

// ── AJAX handlers ─────────────────────────────────────────────────────────
/** Returns all submenu slugs (with sub:: prefix) for a given parent. */
function t9p_tmv_get_sub_slugs( $parent_slug ) {
    global $t9p_tmv_menu_snapshot_raw;
    $submenu = $t9p_tmv_menu_snapshot_raw['submenu'] ?? array();
    if ( empty( $submenu[ $parent_slug ] ) ) {
        return array();
    }

    return array_values( array_filter( array_map( function ( $s ) {
        return ( $s ? 'sub::' . $s : '' );
    }, array_column( $submenu[ $parent_slug ], 2 ) ) ) );
}

// Toggle hidden state — POST: slug, hidden (1|0), is_parent (1|0)
add_action( 'wp_ajax_t9p_tmv_toggle_item', 't9p_tmv_handler_toggle_item' );
function t9p_tmv_handler_toggle_item() {
    check_ajax_referer( 't9p_tmv_nonce' );
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( array(
                'message' => __( 'Permission denied.', 'the-9-dollar-menu-valet' ),
        ), 403 );
    }
    $slug      = sanitize_text_field( wp_unslash( $_POST['slug'] ?? '' ) );
    $hidden    = sanitize_text_field( wp_unslash( $_POST['hidden'] ?? '0' ) );
    $is_parent = sanitize_text_field( wp_unslash( $_POST['is_parent'] ?? '0' ) );
    if ( '' === $slug ) {
        wp_send_json_error( array(
                'message' => __( 'Invalid slug.', 'the-9-dollar-menu-valet' ),
        ) );
    }
    if ( '0' === $is_parent && strpos( $slug, 'separator' ) !== 0 ) {
        $slug = 'sub::' . $slug;
    }
    $settings     = t9p_tmv_get_settings();
    $hidden_items = $settings['hidden_items'];
    $targets      = array_merge( array( $slug ), ( '1' === $is_parent ? t9p_tmv_get_sub_slugs( $slug ) : array() ) );
    if ( '1' === $hidden ) {
        foreach ( $targets as $s ) {
            if ( ! in_array( $s, $hidden_items, true ) ) {
                $hidden_items[] = $s;
            }
        }
    } else {
        $hidden_items = array_values( array_diff( $hidden_items, $targets ) );
    }
    $settings['hidden_items'] = $hidden_items;
    t9p_tmv_save_settings( $settings );
    wp_send_json_success( array(
            'hidden_items' => $hidden_items,
    ) );
}

// Save drag-and-drop order — POST: order[]
add_action( 'wp_ajax_t9p_tmv_save_order', 't9p_tmv_handler_save_order' );
function t9p_tmv_handler_save_order() {
    check_ajax_referer( 't9p_tmv_nonce' );
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( array(
                'message' => __( 'Permission denied.', 'the-9-dollar-menu-valet' ),
        ), 403 );
    }
    $raw_order = ( isset( $_POST['order'] ) && is_array( $_POST['order'] ) ? array_map( 'sanitize_text_field', wp_unslash( $_POST['order'] ) ) : array() );
    if ( empty( $raw_order ) ) {
        wp_send_json_error( array(
                'message' => __( 'Empty order received.', 'the-9-dollar-menu-valet' ),
        ) );
    }
    $settings               = t9p_tmv_get_settings();
    $settings['menu_order'] = $raw_order;
    ( t9p_tmv_save_settings( $settings ) ? wp_send_json_success() : wp_send_json_error( array(
            'message' => __( 'Could not save settings.', 'the-9-dollar-menu-valet' ),
    ) ) );
}

// Save delete-on-uninstall toggle — POST: delete_on_uninstall (1|0)
add_action( 'wp_ajax_t9p_tmv_save_delete_setting', 't9p_tmv_handler_save_delete_setting' );
function t9p_tmv_handler_save_delete_setting() {
    check_ajax_referer( 't9p_tmv_nonce' );
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( array(
                'message' => __( 'Permission denied.', 'the-9-dollar-menu-valet' ),
        ), 403 );
    }
    $settings                        = t9p_tmv_get_settings();
    $settings['delete_on_uninstall'] = isset( $_POST['delete_on_uninstall'] ) && '1' === sanitize_text_field( wp_unslash( $_POST['delete_on_uninstall'] ) );
    ( t9p_tmv_save_settings( $settings ) ? wp_send_json_success() : wp_send_json_error( array(
            'message' => __( 'Could not save settings.', 'the-9-dollar-menu-valet' ),
    ) ) );
}

// ── Review Notice ─────────────────────────────────────────────────────────────
add_action( 'admin_enqueue_scripts', 't9p_tmv_enqueue_review_notice_script' );
add_action( 'admin_notices', 't9p_tmv_review_notice' );
function t9p_tmv_review_notice_visible() {
    if ( ! t9p_tmv_fs()->is_not_paying() ) {
        return false;
    }
    if ( get_option( 't9p_tmv_review_dismissed' ) ) {
        return false;
    }
    $activated_at = get_option( 't9p_tmv_activated_at' );

    return $activated_at && time() - $activated_at >= 14 * DAY_IN_SECONDS;
}

function t9p_tmv_enqueue_review_notice_script() {
    if ( ! t9p_tmv_review_notice_visible() ) {
        return;
    }
    wp_enqueue_script( 'jquery' );
    $script = sprintf( '(function($){$(function(){function t9p_tmv_dismissReview(){$("#t9p-tmv-review-notice").fadeOut(300);$.post(%s,{action:"t9p_tmv_dismiss_review_notice",_ajax_nonce:%s});}$(document).on("click",".t9p-tmv-dismiss-review",function(e){e.preventDefault();t9p_tmv_dismissReview();});$(document).on("click","#t9p-tmv-review-notice .notice-dismiss",t9p_tmv_dismissReview);});}(jQuery));', wp_json_encode( admin_url( 'admin-ajax.php' ) ), wp_json_encode( wp_create_nonce( 't9p_tmv_review_nonce' ) ) );
    wp_add_inline_script( 'jquery', $script );
}

function t9p_tmv_review_notice() {
    if ( ! t9p_tmv_review_notice_visible() ) {
        return;
    }
    ?>
    <div class="notice notice-info is-dismissible" id="t9p-tmv-review-notice">
        <p><strong>The 9 Dollar Menu Valet</strong><br>
            <?php
            esc_html_e( 'Enjoying the plugin? If it\'s saving you time and headaches, a quick review on wordpress.org would mean the world to us — it literally keeps the lights on (and the coffee flowing).', 'the-9-dollar-menu-valet' );
            ?>
        </p>
        <p><a href="https://wordpress.org/support/plugin/the-9-dollar-menu-valet/reviews/#new-post" target="_blank"
              class="button button-primary" rel="noopener noreferrer">
                <?php
                esc_html_e( 'Sure, happy to help!', 'the-9-dollar-menu-valet' );
                ?>
            </a> &nbsp; <a href="#" class="button t9p-tmv-dismiss-review">
                <?php
                esc_html_e( 'Nah, stop bugging me', 'the-9-dollar-menu-valet' );
                ?>
            </a></p>
        <hr style="margin:12px 0;">
        <p>
            <?php
            esc_html_e( 'Also: beer is always welcome. How else are we supposed to survive and still ship good plugins?', 'the-9-dollar-menu-valet' );
            ?>
            <br>
            <a href="https://buymeacoffee.com/t.9.p" target="_blank" rel="noopener noreferrer">
                <?php
                esc_html_e( 'Buy me a beer', 'the-9-dollar-menu-valet' );
                ?>
            </a></p>
    </div>
    <?php
}

add_action( 'wp_ajax_t9p_tmv_dismiss_review_notice', 't9p_tmv_handler_dismiss_review_notice' );
function t9p_tmv_handler_dismiss_review_notice() {
    check_ajax_referer( 't9p_tmv_review_nonce' );
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die();
    }
    update_option( 't9p_tmv_review_dismissed', 1, false );
    wp_die();
}

// ── REST API ──────────────────────────────────────────────────────────────
add_action( 'rest_api_init', 't9p_tmv_register_rest_routes' );
function t9p_tmv_register_rest_routes() {
    register_rest_route( 't9p-tmv/v1', '/settings', array(
            array(
                    'methods'             => \WP_REST_Server::READABLE,
                    'callback'            => 't9p_tmv_rest_get_settings',
                    'permission_callback' => function () {
                        return current_user_can( 'manage_options' );
                    },
            ),
            array(
                    'methods'             => \WP_REST_Server::CREATABLE,
                    'callback'            => 't9p_tmv_rest_update_settings',
                    'permission_callback' => function () {
                        return current_user_can( 'manage_options' );
                    },
                    'args'                => array(
                            'hidden_items' => array(
                                    'type'              => 'array',
                                    'items'             => array(
                                            'type' => 'string',
                                    ),
                                    'sanitize_callback' => function ( $v ) {
                                        return array_map( 'sanitize_text_field', (array) $v );
                                    },
                            ),
                            'menu_order'   => array(
                                    'type'              => 'array',
                                    'items'             => array(
                                            'type' => 'string',
                                    ),
                                    'sanitize_callback' => function ( $v ) {
                                        return array_map( 'sanitize_text_field', (array) $v );
                                    },
                            ),
                    ),
            )
    ) );
}

function t9p_tmv_rest_get_settings( WP_REST_Request $request ) {
    return rest_ensure_response( t9p_tmv_get_settings() );
}

function t9p_tmv_rest_update_settings( WP_REST_Request $request ) {
    $settings = t9p_tmv_get_settings();
    if ( $request->has_param( 'hidden_items' ) ) {
        $settings['hidden_items'] = $request->get_param( 'hidden_items' );
    }
    if ( $request->has_param( 'menu_order' ) ) {
        $settings['menu_order'] = $request->get_param( 'menu_order' );
    }
    if ( ! t9p_tmv_save_settings( $settings ) ) {
        return new WP_Error( 't9p_tmv_save_failed', __( 'Could not save settings.', 'the-9-dollar-menu-valet' ), array(
                'status' => 500,
        ) );
    }

    return rest_ensure_response( $settings );
}


