<?php
/**
 * Limited WP admin for booking hosts (hovmästare).
 *
 * @package Maca_MenuList
 */

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

/**
 * Bootstrap booking host admin restrictions and menus.
 */
class Maca_MenuList_Admin_Booking_Host {

    /**
     * Constructor.
     */
    public function __construct() {
        add_action('init', 'maca_menulist_register_booking_host_role', 12);
        add_action('admin_menu', array($this, 'register_host_menu'), 9);
        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, 'handle_schedule_save'), 5);
        add_filter('maca_menulist_settings_tabs', array($this, 'filter_settings_tabs_for_host'));
    }

    /**
     * Top-level menu for booking-only users.
     *
     * @return void
     */
    public function register_host_menu() {
        if (!maca_menulist_user_is_booking_host_only() || !maca_menulist_pro_has_feature('table_bookings')) {
            return;
        }

        add_menu_page(
            __('Bordsbokningar', 'maca-restu-pro'),
            __('Bordsbokningar', 'maca-restu-pro'),
            MACA_MENULIST_CAP_MANAGE_BOOKINGS,
            'maca-restu-bookings',
            'maca_menulist_admin_render_table_bookings_page',
            'dashicons-calendar-alt',
            26
        );

        add_submenu_page(
            'maca-restu-bookings',
            __('Bookings', 'maca-restu-pro'),
            __('Bookings', 'maca-restu-pro'),
            MACA_MENULIST_CAP_MANAGE_BOOKINGS,
            'maca-restu-bookings',
            'maca_menulist_admin_render_table_bookings_page'
        );

        if (maca_menulist_user_can_manage_booking_schedule()) {
            add_submenu_page(
                'maca-restu-bookings',
                __('Opening hours & exceptions', 'maca-restu-pro'),
                __('Opening hours & exceptions', 'maca-restu-pro'),
                MACA_MENULIST_CAP_MANAGE_BOOKING_SCHEDULE,
                'maca-restu-booking-schedule',
                array($this, 'render_schedule_page')
            );
        }
    }

    /**
     * Remove default WP and maca Restu menus for booking-only users.
     *
     * @return void
     */
    public function strip_default_menus() {
        if (!maca_menulist_user_is_booking_host_only()) {
            return;
        }

        global $menu;

        $allowed = array(
            'maca-restu-bookings',
            'maca-restu-booking-schedule',
        );

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

        foreach ($menu as $index => $item) {
            if (!isset($item[2])) {
                continue;
            }
            $slug = (string) $item[2];
            if (!in_array($slug, $allowed, true)) {
                remove_menu_page($slug);
            }
        }

        // Keep the Bookings submenu so the parent item loads bookings, not the first child (schedule).
        global $submenu;
        if (isset($submenu['maca-restu-bookings']) && is_array($submenu['maca-restu-bookings'])) {
            $ordered = array();
            foreach ($submenu['maca-restu-bookings'] as $item) {
                if (isset($item[2]) && (string) $item[2] === 'maca-restu-bookings') {
                    $ordered[] = $item;
                }
            }
            foreach ($submenu['maca-restu-bookings'] as $item) {
                if (!isset($item[2]) || (string) $item[2] === 'maca-restu-bookings') {
                    continue;
                }
                $ordered[] = $item;
            }
            if ($ordered !== array()) {
                $submenu['maca-restu-bookings'] = array_values($ordered);
            }
        }
    }

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

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

        $page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '';

        if ($page === 'maca-restu-bookings') {
            $tab = isset($_GET['tab']) ? sanitize_key(wp_unslash($_GET['tab'])) : '';
            $host_tabs = array('bookings', 'floor', 'matrix', 'availability', 'tables', 'log');

            if ($tab === '' || $tab === 'settings') {
                wp_safe_redirect(admin_url('admin.php?page=maca-restu-bookings&tab=bookings'));
                exit;
            }

            if (!in_array($tab, $host_tabs, true)) {
                wp_safe_redirect(admin_url('admin.php?page=maca-restu-bookings&tab=bookings'));
                exit;
            }

            return;
        }

        if ($page === 'maca-restu-booking-schedule' && maca_menulist_user_can_manage_booking_schedule()) {
            return;
        }

        if ($page === 'maca-restu-settings') {
            $tab = isset($_GET['tab']) ? sanitize_key(wp_unslash($_GET['tab'])) : '';
            if (in_array($tab, array('hours', 'exceptions'), true) && maca_menulist_user_can_manage_booking_schedule()) {
                return;
            }
        }

        $fallback = maca_menulist_user_can_manage_bookings()
            ? admin_url('admin.php?page=maca-restu-bookings&tab=bookings')
            : admin_url('admin.php?page=maca-restu-booking-schedule');

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

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

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

        if ($page !== '' && !in_array($page, array('maca-restu-bookings', 'maca-restu-booking-schedule'), true)) {
            wp_safe_redirect($fallback);
            exit;
        }
    }

    /**
     * Save weekly hours from the host schedule page.
     *
     * @return void
     */
    public function handle_schedule_save() {
        if (!isset($_POST['maca_booking_host_action']) || sanitize_key(wp_unslash($_POST['maca_booking_host_action'])) !== 'save_hours') {
            return;
        }

        if (!isset($_POST['maca_booking_host_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['maca_booking_host_nonce'])), 'maca_booking_host_hours')) {
            return;
        }

        if (!maca_menulist_user_can_manage_booking_schedule() || !maca_menulist_pro_has_feature('table_bookings')) {
            return;
        }

        if (isset($_POST['hours']) && is_array($_POST['hours'])) {
            maca_menulist_save_booking_hours(wp_unslash($_POST['hours']));
            add_settings_error('maca_booking_host', 'hours_saved', __('Opening hours saved.', 'maca-restu-pro'), 'success');
        }

        wp_safe_redirect(admin_url('admin.php?page=maca-restu-booking-schedule&tab=hours'));
        exit;
    }

    /**
     * Hide settings tabs hosts must not see (when they reach settings).
     *
     * @param array<string, array> $tabs Tab definitions.
     * @return array<string, array>
     */
    public function filter_settings_tabs_for_host($tabs) {
        if (!maca_menulist_user_is_booking_host_only() || !is_array($tabs)) {
            return $tabs;
        }

        $allowed = array('hours', 'exceptions');

        return array_intersect_key($tabs, array_flip($allowed));
    }

    /**
     * Opening hours and exceptions for booking hosts.
     *
     * @return void
     */
    public function render_schedule_page() {
        if (!maca_menulist_user_can_manage_booking_schedule()) {
            return;
        }

        if (!maca_menulist_pro_has_feature('table_bookings')) {
            echo wp_kses_post(maca_menulist_pro_locked_notice('table_bookings'));
            return;
        }

        $tab = isset($_GET['tab']) ? sanitize_key(wp_unslash($_GET['tab'])) : 'hours';
        if (!in_array($tab, array('hours', 'exceptions'), true)) {
            $tab = 'hours';
        }

        $base_url = admin_url('admin.php?page=maca-restu-booking-schedule');
        ?>
        <div class="wrap maca-booking-host-schedule">
            <h1><?php esc_html_e('Opening hours & exceptions', 'maca-restu-pro'); ?></h1>
            <?php settings_errors('maca_booking_host'); ?>
            <?php settings_errors('maca_bookings'); ?>

            <nav class="nav-tab-wrapper">
                <a href="<?php echo esc_url($base_url . '&tab=hours'); ?>" class="nav-tab <?php echo $tab === 'hours' ? 'nav-tab-active' : ''; ?>">
                    <?php esc_html_e('Opening hours', 'maca-restu-pro'); ?>
                </a>
                <a href="<?php echo esc_url($base_url . '&tab=exceptions'); ?>" class="nav-tab <?php echo $tab === 'exceptions' ? 'nav-tab-active' : ''; ?>">
                    <?php esc_html_e('Exceptions', 'maca-restu-pro'); ?>
                </a>
            </nav>

            <div class="maca-booking-host-schedule-content" style="margin-top:16px;">
                <?php if ($tab === 'exceptions') : ?>
                    <?php
                    if (function_exists('maca_menulist_render_booking_exceptions_settings_panel')) {
                        maca_menulist_render_booking_exceptions_settings_panel();
                    }
                    ?>
                <?php else : ?>
                    <form method="post" action="<?php echo esc_url($base_url . '&tab=hours'); ?>">
                        <?php wp_nonce_field('maca_booking_host_hours', 'maca_booking_host_nonce'); ?>
                        <input type="hidden" name="maca_booking_host_action" value="save_hours">
                        <?php maca_menulist_render_opening_hours_fields(); ?>
                        <?php submit_button(__('Save opening hours', 'maca-restu-pro')); ?>
                    </form>
                <?php endif; ?>
            </div>
        </div>
        <?php
    }
}

if (!defined('MACA_MENULIST_BOOKING_HOST_ADMIN_LOADED')) {
    define('MACA_MENULIST_BOOKING_HOST_ADMIN_LOADED', true);
    new Maca_MenuList_Admin_Booking_Host();
}
