<?php
/**
 * Name: Login/Logout Menu Items
 * Description: Add smart Login or Logout menu item to classic WordPress menus that shows Login when logged out and Logout when logged in
 * Category: User Management
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Dynamic Navigation",
 *     "description": "Show login/logout links in your classic menu that automatically change based on whether the user is logged in or not."
 *   },
 *   {
 *     "title": "Better UX",
 *     "description": "Make it easier for users to find login and logout options without hunting through your site."
 *   }
 * ]
 * Added: 2025-08-16
 * Tags: menu, login, logout, navigation, authentication
 * WhereToFind: {
 *   "location": "Navigation Menus",
 *   "url": "/",
 *   "instructions": "Menu shows 'Login' when logged out, 'Logout' when logged in",
 *   "newTab": true
 * }
 */

// Prevent direct access
if (!defined('ABSPATH')) exit;

class SwitchboardLoginLogoutMenu {

    public function __construct() {
        // Classic menu support
        add_action('load-nav-menus.php', [$this, 'add_meta_box']);
        add_filter('wp_setup_nav_menu_item', [$this, 'setup_nav_menu_item']);
        add_filter('wp_nav_menu_items', [$this, 'render_menu_items'], 10, 2);

        // Register with data registry
        $this->register_with_data_registry();
    }

    private function register_with_data_registry() {
        if (class_exists('Switchboard_Data_Registry')) {
            $registry = Switchboard_Data_Registry::get_instance();
            $registry->auto_register($this, __FILE__);
        }
    }

    public function register_data_locations() {
        return [
            'options' => [
                'switchboard_login-logout-menu_settings'
            ],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
            'term_meta' => [],
            'transients' => []
        ];
    }

    public function add_meta_box() {
        add_meta_box(
            'switchboard-login-logout-menu',
            __('Login/Logout Links', 'wpswitchboard') . ' <span class="switchboard-badge">SWITCHBOARD</span>',
            [$this, 'render_meta_box'],
            'nav-menus',
            'side',
            'low'
        );
    }

