<?php
/**
 * Limited wp-admin for maca Restu demo users.
 *
 * @package Maca_MenuList
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Strip WP core menus and sensitive maca Restu pages for demo users.
 */
class Maca_MenuList_Admin_Demo_User {

    /**
     * Constructor.
     */
    public function __construct() {
        add_action('admin_menu', array($this, 'remove_sensitive_submenus'), 998);
        add_action('admin_menu', array($this, 'strip_default_menus'), 999);
        add_action('admin_init', array($this, 'guard_admin_access'), 1);
        add_action('admin_init', array($this, 'guard_readonly_writes'), 2);
        add_action('admin_notices', array($this, 'render_demo_notice'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_readonly_assets'));
    }

    /**
     * Hide backup, license, and legal pages from the maca Restu submenu.
     *
     * @return void
     */
    public function remove_sensitive_submenus() {
        if (!maca_menulist_user_is_demo_manager()) {
            return;
        }

        foreach (maca_menulist_demo_denied_admin_pages() as $page) {
            remove_submenu_page('maca-restu', $page);
        }
    }

    /**
     * Remove all non-maca-Restu top-level admin menus.
     *
     * @return void
     */
    public function strip_default_menus() {
        if (!maca_menulist_user_is_demo_manager()) {
            return;
        }

        global $menu;

        if (!is_array($menu)) {
            return;
        }

        foreach ($menu as $index => $item) {
            if (!isset($item[2])) {
                continue;
            }

            $slug = (string) $item[2];
            if ($slug !== maca_menulist_admin_menu_slug()) {
                remove_menu_page($slug);
            }
        }
    }

    /**
     * Redirect demo users away from disallowed admin screens.
     *
     * @return void
     */
    public function guard_admin_access() {
        if (!maca_menulist_user_is_demo_manager()) {
            return;
        }

        if (defined('DOING_AJAX') && DOING_AJAX) {
            return;
        }

        $page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '';
        $fallback = admin_url('admin.php?page=maca-restu-dashboard');

        if (maca_menulist_is_maca_restu_admin_page($page)) {
            if (in_array($page, maca_menulist_demo_denied_admin_pages(), true)) {
                wp_safe_redirect($fallback);
                exit;
            }

            return;
        }

        $script = isset($GLOBALS['pagenow']) ? (string) $GLOBALS['pagenow'] : '';

        if ($page === '' && $script !== '' && !in_array($script, array('admin.php', 'admin-ajax.php', 'profile.php'), true)) {
            wp_safe_redirect($fallback);
            exit;
        }

        if ($page === '' && $script === 'admin.php' && !isset($_GET['page'])) {
            wp_safe_redirect($fallback);
            exit;
        }

        if (!maca_menulist_is_maca_restu_admin_page($page)) {
            wp_safe_redirect($fallback);
            exit;
        }
    }

    /**
     * Block import, export, and payment saves for demo users.
     *
     * @return void
     */
    public function guard_readonly_writes() {
        if (!maca_menulist_user_is_demo_manager()) {
            return;
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '';

        if ($page === 'maca-restu-dish-csv' && isset($_GET['maca_export'])) {
            wp_safe_redirect(admin_url('admin.php?page=maca-restu-dish-csv&demo_readonly=1'));
            exit;
        }

        if ($page === 'maca-restu-payment-history' && isset($_GET['maca_export'])) {
            wp_safe_redirect(admin_url('admin.php?page=maca-restu-payment-history&demo_readonly=1'));
            exit;
        }

        if (!maca_menulist_admin_is_demo_readonly_page($page)) {
            return;
        }

        if (!empty($_POST)) {
            wp_safe_redirect(add_query_arg('demo_readonly', '1', admin_url('admin.php?page=' . $page)));
            exit;
        }
    }

    /**
     * Disable forms and export links on read-only demo screens.
     *
     * @param string $hook Admin hook suffix.
     * @return void
     */
    public function enqueue_readonly_assets($hook) {
        if (!maca_menulist_user_is_demo_manager() || !maca_menulist_admin_is_demo_readonly_page()) {
            return;
        }

        wp_register_script('maca-menulist-admin-demo-readonly', '', array('jquery'), MACA_MENULIST_VERSION, true);
        wp_enqueue_script('maca-menulist-admin-demo-readonly');
        wp_add_inline_script(
            'maca-menulist-admin-demo-readonly',
            "jQuery(function($){
                var \$wrap = $('.maca-demo-readonly-wrap');
                \$wrap.find('form').on('submit', function(e){ e.preventDefault(); });
                \$wrap.find('input, select, textarea, button').prop('disabled', true);
                \$wrap.find('a.button-primary, a.button').filter(function(){
                    return (this.href || '').indexOf('maca_export=') !== -1;
                }).addClass('disabled').attr('aria-disabled', 'true').on('click', function(e){ e.preventDefault(); });
            });"
        );
    }

    /**
     * Explain demo restrictions in admin.
     *
     * @return void
     */
    public function render_demo_notice() {
        if (!maca_menulist_user_is_demo_manager()) {
            return;
        }

        echo '<div class="notice notice-info"><p>';
        esc_html_e(
            'You are logged in as a maca Restu demo user. You can edit menus, dishes, and table reservations (bookings, floor overview, tables, opening hours, and exceptions), but payments, import/export, Facebook/Instagram publishing, secrets, license, backup, and other sensitive settings are read-only or hidden.',
            'maca-restu-pro'
        );
        echo '</p></div>';
    }
}