    public function render_meta_box() {
        ?>
        <div id="posttype-switchboard-login-logout" class="posttypediv">
            <div id="tabs-panel-switchboard-login-logout" class="tabs-panel tabs-panel-active">
                <ul id="switchboard-login-logout-checklist" class="categorychecklist form-no-clear">
                    <li>
                        <label class="menu-item-title">
                            <input type="checkbox" class="menu-item-checkbox" name="menu-item[-1][menu-item-object-id]" value="-1"> <?php esc_html_e('Login/Logout', 'wpswitchboard'); ?>
                        </label>
                        <input type="hidden" class="menu-item-type" name="menu-item[-1][menu-item-type]" value="custom">
                        <input type="hidden" class="menu-item-title" name="menu-item[-1][menu-item-title]" value="<?php esc_attr_e('Login/Logout', 'wpswitchboard'); ?>">
                        <input type="hidden" class="menu-item-url" name="menu-item[-1][menu-item-url]" value="#switchboard-login-logout">
                        <input type="hidden" class="menu-item-classes" name="menu-item[-1][menu-item-classes]" value="switchboard-login-logout-link">
                    </li>
                </ul>
            </div>
            <p class="button-controls">
                <span class="add-to-menu">
                    <input type="submit" class="button-secondary submit-add-to-menu right" value="<?php esc_attr_e('Add to Menu', 'wpswitchboard'); ?>" name="add-post-type-menu-item" id="submit-posttype-switchboard-login-logout">
                    <span class="spinner"></span>
                </span>
            </p>
        </div>
        <style>
        #posttype-switchboard-login-logout p.description {
            padding: 8px 12px;
            background: #f0f6fc;
            border-left: 3px solid var(--primary-500);
            margin: 10px 0;
            font-size: 12px;
            line-height: 1.5;
        }
        </style>
        <p class="sb-sp-description">
            <strong><?php esc_html_e('How it works:', 'wpswitchboard'); ?></strong> <?php esc_html_e('This single menu item automatically shows "Login" when logged out and "Logout" when logged in. Just add it to your menu once!', 'wpswitchboard'); ?>
        </p>
        <?php
    }

    public function setup_nav_menu_item($menu_item) {
        if ($menu_item->url === '#switchboard-login-logout') {
            $menu_item->type_label = __('Login/Logout', 'wpswitchboard');
        }
        return $menu_item;
    }

    /**
     * Render settings panel for Login/Logout Menu
     */
    public function render_settings($settings = []) {
        $login_text = isset($settings['login_text']) ? $settings['login_text'] : 'Log In';
        $logout_text = isset($settings['logout_text']) ? $settings['logout_text'] : 'Log Out';
        ?>
        <input type="hidden" name="module" value="login-logout-menu">

        <div class="sb-sp-group sb-sp-field-horizontal" style="margin-bottom: 24px;">
            <div class="sb-sp-field-horizontal-left">
                <label for="setting_login_text" class="sb-sp-label"><?php esc_html_e('Login Link Text', 'wpswitchboard'); ?></label>
                <p class="sb-sp-description"><?php esc_html_e('Text to display for the login link when users are logged out.', 'wpswitchboard'); ?></p>
            </div>
            <input type="text" name="setting_login_text" id="setting_login_text" value="<?php echo esc_attr($login_text); ?>" class="sb-sp-input">
        </div>

        <div class="sb-sp-group sb-sp-field-horizontal" style="margin-bottom: 24px;">
            <div class="sb-sp-field-horizontal-left">
                <label for="setting_logout_text" class="sb-sp-label"><?php esc_html_e('Logout Link Text', 'wpswitchboard'); ?></label>
                <p class="sb-sp-description"><?php esc_html_e('Text to display for the logout link when users are logged in.', 'wpswitchboard'); ?></p>
            </div>
            <input type="text" name="setting_logout_text" id="setting_logout_text" value="<?php echo esc_attr($logout_text); ?>" class="sb-sp-input">
        </div>

        <div class="sb-sp-info-box sb-sp-info-box-info" style="margin-top: 24px;">
            <h4 class="sb-sp-heading-sm"><?php esc_html_e('How to Add Login/Logout Link', 'wpswitchboard'); ?></h4>

            <p class="sb-sp-description" style="margin-bottom: 12px;">
                <strong><?php esc_html_e('Classic Themes (Appearance > Menus):', 'wpswitchboard'); ?></strong><br>
                <?php esc_html_e('Go to Appearance > Menus. Look for the "Login/Logout Links" box in the left sidebar and add it to your menu.', 'wpswitchboard'); ?>
            </p>

            <p class="sb-sp-description" style="margin-bottom: 0;">
                <strong><?php esc_html_e('Block Themes (Site Editor):', 'wpswitchboard'); ?></strong><br>
                <?php esc_html_e('WordPress has a built-in "Login/out" block. In the Navigation block, click + and search for "Login/out" to add it.', 'wpswitchboard'); ?>
            </p>
        </div>

        <div class="sb-sp-info-box sb-sp-info-box-tip" style="margin-top: 16px;">
            <h4 class="sb-sp-heading-sm"><?php esc_html_e('PHP / Theme Development', 'wpswitchboard'); ?></h4>
            <p class="sb-sp-description" style="margin-bottom: 8px;">
                <?php esc_html_e('Use this code in your theme templates:', 'wpswitchboard'); ?>
            </p>
            <div style="background: #1e293b; border-radius: 6px; padding: 12px; margin-bottom: 8px; overflow-x: auto;">
                <code style="color: #e2e8f0; font-size: 12px; white-space: pre; display: block;">&lt;?php echo switchboard_login_logout_link(); ?&gt;</code>
            </div>
            <p class="sb-sp-description" style="margin-bottom: 8px;">
                <?php esc_html_e('With custom options:', 'wpswitchboard'); ?>
            </p>
            <div style="background: #1e293b; border-radius: 6px; padding: 12px; margin-bottom: 8px; overflow-x: auto;">
                <code style="color: #e2e8f0; font-size: 12px; white-space: pre; display: block;">&lt;?php echo switchboard_login_logout_link([
    'login_text'  =&gt; 'Sign In',
    'logout_text' =&gt; 'Sign Out',
    'class'       =&gt; 'my-custom-class',
    'redirect'    =&gt; home_url(),
]); ?&gt;</code>
            </div>
            <p class="sb-sp-description" style="margin: 0; font-size: 12px;">
                <?php esc_html_e('Or use native WordPress:', 'wpswitchboard'); ?>
            </p>
            <div style="background: #1e293b; border-radius: 6px; padding: 12px; margin-top: 8px; overflow-x: auto;">
                <code style="color: #e2e8f0; font-size: 12px; white-space: pre; display: block;">&lt;?php if (is_user_logged_in()): ?&gt;
    &lt;a href="&lt;?php echo wp_logout_url(); ?&gt;"&gt;Log Out&lt;/a&gt;
&lt;?php else: ?&gt;
    &lt;a href="&lt;?php echo wp_login_url(); ?&gt;"&gt;Log In&lt;/a&gt;
&lt;?php endif; ?&gt;</code>
            </div>
        </div>
        <?php
    }

    /**
     * Helper function for theme developers
     */
    public static function get_login_logout_link($args = []) {
        $settings = get_option('switchboard_login-logout-menu_settings', []);

        $defaults = [
            'login_text' => isset($settings['login_text']) ? $settings['login_text'] : __('Log In', 'wpswitchboard'),
            'logout_text' => isset($settings['logout_text']) ? $settings['logout_text'] : __('Log Out', 'wpswitchboard'),
            'redirect' => get_permalink(),
            'class' => 'switchboard-login-logout-link',
        ];

        $args = wp_parse_args($args, $defaults);

        if (is_user_logged_in()) {
            $url = wp_logout_url($args['redirect']);
            $text = $args['logout_text'];
        } else {
            $url = wp_login_url($args['redirect']);
            $text = $args['login_text'];
        }

        return sprintf(
            '<a href="%s" class="%s">%s</a>',
            esc_url($url),
            esc_attr($args['class']),
            esc_html($text)
        );
    }

    public function render_menu_items($items, $args) {
        $settings = get_option('switchboard_login-logout-menu_settings', []);
        $login_text = isset($settings['login_text']) ? $settings['login_text'] : 'Log In';
        $logout_text = isset($settings['logout_text']) ? $settings['logout_text'] : 'Log Out';

        // Replace the single #switchboard-login-logout placeholder
        if (is_user_logged_in()) {
            // User is logged in - show logout link
            $items = str_replace(
                'href="#switchboard-login-logout"',
                'href="' . esc_url(wp_logout_url(get_permalink())) . '"',
                $items
            );
            $items = str_replace('>Login/Logout<', '>' . esc_html($logout_text) . '<', $items);
        } else {
            // User is logged out - show login link
            $items = str_replace(
                'href="#switchboard-login-logout"',
                'href="' . esc_url(wp_login_url(get_permalink())) . '"',
                $items
            );
            $items = str_replace('>Login/Logout<', '>' . esc_html($login_text) . '<', $items);
        }

        return $items;
    }
}

// Initialize and register with data system
$switchboard_instance = new SwitchboardLoginLogoutMenu();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);

/**
 * Global helper function for theme developers
 *
 * Usage in themes:
 *   <?php echo switchboard_login_logout_link(); ?>
 *
 * With custom options:
 *   <?php echo switchboard_login_logout_link([
 *       'login_text' => 'Sign In',
 *       'logout_text' => 'Sign Out',
 *       'class' => 'my-custom-class',
 *       'redirect' => home_url(),
 *   ]); ?>
 *
 * @param array $args Optional arguments
 * @return string HTML link element
 */
function switchboard_login_logout_link($args = []) {
    return SwitchboardLoginLogoutMenu::get_login_logout_link($args);
}
