<?php
/**
 * Admin Interface for Maca Menu List
 *
 * @package Maca_Menu_List
 * @since 1.0.0
 */

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

require_once MACA_MENULIST_PLUGIN_DIR . 'includes/admin-navigation.php';
require_once MACA_MENULIST_PLUGIN_DIR . 'includes/admin-guest-strings.php';
require_once MACA_MENULIST_PLUGIN_DIR . 'includes/admin-menu-groups.php';

maca_menulist_register_admin_menu_groups();

class Maca_Menu_List_Admin {
    
    /**
     * Constructor
     */
    public function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_menu', array($this, 'adjust_admin_menu_for_content_mode'), 999);
        add_action('admin_menu', array($this, 'reorder_admin_submenu'), 1000);
        add_action('admin_menu', array($this, 'retranslate_admin_submenu'), 1001);
        add_action('admin_init', array($this, 'handle_form_submission'));
        add_action('admin_init', array($this, 'handle_qr_print_page'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_plugins_screen_scripts'));

        require_once MACA_MENULIST_PLUGIN_DIR . 'includes/deactivation-feedback.php';

        require_once MACA_MENULIST_PLUGIN_DIR . 'includes/admin-dishes.php';
        new Maca_Menu_List_Admin_Dishes();

        require_once MACA_MENULIST_PLUGIN_DIR . 'includes/backup.php';
        require_once MACA_MENULIST_PLUGIN_DIR . 'includes/admin-backup.php';
        Maca_MenuList_Admin_Backup::instance();

        require_once MACA_MENULIST_PLUGIN_DIR . 'includes/admin-opening-hours.php';
        require_once MACA_MENULIST_PLUGIN_DIR . 'includes/admin-booking-exceptions.php';
        require_once MACA_MENULIST_PLUGIN_DIR . 'includes/admin-table-booking-settings.php';
        require_once MACA_MENULIST_PLUGIN_DIR . 'includes/admin-table-bookings.php';
        new Maca_MenuList_Admin_Table_Bookings();

        require_once MACA_MENULIST_PLUGIN_DIR . 'includes/admin-dashboard.php';
        new Maca_MenuList_Admin_Dashboard();

        require_once MACA_MENULIST_PLUGIN_DIR . 'includes/admin-daily-report.php';

        require_once MACA_MENULIST_PLUGIN_DIR . 'includes/admin-menu-preview.php';
        Maca_MenuList_Admin_Menu_Preview::bootstrap();
    }

    /**
     * Hide file-based menu pages when dish mode is active.
     */
    public function adjust_admin_menu_for_content_mode() {
        if (!maca_menulist_is_dishes_mode()) {
            return;
        }

        remove_submenu_page('maca-restu', 'maca-restu');
        remove_submenu_page('maca-restu', 'maca-restu-menus');
    }

    /**
     * Sort submenu items for PDF/image menus vs dish mode.
     */
    public function reorder_admin_submenu() {
        global $submenu;

        if (!isset($submenu['maca-restu']) || !is_array($submenu['maca-restu'])) {
            return;
        }

        if (maca_menulist_is_dishes_mode()) {
            $order = array(
                'maca-restu-dashboard',
                'maca-restu-daily-report',
                'maca-restu-onboarding',
                'maca-restu-settings',
                'maca-restu-personal',
                'maca-restu-campaigns',
                'maca-restu-dish-categories',
                'maca-restu-dishes',
                'maca-restu-menu-preview',
                'maca-restu-allergens',
                'maca-restu-orders',
                'maca-restu-payments',
                'maca-restu-payment-history',
                'maca-restu-bookings',
                'maca-restu-qr',
                'maca-restu-info-hub',
                'maca-restu-site-chat',
                'maca-restu-guide',
                'maca-restu-support',
                'maca-restu-group-import-backup',
                'maca-restu-dish-csv',
                'maca-restu-import-pdf',
                'maca-restu-backup',
                'maca-restu-legal',
                'maca-restu-subscription',
            );
        } else {
            $order = array(
                'maca-restu-dashboard',
                'maca-restu-daily-report',
                'maca-restu-onboarding',
                'maca-restu-settings',
                'maca-restu-personal',
                'maca-restu',
                'maca-restu-menus',
                'maca-restu-menu-preview',
                'maca-restu-bookings',
                'maca-restu-qr',
                'maca-restu-info-hub',
                'maca-restu-site-chat',
                'maca-restu-guide',
                'maca-restu-support',
                'maca-restu-group-import-backup',
                'maca-restu-backup',
                'maca-restu-legal',
                'maca-restu-subscription',
            );
        }

        $by_slug = array();

        foreach ($submenu['maca-restu'] as $item) {
            if (!isset($item[2])) {
                continue;
            }

            $by_slug[$item[2]] = $item;
        }

        $reordered = array();

        foreach ($order as $slug) {
            if (isset($by_slug[$slug])) {
                $reordered[] = $by_slug[$slug];
                unset($by_slug[$slug]);
            }
        }

        foreach ($by_slug as $item) {
            $reordered[] = $item;
        }

        $submenu['maca-restu'] = $reordered;
    }

    /**
     * Re-apply translations to admin submenu labels (after reorder / content-mode hooks).
     */
    public function retranslate_admin_submenu() {
        maca_menulist_apply_admin_submenu_translations();
    }

    /**
     * Scripts on the Plugins screen (deactivation feedback modal).
     *
     * @param string $hook Current admin page hook.
     * @return void
     */
    public function enqueue_plugins_screen_scripts($hook) {
        if ($hook !== 'plugins.php') {
            return;
        }

        wp_enqueue_style(
            'maca-menulist-admin-plugins',
            MACA_MENULIST_PLUGIN_URL . 'assets/css/admin-plugins.css',
            array(),
            MACA_MENULIST_VERSION
        );

        wp_enqueue_script(
            'maca-menulist-admin-plugins',
            MACA_MENULIST_PLUGIN_URL . 'assets/js/admin-plugins.js',
            array(),
            MACA_MENULIST_VERSION,
            true
        );

        $reasons = array();
        foreach (maca_menulist_deactivation_feedback_reasons() as $id => $label) {
            $reasons[] = array(
                'id'    => $id,
                'label' => $label,
            );
        }

        wp_localize_script(
            'maca-menulist-admin-plugins',
            'macaMenulistPlugins',
            array(
                'pluginSlug'         => plugin_basename(MACA_MENULIST_PLUGIN_FILE),
                'ajaxUrl'            => admin_url('admin-ajax.php'),
                'nonce'              => wp_create_nonce('maca_restu_deactivation_feedback'),
                'modalTitle'         => __('Before you deactivate maca Restu Pro', 'maca-restu-pro'),
                'modalIntro'         => __('Help us improve — what is the main reason you are deactivating?', 'maca-restu-pro'),
                'detailsPlaceholder' => __('Tell us a bit more (optional)', 'maca-restu-pro'),
                'cancelLabel'        => __('Cancel', 'maca-restu-pro'),
                'skipLabel'          => __('Skip and deactivate', 'maca-restu-pro'),
                'submitLabel'        => __('Send feedback and deactivate', 'maca-restu-pro'),
                'reasons'            => $reasons,
            )
        );
    }
    
    /**
     * Enqueue admin scripts
     */
    public function enqueue_admin_scripts($hook) {
        if (!is_string($hook) || $hook === '') {
            return;
        }

        // Media library is not needed on guide or backup screens.
        if (
            strpos($hook, 'maca-restu') !== false
            && strpos($hook, 'maca-restu-guide') === false
            && strpos($hook, 'maca-restu-backup') === false
        ) {
            wp_enqueue_media();

            if (strpos($hook, 'maca-restu-settings') !== false) {
                wp_enqueue_style(
                    'maca-menulist-admin-settings',
                    MACA_MENULIST_PLUGIN_URL . 'assets/css/admin-settings.css',
                    array(),
                    MACA_MENULIST_VERSION
                );
                wp_enqueue_script(
                    'maca-menulist-admin-settings-tabs',
                    MACA_MENULIST_PLUGIN_URL . 'assets/js/admin-settings-tabs.js',
                    array('jquery'),
                    MACA_MENULIST_VERSION,
                    true
                );

                wp_enqueue_style(
                    'maca-menulist-style',
                    MACA_MENULIST_PLUGIN_URL . 'assets/css/style.css',
                    array(),
                    MACA_MENULIST_VERSION
                );
                wp_enqueue_style(
                    'maca-menulist-dish-menu-themes',
                    MACA_MENULIST_PLUGIN_URL . 'assets/css/dish-menu-themes.css',
                    array('maca-menulist-style'),
                    MACA_MENULIST_VERSION
                );
                wp_enqueue_style(
                    'maca-menulist-admin-dish-theme-preview',
                    MACA_MENULIST_PLUGIN_URL . 'assets/css/admin-dish-menu-theme-preview.css',
                    array('maca-menulist-dish-menu-themes'),
                    MACA_MENULIST_VERSION
                );
                wp_enqueue_script(
                    'maca-menulist-admin-dish-theme-preview',
                    MACA_MENULIST_PLUGIN_URL . 'assets/js/admin-dish-menu-theme-preview.js',
                    array('jquery'),
                    MACA_MENULIST_VERSION,
                    true
                );
            }

            if (strpos($hook, 'maca-restu-payments') !== false) {
                wp_enqueue_script(
                    'maca-menulist-admin-payments-tabs',
                    MACA_MENULIST_PLUGIN_URL . 'assets/js/admin-payments-tabs.js',
                    array('jquery'),
                    MACA_MENULIST_VERSION,
                    true
                );
            }

            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only screen detection for script enqueue.
            $admin_action = isset($_GET['action']) ? sanitize_key(wp_unslash($_GET['action'])) : 'list';
            if (in_array($admin_action, array('add', 'edit'), true)) {
                wp_enqueue_script(
                    'maca-menulist-admin-record-nav',
                    MACA_MENULIST_PLUGIN_URL . 'assets/js/admin-record-nav.js',
                    array('jquery'),
                    MACA_MENULIST_VERSION,
                    true
                );
                wp_localize_script(
                    'maca-menulist-admin-record-nav',
                    'macaMenulistAdminNav',
                    array(
                        'unsavedMessage' => __(
                            'Du har osparade ändringar. Lämna sidan utan att spara?',
                            'maca-restu-pro'
                        ),
                    )
                );
            }
        }
    }
    
    /**
     * Add admin menu
     */
    public function add_admin_menu() {
        // Main menu
        add_menu_page(
            __('maca Restu', 'maca-restu-pro'),
            __('maca Restu', 'maca-restu-pro'),
            maca_menulist_admin_required_cap(),
            'maca-restu',
            array($this, 'render_categories_page'),
            maca_menulist_get_admin_menu_icon(),
            30
        );
        
        // Categories submenu
        add_submenu_page(
            'maca-restu',
            __('Kategorier', 'maca-restu-pro'),
            __('Kategorier', 'maca-restu-pro'),
            maca_menulist_admin_required_cap(),
            'maca-restu',
            array($this, 'render_categories_page')
        );
        
        // Menus submenu
        add_submenu_page(
            'maca-restu',
            __('Menyer', 'maca-restu-pro'),
            __('Menyer', 'maca-restu-pro'),
            maca_menulist_admin_required_cap(),
            'maca-restu-menus',
            array($this, 'render_menus_page')
        );
        
        // Settings submenu
        add_submenu_page(
            'maca-restu',
            __('Inställningar', 'maca-restu-pro'),
            __('Inställningar', 'maca-restu-pro'),
            maca_menulist_admin_required_cap(),
            'maca-restu-settings',
            array($this, 'render_settings_page')
        );
        
        // Guide submenu
        add_submenu_page(
            'maca-restu',
            __('Guide', 'maca-restu-pro'),
            __('Guide', 'maca-restu-pro'),
            maca_menulist_admin_required_cap(),
            'maca-restu-guide',
            array($this, 'render_guide_page')
        );
        
        // QR Code submenu
        add_submenu_page(
            'maca-restu',
            __('QR-koder', 'maca-restu-pro'),
            __('QR-koder', 'maca-restu-pro'),
            maca_menulist_admin_required_cap(),
            'maca-restu-qr',
            array($this, 'render_qr_page')
        );
    }
    
    /**
     * Handle form submission
     */
    public function handle_form_submission() {
        if (!isset($_POST['maca_action'])) {
            return;
        }
        
        if (!isset($_POST['maca_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['maca_nonce'])), 'maca_save')) {
            return;
        }
        
        if (!maca_menulist_user_can_manage_plugin()) {
            return;
        }
        
        $action = sanitize_text_field(wp_unslash($_POST['maca_action']));
        $type = isset($_POST['maca_type']) ? sanitize_text_field(wp_unslash($_POST['maca_type'])) : '';
        
        if ($type === 'category') {
            if ($action === 'add' || $action === 'edit') {
                $this->save_category();
            } elseif ($action === 'delete') {
                $this->delete_category();
            }
        } elseif ($type === 'menu') {
            if ($action === 'add' || $action === 'edit') {
                $this->save_menu();
            } elseif ($action === 'delete') {
                $this->delete_menu();
            } elseif ($action === 'duplicate') {
                $this->duplicate_menu();
            }
        } elseif ($type === 'settings') {
            $this->save_settings();
        } elseif ($action === 'save_qr') {
            $this->save_qr_settings();
        }
    }
    
    /**
     * Save category
     */
    private function save_category() {
        // Nonce and capability verified in handle_form_submission().
        // phpcs:disable WordPress.Security.NonceVerification.Missing

        try {
            $name = sanitize_text_field(wp_unslash($_POST['category_name'] ?? ''));
            $name_en = sanitize_text_field(wp_unslash($_POST['category_name_en'] ?? ''));
            $thumbnail_url = maca_menulist_normalize_url(esc_url_raw(wp_unslash($_POST['thumbnail_url'] ?? '')));
            $description = sanitize_textarea_field(wp_unslash($_POST['category_description'] ?? ''));
            $description_en = sanitize_textarea_field(wp_unslash($_POST['category_description_en'] ?? ''));
            $sort_order = isset($_POST['sort_order']) ? intval(wp_unslash($_POST['sort_order'])) : 0;
            $category_id = isset($_POST['category_id']) ? intval(wp_unslash($_POST['category_id'])) : 0;

            if (maca_menulist_admin_content_field_missing($name, $name_en)) {
                add_settings_error(
                    'maca_category',
                    'error',
                    maca_menulist_admin_show_local_content_fields()
                        ? __('Category name is required in English or your local language.', 'maca-restu-pro')
                        : __('Category name is required.', 'maca-restu-pro')
                );
                return;
            }

            $row = array(
                'name' => $name,
                'name_en' => $name_en,
                'thumbnail_url' => $thumbnail_url,
                'description' => $description,
                'description_en' => $description_en,
                'sort_order' => $sort_order,
            );

            if ($category_id > 0) {
                $result = maca_menulist_db_update_category($category_id, $row);

                if ($result === false) {
                    add_settings_error('maca_category', 'error', __('Error updating category.', 'maca-restu-pro'));
                    return;
                }
            } else {
                $result = maca_menulist_db_insert_category($row);

                if ($result === false) {
                    add_settings_error('maca_category', 'error', __('Error creating category.', 'maca-restu-pro'));
                    return;
                }
            }

            add_settings_error('maca_category', 'success', __('Category saved successfully.', 'maca-restu-pro'), 'updated');
        } catch (Exception $e) {
            add_settings_error('maca_category', 'error', __('An error occurred: ', 'maca-restu-pro') . $e->getMessage());
        }

        // phpcs:enable WordPress.Security.NonceVerification.Missing
    }
    
    /**
     * Delete category
     */
    private function delete_category() {
        // phpcs:disable WordPress.Security.NonceVerification.Missing
        $category_id = isset($_POST['category_id']) ? intval(wp_unslash($_POST['category_id'])) : 0;
        // phpcs:enable WordPress.Security.NonceVerification.Missing

        if ($category_id > 0) {
            maca_menulist_db_delete_category($category_id);
            add_settings_error('maca_category', 'success', __('Category deleted successfully.', 'maca-restu-pro'), 'updated');
        }
    }
    
    /**
     * Save menu
     */
    private function save_menu() {
        // phpcs:disable WordPress.Security.NonceVerification.Missing
        try {
            $category_id = isset($_POST['category_id']) ? intval(wp_unslash($_POST['category_id'])) : 0;
            $title = sanitize_text_field(wp_unslash($_POST['menu_title'] ?? ''));
            $title_en = sanitize_text_field(wp_unslash($_POST['menu_title_en'] ?? ''));
            $file_url = maca_menulist_normalize_url(esc_url_raw(wp_unslash($_POST['file_url'] ?? '')));
            $file_type = sanitize_text_field(wp_unslash($_POST['file_type'] ?? 'image'));
            $schedule = maca_menulist_parse_schedule_from_request();
            $is_active = isset($_POST['is_active']) ? 1 : 0;
            $menu_id = isset($_POST['menu_id']) ? intval(wp_unslash($_POST['menu_id'])) : 0;
            
            // Handle file upload
            if (isset($_FILES['file_upload']['error']) && UPLOAD_ERR_OK === (int) $_FILES['file_upload']['error']) {
                // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Handled by wp_handle_upload().
                $uploaded_file = $_FILES['file_upload'];
                
                // Check file type
                $file_ext = strtolower(pathinfo($uploaded_file['name'], PATHINFO_EXTENSION));
                $allowed_types = array('jpg', 'jpeg', 'png', 'gif', 'pdf');
                
                if (!in_array($file_ext, $allowed_types)) {
                    add_settings_error('maca_menu', 'error', __('Invalid file type. Please upload an image or PDF.', 'maca-restu-pro'));
                    return;
                }
                
                // Upload to WordPress media library
                $upload = wp_handle_upload($uploaded_file, array('test_form' => false));
                
                if (isset($upload['error'])) {
                    add_settings_error('maca_menu', 'error', __('File upload error: ', 'maca-restu-pro') . $upload['error']);
                    return;
                }
                
                if (isset($upload['url'])) {
                    $file_url = maca_menulist_normalize_url($upload['url']);
                    
                    // Auto-detect file type if not set
                    if ($file_ext === 'pdf') {
                        $file_type = 'pdf';
                    } else {
                        $file_type = 'image';
                    }
                }
            }
            
            if (empty($category_id) || empty($file_url) || maca_menulist_admin_content_field_missing($title, $title_en)) {
                add_settings_error(
                    'maca_menu',
                    'error',
                    maca_menulist_admin_show_local_content_fields()
                        ? __('Category, title (English or local), and file are required.', 'maca-restu-pro')
                        : __('Category, title, and file are required.', 'maca-restu-pro')
                );
                return;
            }

            $row = array(
                'category_id' => $category_id,
                'title' => $title,
                'title_en' => $title_en,
                'file_url' => $file_url,
                'file_type' => $file_type,
                'start_date' => $schedule['start_date'],
                'end_date' => $schedule['end_date'],
                'time_start' => $schedule['time_start'],
                'time_end' => $schedule['time_end'],
                'days_of_week' => $schedule['days_of_week'],
                'is_active' => $is_active,
            );

            if ($menu_id > 0) {
                $result = maca_menulist_db_update_menu($menu_id, $row);

                if ($result === false) {
                    add_settings_error('maca_menu', 'error', __('Error updating menu.', 'maca-restu-pro'));
                    return;
                }
            } else {
                $result = maca_menulist_db_insert_menu($row);

                if ($result === false) {
                    add_settings_error('maca_menu', 'error', __('Error creating menu.', 'maca-restu-pro'));
                    return;
                }
            }
            
            add_settings_error('maca_menu', 'success', __('Menu saved successfully.', 'maca-restu-pro'), 'updated');
        } catch (Exception $e) {
            add_settings_error('maca_menu', 'error', __('An error occurred: ', 'maca-restu-pro') . $e->getMessage());
        }

        // phpcs:enable WordPress.Security.NonceVerification.Missing
    }
    
    /**
     * Delete menu
     */
    private function delete_menu() {
        // phpcs:disable WordPress.Security.NonceVerification.Missing
        $menu_id = isset($_POST['menu_id']) ? intval(wp_unslash($_POST['menu_id'])) : 0;
        // phpcs:enable WordPress.Security.NonceVerification.Missing

        if ($menu_id > 0) {
            maca_menulist_db_delete_menu($menu_id);
            add_settings_error('maca_menu', 'success', __('Menu deleted successfully.', 'maca-restu-pro'), 'updated');
        }
    }

    /**
     * Duplicate menu
     */
    private function duplicate_menu() {
        // phpcs:disable WordPress.Security.NonceVerification.Missing
        $menu_id = isset($_POST['menu_id']) ? intval(wp_unslash($_POST['menu_id'])) : 0;
        // phpcs:enable WordPress.Security.NonceVerification.Missing

        if ($menu_id <= 0) {
            return;
        }

        $new_menu_id = maca_menulist_db_duplicate_menu($menu_id);
        if ($new_menu_id === false) {
            add_settings_error('maca_menu', 'error', __('Could not duplicate menu.', 'maca-restu-pro'));
            return;
        }

        add_settings_error('maca_menu', 'success', __('Menu duplicated successfully.', 'maca-restu-pro'), 'updated');
    }
    
    /**
     * Render categories page
     */
    public function render_categories_page() {
        if (maca_menulist_is_dishes_mode()) {
            wp_safe_redirect(admin_url('admin.php?page=maca-restu-dish-categories'));
            exit;
        }

        // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only admin navigation; writes use POST + nonce.
        $action = isset($_GET['action']) ? sanitize_text_field(wp_unslash($_GET['action'])) : 'list';
        $category_id = isset($_GET['category_id']) ? intval($_GET['category_id']) : 0;
        // phpcs:enable WordPress.Security.NonceVerification.Recommended
        
        ?>
        <div class="wrap">
            <h1><?php esc_html_e('Menu Categories', 'maca-restu-pro'); ?></h1>
            
            <?php settings_errors('maca_category'); ?>
            
            <?php if ($action === 'add' || $action === 'edit') : ?>
                <?php $this->render_category_form($action, $category_id); ?>
            <?php else : ?>
                <?php $this->render_categories_list(); ?>
            <?php endif; ?>
        </div>
        <?php
    }
    
    /**
     * Render category form
     */
    private function render_category_form($action, $category_id) {
        $category = null;
        if ($action === 'edit' && $category_id > 0) {
            $category = maca_menulist_db_get_category($category_id);
        }
        
        $name = $category ? $category->name : '';
        $name_en = ($category && isset($category->name_en)) ? $category->name_en : '';
        $thumbnail_url = $category ? $category->thumbnail_url : '';
        $description = $category ? $category->description : '';
        $description_en = ($category && isset($category->description_en)) ? $category->description_en : '';
        $sort_order = $category ? $category->sort_order : 0;
        $preset_thumbnail = '';
        
        // Check if current thumbnail is a preset
        $presets = array(
            'drink' => MACA_MENULIST_PLUGIN_URL . 'assets/thumbnails/drink.svg',
            'cafe' => MACA_MENULIST_PLUGIN_URL . 'assets/thumbnails/cafe.svg',
            'lunch' => MACA_MENULIST_PLUGIN_URL . 'assets/thumbnails/lunch.svg',
            'dinner' => MACA_MENULIST_PLUGIN_URL . 'assets/thumbnails/dinner.svg',
            'tapas' => MACA_MENULIST_PLUGIN_URL . 'assets/thumbnails/tapas.svg',
            'pizza' => MACA_MENULIST_PLUGIN_URL . 'assets/thumbnails/pizza.svg',
            'burgers' => MACA_MENULIST_PLUGIN_URL . 'assets/thumbnails/burgers.svg'
        );
        
        foreach ($presets as $key => $url) {
            if ($thumbnail_url === $url) {
                $preset_thumbnail = $key;
                break;
            }
        }
        
        ?>
        <h2><?php echo esc_html($action === 'add' ? __('Add New Category', 'maca-restu-pro') : __('Edit Category', 'maca-restu-pro')); ?></h2>
        <?php
        $category_nav = array(
            'action' => $action,
            'current_id' => $category_id,
            'records' => maca_menulist_db_get_categories(false),
            'list_url' => admin_url('admin.php?page=maca-restu'),
            'edit_page' => 'maca-restu',
            'edit_id_param' => 'category_id',
        );
        maca_menulist_render_admin_record_navigation($category_nav);
        ?>
        
        <form method="post" action="" class="maca-admin-record-form">
            <?php wp_nonce_field('maca_save', 'maca_nonce'); ?>
            <input type="hidden" name="maca_action" value="<?php echo esc_attr($action); ?>">
            <input type="hidden" name="maca_type" value="category">
            <input type="hidden" name="category_id" value="<?php echo esc_attr($category_id); ?>">
            
            <table class="form-table">
                <tr>
                    <th scope="row">
                        <label for="category_name"><?php echo esc_html(maca_menulist_admin_primary_field_label(__('Category Name', 'maca-restu-pro'))); ?></label>
                    </th>
                    <td>
                        <input type="text" id="category_name" name="category_name" value="<?php echo esc_attr($name); ?>" class="regular-text">
                    </td>
                </tr>

                <?php if (maca_menulist_admin_show_local_content_fields()) : ?>
                <tr>
                    <th scope="row">
                        <label for="category_name_en"><?php echo esc_html(maca_menulist_bilingual_field_label(__('Category Name', 'maca-restu-pro'), true)); ?></label>
                    </th>
                    <td>
                        <input type="text" id="category_name_en" name="category_name_en" value="<?php echo esc_attr($name_en); ?>" class="regular-text">
                        <p class="description"><?php esc_html_e('English text for international guests and the flag switcher on menus.', 'maca-restu-pro'); ?></p>
                    </td>
                </tr>
                <?php endif; ?>
                
                <tr>
                    <th scope="row">
                        <label for="thumbnail_url"><?php esc_html_e('Thumbnail Image', 'maca-restu-pro'); ?></label>
                    </th>
                    <td>
                        <p class="description"><?php esc_html_e('Select a preset image or upload your own:', 'maca-restu-pro'); ?></p>
                        <select id="maca-preset-thumbnail" name="preset_thumbnail" class="regular-text">
                            <option value=""><?php esc_html_e('-- Select preset image --', 'maca-restu-pro'); ?></option>
                            <option value="drink" <?php selected($preset_thumbnail, 'drink'); ?>><?php esc_html_e('Drink', 'maca-restu-pro'); ?></option>
                            <option value="cafe" <?php selected($preset_thumbnail, 'cafe'); ?>><?php esc_html_e('Cafe', 'maca-restu-pro'); ?></option>
                            <option value="lunch" <?php selected($preset_thumbnail, 'lunch'); ?>><?php esc_html_e('Lunch', 'maca-restu-pro'); ?></option>
                            <option value="dinner" <?php selected($preset_thumbnail, 'dinner'); ?>><?php esc_html_e('Dinner', 'maca-restu-pro'); ?></option>
                            <option value="tapas" <?php selected($preset_thumbnail, 'tapas'); ?>><?php esc_html_e('Tapas', 'maca-restu-pro'); ?></option>
                            <option value="pizza" <?php selected($preset_thumbnail, 'pizza'); ?>><?php esc_html_e('Pizza', 'maca-restu-pro'); ?></option>
                            <option value="burgers" <?php selected($preset_thumbnail, 'burgers'); ?>><?php esc_html_e('Burgers', 'maca-restu-pro'); ?></option>
                        </select>
                        <p class="description"><?php esc_html_e('Or upload a custom image:', 'maca-restu-pro'); ?></p>
                        <input type="text" id="thumbnail_url" name="thumbnail_url" value="<?php echo esc_attr($thumbnail_url); ?>" class="regular-text">
                        <button type="button" class="button" id="upload_thumbnail_button"><?php esc_html_e('Upload Image', 'maca-restu-pro'); ?></button>
                        <p class="description"><?php esc_html_e('Thumbnail for the category button (optional)', 'maca-restu-pro'); ?></p>
                        <?php if ($thumbnail_url) : ?>
                            <div class="image-preview">
                                <img src="<?php echo esc_url($thumbnail_url); ?>" alt="<?php echo esc_attr($name); ?>" style="max-width: 100px; margin-top: 10px;">
                            </div>
                        <?php endif; ?>
                    </td>
                </tr>
                
                <tr>
                    <th scope="row">
                        <label for="category_description"><?php echo esc_html(maca_menulist_admin_primary_field_label(__('Description', 'maca-restu-pro'))); ?></label>
                    </th>
                    <td>
                        <textarea id="category_description" name="category_description" rows="5" class="large-text"><?php echo esc_textarea($description); ?></textarea>
                        <?php if (!maca_menulist_admin_show_local_content_fields()) : ?>
                            <p class="description"><?php esc_html_e('Optional description for this category', 'maca-restu-pro'); ?></p>
                        <?php endif; ?>
                    </td>
                </tr>

                <?php if (maca_menulist_admin_show_local_content_fields()) : ?>
                <tr>
                    <th scope="row">
                        <label for="category_description_en"><?php echo esc_html(maca_menulist_bilingual_field_label(__('Description', 'maca-restu-pro'), true)); ?></label>
                    </th>
                    <td>
                        <textarea id="category_description_en" name="category_description_en" rows="5" class="large-text"><?php echo esc_textarea($description_en); ?></textarea>
                        <p class="description"><?php esc_html_e('Optional description for this category', 'maca-restu-pro'); ?></p>
                    </td>
                </tr>
                <?php endif; ?>
                
                <tr>
                    <th scope="row">
                        <label for="sort_order"><?php esc_html_e('Sort Order', 'maca-restu-pro'); ?></label>
                    </th>
                    <td>
                        <input type="number" id="sort_order" name="sort_order" value="<?php echo esc_attr($sort_order); ?>" class="small-text" min="0">
                        <p class="description"><?php esc_html_e('Lower numbers appear first. Default is 0.', 'maca-restu-pro'); ?></p>
                    </td>
                </tr>
            </table>
            
            <?php submit_button($action === 'add' ? __('Add Category', 'maca-restu-pro') : __('Update Category', 'maca-restu-pro')); ?>
            <?php maca_menulist_render_admin_record_navigation(array_merge($category_nav, array('modifier' => 'bottom'))); ?>
        </form>
        
        <script>
            jQuery(document).ready(function($) {
                var presets = {
                    'drink': '<?php echo esc_url(MACA_MENULIST_PLUGIN_URL . 'assets/thumbnails/drink.svg'); ?>',
                    'cafe': '<?php echo esc_url(MACA_MENULIST_PLUGIN_URL . 'assets/thumbnails/cafe.svg'); ?>',
                    'lunch': '<?php echo esc_url(MACA_MENULIST_PLUGIN_URL . 'assets/thumbnails/lunch.svg'); ?>',
                    'dinner': '<?php echo esc_url(MACA_MENULIST_PLUGIN_URL . 'assets/thumbnails/dinner.svg'); ?>',
                    'tapas': '<?php echo esc_url(MACA_MENULIST_PLUGIN_URL . 'assets/thumbnails/tapas.svg'); ?>',
                    'pizza': '<?php echo esc_url(MACA_MENULIST_PLUGIN_URL . 'assets/thumbnails/pizza.svg'); ?>',
                    'burgers': '<?php echo esc_url(MACA_MENULIST_PLUGIN_URL . 'assets/thumbnails/burgers.svg'); ?>'
                };
                
                $('#maca-preset-thumbnail').on('change', function() {
                    var selected = $(this).val();
                    if (selected && presets[selected]) {
                        $('#thumbnail_url').val(presets[selected]);
                        $('.image-preview').html('<img src="' + presets[selected] + '" alt="<?php echo esc_attr($name); ?>" style="max-width: 100px; margin-top: 10px;">');
                    }
                });
                
                $('#upload_thumbnail_button').on('click', function(e) {
                    e.preventDefault();
                    
                    var mediaUploader = wp.media({
                        title: '<?php esc_html_e('Select Thumbnail', 'maca-restu-pro'); ?>',
                        button: {
                            text: '<?php esc_html_e('Use This Image', 'maca-restu-pro'); ?>'
                        },
                        multiple: false
                    });
                    
                    mediaUploader.on('select', function() {
                        var attachment = mediaUploader.state().get('selection').first().toJSON();
                        $('#thumbnail_url').val(attachment.url);
                        $('#maca-preset-thumbnail').val('');
                        $('.image-preview').html('<img src="' + attachment.url + '" alt="<?php echo esc_attr($name); ?>" style="max-width: 100px; margin-top: 10px;">');
                    });
                    
                    mediaUploader.open();
                });
            });
        </script>
        <?php
    }
    
    /**
     * Render categories list
     */
    private function render_categories_list() {
        $categories = maca_menulist_db_get_categories(true);
        
        ?>
        <p>
            <a href="<?php echo esc_url(admin_url('admin.php?page=maca-restu&action=add')); ?>" class="button button-primary">
                <?php esc_html_e('Add New Category', 'maca-restu-pro'); ?>
            </a>
        </p>
        
        <?php if (empty($categories)) : ?>
            <p><?php esc_html_e('No categories found. Add your first category above.', 'maca-restu-pro'); ?></p>
        <?php else : ?>
            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th><?php esc_html_e('Name', 'maca-restu-pro'); ?></th>
                        <th><?php esc_html_e('Thumbnail', 'maca-restu-pro'); ?></th>
                        <th><?php esc_html_e('Description', 'maca-restu-pro'); ?></th>
                        <th><?php esc_html_e('Actions', 'maca-restu-pro'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($categories as $category) : ?>
                        <tr>
                            <td>
                                <strong><?php echo esc_html(maca_menulist_get_admin_content_label($category->name, isset($category->name_en) ? $category->name_en : '')); ?></strong>
                            </td>
                            <td>
                                <?php if ($category->thumbnail_url) : ?>
                                    <img src="<?php echo esc_url($category->thumbnail_url); ?>" alt="<?php echo esc_attr($category->name); ?>" style="max-width: 50px; max-height: 50px;">
                                <?php else : ?>
                                    <em><?php esc_html_e('No thumbnail', 'maca-restu-pro'); ?></em>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php echo esc_html(wp_trim_words($category->description, 10)); ?>
                            </td>
                            <td>
                                <a href="<?php echo esc_url( admin_url('admin.php?page=maca-restu&action=edit&category_id=' . $category->id) ); ?>" class="button button-small">
                                    <?php esc_html_e('Edit', 'maca-restu-pro'); ?>
                                </a>
                                <form method="post" action="" style="display: inline;">
                                    <?php wp_nonce_field('maca_save', 'maca_nonce'); ?>
                                    <input type="hidden" name="maca_action" value="delete">
                                    <input type="hidden" name="maca_type" value="category">
                                    <input type="hidden" name="category_id" value="<?php echo esc_attr($category->id); ?>">
                                    <button type="submit" class="button button-small" onclick="return confirm('<?php esc_html_e('Are you sure you want to delete this category? All associated menus will also be deleted.', 'maca-restu-pro'); ?>');">
                                        <?php esc_html_e('Delete', 'maca-restu-pro'); ?>
                                    </button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
        <?php
    }
    
    /**
     * Render menus page
     */
    public function render_menus_page() {
        if (maca_menulist_is_dishes_mode()) {
            wp_safe_redirect(admin_url('admin.php?page=maca-restu-dishes'));
            exit;
        }

        // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only admin navigation; writes use POST + nonce.
        $action = isset($_GET['action']) ? sanitize_text_field(wp_unslash($_GET['action'])) : 'list';
        $menu_id = isset($_GET['menu_id']) ? intval($_GET['menu_id']) : 0;
        // phpcs:enable WordPress.Security.NonceVerification.Recommended
        
        ?>
        <div class="wrap">
            <h1><?php esc_html_e('Menu Files', 'maca-restu-pro'); ?></h1>
            
            <?php settings_errors('maca_menu'); ?>
            
            <?php if ($action === 'add' || $action === 'edit') : ?>
                <?php $this->render_menu_form($action, $menu_id); ?>
            <?php else : ?>
                <?php $this->render_menus_list(); ?>
            <?php endif; ?>
        </div>
        <?php
    }
    
    /**
     * Render menu form
     */
    private function render_menu_form($action, $menu_id) {
        $menu = null;
        if ($action === 'edit' && $menu_id > 0) {
            $menu = maca_menulist_db_get_menu($menu_id);
        }
        
        $category_id = $menu ? $menu->category_id : 0;
        $title = $menu ? $menu->title : '';
        $title_en = ($menu && isset($menu->title_en)) ? $menu->title_en : '';
        $file_url = $menu ? $menu->file_url : '';
        $file_type = $menu ? $menu->file_type : 'pdf';
        $start_date = $menu ? maca_menulist_format_datetime_local_value($menu->start_date) : '';
        $end_date = $menu ? maca_menulist_format_datetime_local_value($menu->end_date) : '';
        $time_start = ($menu && !empty($menu->time_start)) ? substr($menu->time_start, 0, 5) : '';
        $time_end = ($menu && !empty($menu->time_end)) ? substr($menu->time_end, 0, 5) : '';
        $selected_days = $menu ? maca_menulist_parse_days_of_week($menu->days_of_week ?? '') : array();
        $is_active = $menu ? $menu->is_active : 1;
        $weekday_labels = maca_menulist_weekday_labels_ordered();
        
        $categories = maca_menulist_db_get_categories(false);
        
        ?>
        <h2><?php echo esc_html($action === 'add' ? __('Add New Menu', 'maca-restu-pro') : __('Edit Menu', 'maca-restu-pro')); ?></h2>
        <?php
        $menu_nav = array(
            'action' => $action,
            'current_id' => $menu_id,
            'records' => maca_menulist_db_get_menus_with_categories(),
            'list_url' => admin_url('admin.php?page=maca-restu-menus'),
            'edit_page' => 'maca-restu-menus',
            'edit_id_param' => 'menu_id',
        );
        maca_menulist_render_admin_record_navigation($menu_nav);
        ?>
        
        <form method="post" action="" enctype="multipart/form-data" class="maca-admin-record-form">
            <?php wp_nonce_field('maca_save', 'maca_nonce'); ?>
            <input type="hidden" name="maca_action" value="<?php echo esc_attr($action); ?>">
            <input type="hidden" name="maca_type" value="menu">
            <input type="hidden" name="menu_id" value="<?php echo esc_attr($menu_id); ?>">
            
            <table class="form-table">
                <tr>
                    <th scope="row">
                        <label for="category_id"><?php esc_html_e('Category', 'maca-restu-pro'); ?></label>
                    </th>
                    <td>
                        <select id="category_id" name="category_id" required>
                            <option value=""><?php esc_html_e('Select a category', 'maca-restu-pro'); ?></option>
                            <?php foreach ($categories as $cat) : ?>
                                <option value="<?php echo esc_attr($cat->id); ?>" <?php selected($category_id, $cat->id); ?>>
                                    <?php echo esc_html(maca_menulist_get_category_display_name($cat)); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <?php if (empty($categories)) : ?>
                            <p class="description">
                                <?php esc_html_e('No categories found. Please create a category first.', 'maca-restu-pro'); ?>
                                <a href="<?php echo esc_url( admin_url('admin.php?page=maca-restu') ); ?>"><?php esc_html_e('Go to Categories', 'maca-restu-pro'); ?></a>
                            </p>
                        <?php endif; ?>
                    </td>
                </tr>
                
                <tr>
                    <th scope="row">
                        <label for="menu_title"><?php echo esc_html(maca_menulist_admin_primary_field_label(__('Menu Title', 'maca-restu-pro'))); ?></label>
                    </th>
                    <td>
                        <input type="text" id="menu_title" name="menu_title" value="<?php echo esc_attr($title); ?>" class="regular-text">
                    </td>
                </tr>

                <?php if (maca_menulist_admin_show_local_content_fields()) : ?>
                <tr>
                    <th scope="row">
                        <label for="menu_title_en"><?php echo esc_html(maca_menulist_bilingual_field_label(__('Menu Title', 'maca-restu-pro'), true)); ?></label>
                    </th>
                    <td>
                        <input type="text" id="menu_title_en" name="menu_title_en" value="<?php echo esc_attr($title_en); ?>" class="regular-text">
                    </td>
                </tr>
                <?php endif; ?>
                
                <tr>
                    <th scope="row">
                        <label for="file_type"><?php esc_html_e('File Type', 'maca-restu-pro'); ?></label>
                    </th>
                    <td>
                        <select id="file_type" name="file_type">
                            <option value="image" <?php selected($file_type, 'image'); ?>><?php esc_html_e('Image', 'maca-restu-pro'); ?></option>
                            <option value="pdf" <?php selected($file_type, 'pdf'); ?>><?php esc_html_e('PDF', 'maca-restu-pro'); ?></option>
                        </select>
                    </td>
                </tr>
                
                <tr>
                    <th scope="row">
                        <label><?php esc_html_e('Upload File', 'maca-restu-pro'); ?></label>
                    </th>
                    <td>
                        <div id="maca-drop-zone" class="maca-drop-zone">
                            <div class="maca-drop-zone-content">
                                <span class="dashicons dashicons-upload"></span>
                                <p><?php esc_html_e('Drag & drop a file here or', 'maca-restu-pro'); ?></p>
                                <button type="button" class="button" id="maca-browse-files"><?php esc_html_e('Browse Files', 'maca-restu-pro'); ?></button>
                                <input type="file" id="file_upload" name="file_upload" accept="image/*,.pdf" style="display: none;">
                            </div>
                            <div id="maca-file-preview" class="maca-file-preview" style="display: none;">
                                <span class="dashicons dashicons-media"></span>
                                <span id="maca-file-name"></span>
                                <button type="button" class="button button-small" id="maca-remove-file"><?php esc_html_e('Remove', 'maca-restu-pro'); ?></button>
                            </div>
                        </div>
                        <p class="description"><?php esc_html_e('Accepts images (JPG, PNG, GIF) and PDF files', 'maca-restu-pro'); ?></p>
                    </td>
                </tr>
                
                <tr>
                    <th scope="row">
                        <label for="file_url"><?php esc_html_e('File URL', 'maca-restu-pro'); ?></label>
                    </th>
                    <td>
                        <input type="text" id="file_url" name="file_url" value="<?php echo esc_attr($file_url); ?>" class="regular-text">
                        <button type="button" class="button" id="upload_file_button"><?php esc_html_e('Select from Media Library', 'maca-restu-pro'); ?></button>
                        <p class="description"><?php esc_html_e('Or select a file from media library', 'maca-restu-pro'); ?></p>
                        <?php if ($file_url) : ?>
                            <div class="file-preview">
                                <?php if ($file_type === 'pdf') : ?>
                                    <a href="<?php echo esc_url($file_url); ?>" target="_blank"><?php esc_html_e('View PDF', 'maca-restu-pro'); ?></a>
                                <?php else : ?>
                                    <img src="<?php echo esc_url($file_url); ?>" alt="<?php echo esc_attr($title); ?>" style="max-width: 300px; margin-top: 10px;">
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    </td>
                </tr>
                
                <tr>
                    <th scope="row">
                        <label for="start_date"><?php esc_html_e('Start Date', 'maca-restu-pro'); ?></label>
                    </th>
                    <td>
                        <input type="datetime-local" id="start_date" name="start_date" value="<?php echo esc_attr($start_date); ?>">
                        <p class="description"><?php esc_html_e('Optional: When to start showing this menu', 'maca-restu-pro'); ?></p>
                    </td>
                </tr>
                
                <tr>
                    <th scope="row">
                        <label for="end_date"><?php esc_html_e('End Date', 'maca-restu-pro'); ?></label>
                    </th>
                    <td>
                        <input type="datetime-local" id="end_date" name="end_date" value="<?php echo esc_attr($end_date); ?>">
                        <p class="description"><?php esc_html_e('Optional: When to stop showing this menu', 'maca-restu-pro'); ?></p>
                        <div style="background: #000; color: #fff; padding: 10px; margin-top: 10px; border-radius: 4px;">
                            <strong><?php esc_html_e('Current site time:', 'maca-restu-pro'); ?></strong> <?php echo esc_html(maca_menulist_format_wp_datetime(maca_menulist_wp_now_mysql())); ?>
                        </div>
                    </td>
                </tr>
                
                <tr>
                    <th scope="row">
                        <label><?php esc_html_e('Days of week', 'maca-restu-pro'); ?></label>
                    </th>
                    <td>
                        <fieldset>
                            <legend class="screen-reader-text"><?php esc_html_e('Days of week', 'maca-restu-pro'); ?></legend>
                            <?php foreach ($weekday_labels as $day_num => $day_label) : ?>
                                <label style="display:inline-block;margin-right:12px;margin-bottom:6px;">
                                    <input type="checkbox" name="days_of_week[]" value="<?php echo esc_attr($day_num); ?>" <?php checked(in_array($day_num, $selected_days, true)); ?>>
                                    <?php echo esc_html($day_label); ?>
                                </label>
                            <?php endforeach; ?>
                        </fieldset>
                        <p class="description"><?php esc_html_e('Leave all unchecked to show every day. Useful for e.g. lunch menu Monday–Friday only.', 'maca-restu-pro'); ?></p>
                    </td>
                </tr>

                <tr>
                    <th scope="row">
                        <label for="time_start"><?php esc_html_e('Daily start time', 'maca-restu-pro'); ?></label>
                    </th>
                    <td>
                        <input type="time" id="time_start" name="time_start" value="<?php echo esc_attr($time_start); ?>">
                        <p class="description"><?php esc_html_e('Optional: e.g. 11:00 for lunch menu. Leave empty for all day.', 'maca-restu-pro'); ?></p>
                    </td>
                </tr>

                <tr>
                    <th scope="row">
                        <label for="time_end"><?php esc_html_e('Daily end time', 'maca-restu-pro'); ?></label>
                    </th>
                    <td>
                        <input type="time" id="time_end" name="time_end" value="<?php echo esc_attr($time_end); ?>">
                        <p class="description"><?php esc_html_e('Optional: e.g. 14:00. For evening menus past midnight you can set e.g. 22:00–02:00.', 'maca-restu-pro'); ?></p>
                    </td>
                </tr>

                <tr>
                    <th scope="row">
                        <label for="is_active"><?php esc_html_e('Active', 'maca-restu-pro'); ?></label>
                    </th>
                    <td>
                        <input type="checkbox" id="is_active" name="is_active" value="1" <?php checked($is_active, 1); ?>>
                        <label for="is_active"><?php esc_html_e('Enable this menu', 'maca-restu-pro'); ?></label>
                    </td>
                </tr>
            </table>
            
            <?php submit_button($action === 'add' ? __('Add Menu', 'maca-restu-pro') : __('Update Menu', 'maca-restu-pro')); ?>
            <?php maca_menulist_render_admin_record_navigation(array_merge($menu_nav, array('modifier' => 'bottom'))); ?>
        </form>
        
        <script>
            jQuery(document).ready(function($) {
                // Media library uploader
                $('#upload_file_button').on('click', function(e) {
                    e.preventDefault();
                    
                    var file_type = $('#file_type').val();
                    var title = file_type === 'pdf' ? '<?php esc_html_e('Select PDF File', 'maca-restu-pro'); ?>' : '<?php esc_html_e('Select Menu Image', 'maca-restu-pro'); ?>';
                    
                    var mediaUploader = wp.media({
                        title: title,
                        button: {
                            text: '<?php esc_html_e('Use This File', 'maca-restu-pro'); ?>'
                        },
                        multiple: false
                    });
                    
                    mediaUploader.on('select', function() {
                        var attachment = mediaUploader.state().get('selection').first().toJSON();
                        $('#file_url').val(attachment.url);
                        
                        if (file_type === 'pdf') {
                            $('.file-preview').html('<a href="' + attachment.url + '" target="_blank"><?php esc_html_e('View PDF', 'maca-restu-pro'); ?></a>');
                        } else {
                            $('.file-preview').html('<img src="' + attachment.url + '" alt="<?php echo esc_attr($title); ?>" style="max-width: 300px; margin-top: 10px;">');
                        }
                    });
                    
                    mediaUploader.open();
                });
                
                // Drag and drop functionality
                var dropZone = $('#maca-drop-zone');
                var fileInput = $('#file_upload');
                var browseBtn = $('#maca-browse-files');
                var removeBtn = $('#maca-remove-file');
                var dropContent = $('.maca-drop-zone-content');
                var filePreview = $('#maca-file-preview');
                var fileName = $('#maca-file-name');
                
                // Browse files button
                browseBtn.on('click', function(e) {
                    e.preventDefault();
                    fileInput.click();
                });
                
                // File input change
                fileInput.on('change', function(e) {
                    handleFile(this.files[0]);
                });
                
                // Drag and drop events
                dropZone.on('dragover', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    dropZone.addClass('drag-over');
                });
                
                dropZone.on('dragleave', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    dropZone.removeClass('drag-over');
                });
                
                dropZone.on('drop', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    dropZone.removeClass('drag-over');
                    
                    var files = e.originalEvent.dataTransfer.files;
                    if (files.length > 0) {
                        fileInput[0].files = files;
                        handleFile(files[0]);
                    }
                });
                
                // Remove file
                removeBtn.on('click', function(e) {
                    e.preventDefault();
                    fileInput.val('');
                    dropContent.show();
                    filePreview.hide();
                });
                
                // Handle file selection
                function handleFile(file) {
                    if (!file) return;
                    
                    // Check file type
                    var allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'application/pdf'];
                    var fileExt = file.name.split('.').pop().toLowerCase();
                    var allowedExts = ['jpg', 'jpeg', 'png', 'gif', 'pdf'];
                    
                    if (allowedTypes.indexOf(file.type) === -1 && allowedExts.indexOf(fileExt) === -1) {
                        alert('<?php esc_html_e('Invalid file type. Please upload an image or PDF.', 'maca-restu-pro'); ?>');
                        return;
                    }
                    
                    // Show file preview
                    fileName.text(file.name);
                    dropContent.hide();
                    filePreview.show();
                    
                    // Auto-detect file type
                    if (fileExt === 'pdf' || file.type === 'application/pdf') {
                        $('#file_type').val('pdf');
                    } else {
                        $('#file_type').val('image');
                    }
                }
            });
        </script>
        <?php
    }
    
    /**
     * Render menus list
     */
    private function render_menus_list() {
        $menus = maca_menulist_db_get_menus_with_categories();
        
        ?>
        <p>
            <a href="<?php echo esc_url( admin_url('admin.php?page=maca-restu-menus&action=add') ); ?>" class="button button-primary">
                <?php esc_html_e('Add New Menu', 'maca-restu-pro'); ?>
            </a>
        </p>
        
        <?php if (empty($menus)) : ?>
            <p><?php esc_html_e('No menus found. Add your first menu above.', 'maca-restu-pro'); ?></p>
        <?php else : ?>
            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th><?php esc_html_e('Title', 'maca-restu-pro'); ?></th>
                        <th><?php esc_html_e('Category', 'maca-restu-pro'); ?></th>
                        <th><?php esc_html_e('File Type', 'maca-restu-pro'); ?></th>
                        <th><?php esc_html_e('Schedule', 'maca-restu-pro'); ?></th>
                        <th><?php esc_html_e('Actions', 'maca-restu-pro'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($menus as $menu) : ?>
                        <?php
                        $schedule_display = maca_menulist_get_admin_menu_schedule_display($menu);
                        $status = $schedule_display['status'];
                        $preview_url = admin_url('admin.php?page=maca-restu-menu-preview');
                        ?>
                        <tr>
                            <td>
                                <strong><?php echo esc_html(maca_menulist_get_admin_content_label($menu->title, isset($menu->title_en) ? $menu->title_en : '')); ?></strong>
                            </td>
                            <td>
                                <?php echo esc_html($menu->category_name); ?>
                            </td>
                            <td>
                                <?php echo esc_html(ucfirst($menu->file_type)); ?>
                            </td>
                            <td>
                                <span class="maca-menu-schedule status-<?php echo esc_attr($status); ?>">
                                    <?php echo esc_html($schedule_display['line']); ?>
                                </span>
                                <div class="maca-menu-schedule-links">
                                    <a href="<?php echo esc_url($preview_url); ?>">
                                        <?php echo esc_html_x('Preview', 'menu schedule link', 'maca-restu-pro'); ?>
                                    </a>
                                </div>
                            </td>
                            <td>
                                <a href="<?php echo esc_url( admin_url('admin.php?page=maca-restu-menus&action=edit&menu_id=' . $menu->id) ); ?>" class="button button-small">
                                    <?php esc_html_e('Edit', 'maca-restu-pro'); ?>
                                </a>
                                <form method="post" action="" style="display: inline;">
                                    <?php wp_nonce_field('maca_save', 'maca_nonce'); ?>
                                    <input type="hidden" name="maca_action" value="duplicate">
                                    <input type="hidden" name="maca_type" value="menu">
                                    <input type="hidden" name="menu_id" value="<?php echo esc_attr($menu->id); ?>">
                                    <button type="submit" class="button button-small">
                                        <?php esc_html_e('Duplicate', 'maca-restu-pro'); ?>
                                    </button>
                                </form>
                                <form method="post" action="" style="display: inline;">
                                    <?php wp_nonce_field('maca_save', 'maca_nonce'); ?>
                                    <input type="hidden" name="maca_action" value="delete">
                                    <input type="hidden" name="maca_type" value="menu">
                                    <input type="hidden" name="menu_id" value="<?php echo esc_attr($menu->id); ?>">
                                    <button type="submit" class="button button-small" onclick="return confirm('<?php esc_html_e('Are you sure you want to delete this menu?', 'maca-restu-pro'); ?>');">
                                        <?php esc_html_e('Delete', 'maca-restu-pro'); ?>
                                    </button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
        <?php
    }
    
    /**
     * Save settings
     */
    private function save_settings() {
        // phpcs:disable WordPress.Security.NonceVerification.Missing
        if (!empty($_POST['maca_flush_rewrites'])) {
            maca_menulist_flush_rewrite_rules();
            add_settings_error(
                'maca_settings',
                'maca_flush_rewrites',
                __('Permalink rules for menu URLs were refreshed.', 'maca-restu-pro'),
                'updated'
            );
        }

        $content_mode = isset($_POST['maca_content_mode']) ? sanitize_text_field(wp_unslash($_POST['maca_content_mode'])) : 'files';
        $price_currency = isset($_POST['maca_price_currency']) ? sanitize_text_field(wp_unslash($_POST['maca_price_currency'])) : 'kr';
        $display_mode = isset($_POST['maca_display_mode']) ? sanitize_text_field(wp_unslash($_POST['maca_display_mode'])) : 'inline';
        $button_layout = isset($_POST['maca_button_layout']) ? sanitize_text_field(wp_unslash($_POST['maca_button_layout'])) : 'horizontal';
        $pdf_display_mode = isset($_POST['maca_pdf_display_mode']) ? sanitize_text_field(wp_unslash($_POST['maca_pdf_display_mode'])) : 'full_page';
        $show_menu_title = isset($_POST['maca_show_menu_title']) ? '1' : '0';
        $public_keep_files_during_migration = isset($_POST['maca_public_keep_files_during_migration']) ? '1' : '0';
        if (maca_menulist_bilingual_menus_available()) {
            $dual_language_menu = isset($_POST['maca_dual_language_menu']) ? '1' : '0';
            $menu_language_switcher = isset($_POST['maca_menu_language_switcher']) ? '1' : '0';
            if (maca_menulist_site_locale_is_english()) {
                $dual_language_menu = '0';
                $menu_language_switcher = '0';
            } elseif ($dual_language_menu === '1') {
                $menu_language_switcher = '0';
            }
        }
        $show_schedule_notes = isset($_POST['maca_show_schedule_notes']) ? '1' : '0';
        $dish_category_filter = isset($_POST['maca_dish_category_filter']) ? '1' : '0';
        $dish_category_nav = isset($_POST['maca_dish_category_nav']) ? sanitize_text_field(wp_unslash($_POST['maca_dish_category_nav'])) : 'buttons';
        if (!in_array($dish_category_nav, array('buttons', 'dropdown'), true)) {
            $dish_category_nav = 'buttons';
        }
        $dish_clickable_images = isset($_POST['maca_dish_clickable_images']) ? '1' : '0';
        $dish_menu_theme = isset($_POST['maca_dish_menu_theme']) ? sanitize_key(wp_unslash($_POST['maca_dish_menu_theme'])) : 'light';
        $dish_menu_layout = isset($_POST['maca_dish_menu_layout']) ? sanitize_key(wp_unslash($_POST['maca_dish_menu_layout'])) : 'rows';
        $campaign_exclusive_mode = isset($_POST['maca_campaign_exclusive_mode']) ? '1' : '0';
        $dish_guest_ratings = isset($_POST['maca_dish_guest_ratings']) ? '1' : '0';
        $table_order = isset($_POST['maca_table_order']) ? '1' : '0';
        $table_order_line_notes = isset($_POST['maca_table_order_line_notes']) ? '1' : '0';
        $table_order_order_note = isset($_POST['maca_table_order_order_note']) ? '1' : '0';
        $table_order_show_prices = isset($_POST['maca_table_order_show_prices']) ? '1' : '0';
        $table_order_guest_status = isset($_POST['maca_table_order_guest_status']) ? '1' : '0';
        $table_order_delivery_mode = isset($_POST['maca_table_order_delivery_mode']) ? sanitize_text_field(wp_unslash($_POST['maca_table_order_delivery_mode'])) : 'guest_screen';
        $table_order_staff_pin = isset($_POST['maca_table_order_staff_pin']) ? wp_unslash($_POST['maca_table_order_staff_pin']) : '';
        $table_order_staff_pin = is_string($table_order_staff_pin) ? trim($table_order_staff_pin) : '';
        $waiter_order_slug = isset($_POST['maca_waiter_order_slug']) ? sanitize_title(wp_unslash($_POST['maca_waiter_order_slug'])) : 'meny-servitris';
        $kitchen_order_slug = isset($_POST['maca_kitchen_order_slug']) ? sanitize_title(wp_unslash($_POST['maca_kitchen_order_slug'])) : 'meny-kok';
        $management_overview_slug = isset($_POST['maca_management_overview_slug']) ? sanitize_title(wp_unslash($_POST['maca_management_overview_slug'])) : 'chef-oversikt';
        $management_overview_pin = isset($_POST['maca_management_overview_pin']) ? sanitize_text_field(wp_unslash($_POST['maca_management_overview_pin'])) : '';
        $menu_footer_enabled = isset($_POST['maca_menu_footer_enabled']) ? '1' : '0';
        $menu_footer_restaurant_name = isset($_POST['maca_menu_footer_restaurant_name']) ? sanitize_text_field(wp_unslash($_POST['maca_menu_footer_restaurant_name'])) : '';
        $menu_footer_address = isset($_POST['maca_menu_footer_address']) ? sanitize_textarea_field(wp_unslash($_POST['maca_menu_footer_address'])) : '';
        $menu_footer_phone = isset($_POST['maca_menu_footer_phone']) ? sanitize_text_field(wp_unslash($_POST['maca_menu_footer_phone'])) : '';
        $menu_footer_email = isset($_POST['maca_menu_footer_email']) ? sanitize_email(wp_unslash($_POST['maca_menu_footer_email'])) : '';
        $menu_footer_website = isset($_POST['maca_menu_footer_website']) ? esc_url_raw(wp_unslash($_POST['maca_menu_footer_website'])) : '';
        $menu_footer_vat_number = isset($_POST['maca_menu_footer_vat_number']) ? sanitize_text_field(wp_unslash($_POST['maca_menu_footer_vat_number'])) : '';
        $vat_rate_dine_in = isset($_POST['maca_vat_rate_dine_in']) ? maca_menulist_sanitize_vat_rate(wp_unslash($_POST['maca_vat_rate_dine_in'])) : '';
        $vat_rate_takeaway = isset($_POST['maca_vat_rate_takeaway']) ? maca_menulist_sanitize_vat_rate(wp_unslash($_POST['maca_vat_rate_takeaway'])) : '';
        $vat_rate_alcohol = isset($_POST['maca_vat_rate_alcohol']) ? maca_menulist_sanitize_vat_rate(wp_unslash($_POST['maca_vat_rate_alcohol'])) : '';
        $vat_rate_dine_in_upcoming = isset($_POST['maca_vat_rate_dine_in_upcoming']) ? maca_menulist_sanitize_vat_rate(wp_unslash($_POST['maca_vat_rate_dine_in_upcoming'])) : '';
        $vat_rate_takeaway_upcoming = isset($_POST['maca_vat_rate_takeaway_upcoming']) ? maca_menulist_sanitize_vat_rate(wp_unslash($_POST['maca_vat_rate_takeaway_upcoming'])) : '';
        $vat_rate_alcohol_upcoming = isset($_POST['maca_vat_rate_alcohol_upcoming']) ? maca_menulist_sanitize_vat_rate(wp_unslash($_POST['maca_vat_rate_alcohol_upcoming'])) : '';
        $vat_rate_dine_in_upcoming_date = isset($_POST['maca_vat_rate_dine_in_upcoming_date']) ? maca_menulist_sanitize_vat_effective_date(wp_unslash($_POST['maca_vat_rate_dine_in_upcoming_date'])) : '';
        $vat_rate_takeaway_upcoming_date = isset($_POST['maca_vat_rate_takeaway_upcoming_date']) ? maca_menulist_sanitize_vat_effective_date(wp_unslash($_POST['maca_vat_rate_takeaway_upcoming_date'])) : '';
        $vat_rate_alcohol_upcoming_date = isset($_POST['maca_vat_rate_alcohol_upcoming_date']) ? maca_menulist_sanitize_vat_effective_date(wp_unslash($_POST['maca_vat_rate_alcohol_upcoming_date'])) : '';
        $offering_mode = isset($_POST['maca_offering_mode']) ? sanitize_key(wp_unslash($_POST['maca_offering_mode'])) : 'dine_in_only';
        $takeaway_slug = isset($_POST['maca_takeaway_slug']) ? sanitize_title(wp_unslash($_POST['maca_takeaway_slug'])) : 'hamtmat';
        $takeaway_page_title = isset($_POST['maca_takeaway_page_title']) ? sanitize_text_field(wp_unslash($_POST['maca_takeaway_page_title'])) : '';
        $service_mode = isset($_POST['maca_service_mode']) ? sanitize_key(wp_unslash($_POST['maca_service_mode'])) : 'dine_in';
        $menu_footer_allergy_text = isset($_POST['maca_menu_footer_allergy_text']) ? sanitize_textarea_field(wp_unslash($_POST['maca_menu_footer_allergy_text'])) : '';
        $menu_footer_allergy_text_en = isset($_POST['maca_menu_footer_allergy_text_en']) ? sanitize_textarea_field(wp_unslash($_POST['maca_menu_footer_allergy_text_en'])) : '';
        $menu_footer_price_text = isset($_POST['maca_menu_footer_price_text']) ? sanitize_textarea_field(wp_unslash($_POST['maca_menu_footer_price_text'])) : '';
        $menu_footer_price_text_en = isset($_POST['maca_menu_footer_price_text_en']) ? sanitize_textarea_field(wp_unslash($_POST['maca_menu_footer_price_text_en'])) : '';
        $menu_footer_serves_alcohol = isset($_POST['maca_menu_footer_serves_alcohol']) ? '1' : '0';
        $menu_footer_age_text = isset($_POST['maca_menu_footer_age_text']) ? sanitize_textarea_field(wp_unslash($_POST['maca_menu_footer_age_text'])) : '';
        $menu_footer_age_text_en = isset($_POST['maca_menu_footer_age_text_en']) ? sanitize_textarea_field(wp_unslash($_POST['maca_menu_footer_age_text_en'])) : '';
        $menu_print_title = isset($_POST['maca_menu_print_title']) ? sanitize_text_field(wp_unslash($_POST['maca_menu_print_title'])) : '';
        $menu_print_title_en = isset($_POST['maca_menu_print_title_en']) ? sanitize_text_field(wp_unslash($_POST['maca_menu_print_title_en'])) : '';
        $website_menu_page_title = isset($_POST['maca_website_menu_page_title']) ? sanitize_text_field(wp_unslash($_POST['maca_website_menu_page_title'])) : '';
        $website_menu_page_title_en = isset($_POST['maca_website_menu_page_title_en']) ? sanitize_text_field(wp_unslash($_POST['maca_website_menu_page_title_en'])) : '';
        $qr_menu_page_title = isset($_POST['maca_qr_menu_page_title']) ? sanitize_text_field(wp_unslash($_POST['maca_qr_menu_page_title'])) : '';
        $qr_menu_page_title_en = isset($_POST['maca_qr_menu_page_title_en']) ? sanitize_text_field(wp_unslash($_POST['maca_qr_menu_page_title_en'])) : '';
        $menu_print_theme = isset($_POST['maca_menu_print_theme']) ? sanitize_key(wp_unslash($_POST['maca_menu_print_theme'])) : 'classic';
        $menu_print_layout = isset($_POST['maca_menu_print_layout']) ? sanitize_key(wp_unslash($_POST['maca_menu_print_layout'])) : 'compact';
        $menu_print_logo = isset($_POST['maca_menu_print_logo']) ? esc_url_raw(wp_unslash($_POST['maca_menu_print_logo'])) : '';
        $menu_print_paper_size = isset($_POST['maca_menu_print_paper_size']) ? sanitize_key(wp_unslash($_POST['maca_menu_print_paper_size'])) : '';
        // phpcs:enable WordPress.Security.NonceVerification.Missing

        if (!in_array($table_order_delivery_mode, maca_menulist_get_table_order_delivery_modes(), true)) {
            $table_order_delivery_mode = 'guest_screen';
        }

        if ($waiter_order_slug === '') {
            $waiter_order_slug = 'meny-servitris';
        }

        if ($kitchen_order_slug === '') {
            $kitchen_order_slug = 'meny-kok';
        }

        if ($management_overview_slug === '') {
            $management_overview_slug = 'chef-oversikt';
        }

        $previous_delivery_mode = get_option('maca_menulist_table_order_delivery_mode', 'guest_screen');
        $previous_waiter_slug = get_option('maca_menulist_waiter_order_slug', 'meny-servitris');
        $previous_kitchen_slug = get_option('maca_menulist_kitchen_order_slug', 'meny-kok');
        $previous_management_overview_slug = maca_menulist_get_management_overview_slug();

        if (!in_array($content_mode, maca_menulist_get_content_modes(), true)) {
            $content_mode = 'files';
        }

        if ($price_currency === '') {
            $price_currency = 'kr';
        }

        $print_themes = maca_menulist_get_menu_print_themes();
        if (!isset($print_themes[$menu_print_theme])) {
            $menu_print_theme = 'classic';
        }

        if (!in_array($menu_print_paper_size, array('', 'a4', 'a5'), true)) {
            $menu_print_paper_size = '';
        }
        if (!in_array($menu_print_layout, array('compact', 'standard'), true)) {
            $menu_print_layout = 'compact';
        }

        $dish_menu_themes = maca_menulist_get_dish_menu_themes();
        if (!isset($dish_menu_themes[ $dish_menu_theme ])) {
            $dish_menu_theme = 'light';
        }

        $dish_menu_layouts = maca_menulist_get_dish_menu_layouts();
        if (!isset($dish_menu_layouts[ $dish_menu_layout ])) {
            $dish_menu_layout = 'rows';
        }

        if (function_exists('maca_menulist_sanitize_offering_mode')) {
            $offering_mode = maca_menulist_sanitize_offering_mode($offering_mode);
        } elseif (!in_array($offering_mode, array('dine_in_only', 'takeaway_only', 'both'), true)) {
            $offering_mode = 'dine_in_only';
        }

        if (
            function_exists('maca_menulist_pro_has_feature')
            && !maca_menulist_pro_has_feature('takeaway')
            && in_array($offering_mode, array('takeaway_only', 'both'), true)
        ) {
            $offering_mode = 'dine_in_only';
            add_settings_error(
                'maca_settings',
                'pro_locked_takeaway',
                __('Takeaway requires an active Pro subscription.', 'maca-restu-pro'),
                'error'
            );
        }

        if ($takeaway_slug === '') {
            $takeaway_slug = 'hamtmat';
        }

        if (!in_array($service_mode, maca_menulist_get_service_modes(), true)) {
            $service_mode = 'dine_in';
        }

        if (function_exists('maca_menulist_sync_service_mode_from_offering')) {
            maca_menulist_sync_service_mode_from_offering($offering_mode);
        }

        foreach (array(
            array('rate' => &$vat_rate_dine_in_upcoming, 'date' => &$vat_rate_dine_in_upcoming_date),
            array('rate' => &$vat_rate_takeaway_upcoming, 'date' => &$vat_rate_takeaway_upcoming_date),
            array('rate' => &$vat_rate_alcohol_upcoming, 'date' => &$vat_rate_alcohol_upcoming_date),
        ) as $scheduled) {
            if ($scheduled['rate'] === '' || $scheduled['date'] === '') {
                $scheduled['rate'] = '';
                $scheduled['date'] = '';
            }
        }
        unset($scheduled);

        if ($content_mode === 'dishes' && !maca_menulist_pro_has_feature('dishes')) {
            $content_mode = 'files';
            add_settings_error(
                'maca_settings',
                'pro_locked',
                __('Online menu requires an active Pro subscription.', 'maca-restu-pro'),
                'error'
            );
        }
        if ($content_mode !== 'dishes') {
            $public_keep_files_during_migration = '0';
        }

        // Order-tab fields may be absent when another settings tab is active or PDF mode hides the section.
        if (!isset($_POST['maca_table_order'])) {
            $table_order = get_option('maca_menulist_table_order', '0');
        }
        if (!isset($_POST['maca_table_order_delivery_mode'])) {
            $table_order_delivery_mode = get_option('maca_menulist_table_order_delivery_mode', 'guest_screen');
        }
        if (!isset($_POST['maca_waiter_order_slug'])) {
            $waiter_order_slug = get_option('maca_menulist_waiter_order_slug', 'meny-servitris');
        }
        if (!isset($_POST['maca_kitchen_order_slug'])) {
            $kitchen_order_slug = get_option('maca_menulist_kitchen_order_slug', 'meny-kok');
        }
        if (!in_array($table_order_delivery_mode, maca_menulist_get_table_order_delivery_modes(), true)) {
            $table_order_delivery_mode = 'guest_screen';
        }

        $previous_content_mode = get_option('maca_menulist_content_mode', 'files');
        $content_mode_changed = ($content_mode !== $previous_content_mode);

        update_option('maca_menulist_content_mode', $content_mode);
        update_option('maca_menulist_price_currency', $price_currency);
        update_option('maca_menulist_display_mode', $display_mode);
        update_option('maca_menulist_button_layout', $button_layout);
        update_option('maca_menulist_pdf_display_mode', $pdf_display_mode);
        update_option('maca_menulist_show_menu_title', $show_menu_title);
        update_option('maca_menulist_public_keep_files_during_migration', $public_keep_files_during_migration);
        if (maca_menulist_bilingual_menus_available()) {
            update_option('maca_menulist_dual_language_menu', $dual_language_menu);
            update_option('maca_menulist_menu_language_switcher', $menu_language_switcher);
        }
        if (maca_menulist_guest_ui_strings_available()) {
            maca_menulist_save_guest_string_overrides_from_post();
        }
        update_option('maca_menulist_show_schedule_notes', $show_schedule_notes);
        update_option('maca_menulist_dish_category_filter', $dish_category_filter);
        update_option('maca_menulist_dish_category_nav', $dish_category_nav);
        update_option('maca_menulist_dish_clickable_images', $dish_clickable_images);
        update_option('maca_menulist_dish_menu_theme', $dish_menu_theme);
        update_option('maca_menulist_dish_menu_layout', $dish_menu_layout);
        update_option('maca_menulist_campaign_exclusive_mode', $campaign_exclusive_mode);
        update_option('maca_menulist_dish_guest_ratings', $dish_guest_ratings);
        update_option('maca_menulist_table_order', $table_order);
        update_option('maca_menulist_table_order_line_notes', $table_order_line_notes);
        update_option('maca_menulist_table_order_order_note', $table_order_order_note);
        update_option('maca_menulist_table_order_show_prices', $table_order_show_prices);
        update_option('maca_menulist_table_order_guest_status', $table_order_guest_status);
        update_option('maca_menulist_table_order_delivery_mode', $table_order_delivery_mode);
        if (maca_menulist_admin_secret_should_update($table_order_staff_pin)) {
            update_option('maca_menulist_table_order_staff_pin', maca_menulist_hash_table_order_staff_pin($table_order_staff_pin), false);
            if (function_exists('maca_menulist_bump_table_order_staff_pin_revision')) {
                maca_menulist_bump_table_order_staff_pin_revision();
            }
            if (function_exists('maca_menulist_clear_all_staff_pin_lockouts')) {
                maca_menulist_clear_all_staff_pin_lockouts();
            } elseif (function_exists('maca_menulist_clear_staff_pin_failed_attempts')) {
                maca_menulist_clear_staff_pin_failed_attempts();
            }
            wp_cache_delete('maca_menulist_table_order_staff_pin', 'options');
            add_settings_error(
                'maca_settings',
                'maca_staff_pin_updated',
                __('Staff PIN was updated.', 'maca-restu-pro'),
                'updated'
            );
        }

        $public_overview_pro_active = function_exists('maca_menulist_pro_has_feature')
            && maca_menulist_pro_has_feature('public_overview');

        if ($public_overview_pro_active && maca_menulist_admin_secret_should_update($management_overview_pin)) {
            $management_overview_pin = trim((string) $management_overview_pin);
            update_option('maca_menulist_management_overview_pin', maca_menulist_hash_management_overview_pin($management_overview_pin), false);
            if (function_exists('maca_menulist_clear_management_pin_failed_attempts')) {
                maca_menulist_clear_management_pin_failed_attempts();
            }
        }

        if ($public_overview_pro_active) {
            update_option('maca_menulist_management_overview_slug', $management_overview_slug);
        }

        if (isset($_POST['hours']) && is_array($_POST['hours'])) {
            maca_menulist_save_booking_hours(wp_unslash($_POST['hours']));
        }

        update_option('maca_menulist_waiter_order_slug', $waiter_order_slug);
        update_option('maca_menulist_kitchen_order_slug', $kitchen_order_slug);
        update_option('maca_menulist_menu_footer_enabled', $menu_footer_enabled);
        update_option('maca_menulist_menu_footer_restaurant_name', $menu_footer_restaurant_name);
        update_option('maca_menulist_menu_footer_address', $menu_footer_address);
        update_option('maca_menulist_menu_footer_phone', $menu_footer_phone);
        update_option('maca_menulist_menu_footer_email', $menu_footer_email);
        update_option('maca_menulist_menu_footer_website', $menu_footer_website);
        update_option('maca_menulist_menu_footer_vat_number', $menu_footer_vat_number);
        update_option('maca_menulist_vat_rate_dine_in', $vat_rate_dine_in);
        update_option('maca_menulist_vat_rate_takeaway', $vat_rate_takeaway);
        update_option('maca_menulist_vat_rate_alcohol', $vat_rate_alcohol);
        update_option('maca_menulist_vat_rate_dine_in_upcoming', $vat_rate_dine_in_upcoming);
        update_option('maca_menulist_vat_rate_takeaway_upcoming', $vat_rate_takeaway_upcoming);
        update_option('maca_menulist_vat_rate_alcohol_upcoming', $vat_rate_alcohol_upcoming);
        update_option('maca_menulist_vat_rate_dine_in_upcoming_date', $vat_rate_dine_in_upcoming_date);
        update_option('maca_menulist_vat_rate_takeaway_upcoming_date', $vat_rate_takeaway_upcoming_date);
        update_option('maca_menulist_vat_rate_alcohol_upcoming_date', $vat_rate_alcohol_upcoming_date);
        $previous_takeaway_slug = function_exists('maca_menulist_get_takeaway_slug') ? maca_menulist_get_takeaway_slug() : '';
        update_option('maca_menulist_offering_mode', $offering_mode);
        $takeaway_pro_active = function_exists('maca_menulist_pro_has_feature')
            && maca_menulist_pro_has_feature('takeaway');
        if ($takeaway_pro_active) {
            update_option('maca_menulist_takeaway_slug', $takeaway_slug);
            update_option('maca_menulist_takeaway_page_title', $takeaway_page_title);
            if ($takeaway_slug !== $previous_takeaway_slug && function_exists('maca_menulist_schedule_rewrite_flush')) {
                maca_menulist_schedule_rewrite_flush();
            }
        }
        update_option('maca_menulist_service_mode', $service_mode);
        update_option('maca_menulist_menu_footer_allergy_text', $menu_footer_allergy_text);
        update_option('maca_menulist_menu_footer_allergy_text_en', $menu_footer_allergy_text_en);
        update_option('maca_menulist_menu_footer_price_text', $menu_footer_price_text);
        update_option('maca_menulist_menu_footer_price_text_en', $menu_footer_price_text_en);
        update_option('maca_menulist_menu_footer_serves_alcohol', $menu_footer_serves_alcohol);
        update_option('maca_menulist_menu_footer_age_text', $menu_footer_age_text);
        update_option('maca_menulist_menu_footer_age_text_en', $menu_footer_age_text_en);
        update_option('maca_menulist_menu_print_title', $menu_print_title);
        update_option('maca_menulist_menu_print_title_en', $menu_print_title_en);
        update_option('maca_menulist_website_menu_page_title', $website_menu_page_title);
        update_option('maca_menulist_website_menu_page_title_en', $website_menu_page_title_en);
        update_option('maca_menulist_qr_menu_page_title', $qr_menu_page_title);
        update_option('maca_menulist_qr_menu_page_title_en', $qr_menu_page_title_en);
        update_option('maca_menulist_menu_print_theme', $menu_print_theme);
        update_option('maca_menulist_menu_print_layout', $menu_print_layout);
        update_option('maca_menulist_menu_print_logo', $menu_print_logo);
        update_option('maca_menulist_menu_print_paper_size', $menu_print_paper_size);

        if (function_exists('maca_menulist_onboarding_set_enabled')) {
            $onboarding_enabled = isset($_POST['maca_onboarding_enabled']);
            $was_onboarding_enabled = maca_menulist_onboarding_is_enabled();
            maca_menulist_onboarding_set_enabled($onboarding_enabled);

            if ($onboarding_enabled && !$was_onboarding_enabled && function_exists('maca_menulist_onboarding_get_state')) {
                $onboarding_state = maca_menulist_onboarding_get_state();
                if (isset($onboarding_state['status']) && (string) $onboarding_state['status'] === 'dismissed') {
                    $onboarding_state['status'] = 'active';
                    $onboarding_state['updated_at'] = maca_menulist_wp_now_mysql();
                    maca_menulist_onboarding_save_state($onboarding_state);
                }
            }
        }

        if ($content_mode_changed) {
            maca_menulist_flush_rewrite_rules();
        }

        if (
            $table_order_delivery_mode !== $previous_delivery_mode
            || $waiter_order_slug !== $previous_waiter_slug
            || $kitchen_order_slug !== $previous_kitchen_slug
            || $management_overview_slug !== $previous_management_overview_slug
        ) {
            maca_menulist_flush_rewrite_rules();
        }
        
        add_settings_error('maca_settings', 'success', __('Settings saved successfully.', 'maca-restu-pro'), 'updated');

        if ($content_mode_changed && $content_mode === 'files') {
            add_settings_error(
                'maca_settings',
                'maca_content_mode_files_notice',
                sprintf(
                    /* translators: 1: waiter slug, 2: kitchen slug */
                    __('You switched to PDF/image menus. Waiter/kitchen pages are paused until you switch back to online menu mode. Your delivery settings are kept. Slugs: %1$s, %2$s.', 'maca-restu-pro'),
                    esc_html($waiter_order_slug),
                    esc_html($kitchen_order_slug)
                ),
                'warning'
            );
        }

        if ($content_mode_changed && $content_mode === 'dishes') {
            add_settings_error(
                'maca_settings',
                'maca_content_mode_dishes_notice',
                __('You switched to online menu mode. Check the Order tab (delivery mode and staff PIN), then open your waiter/kitchen URLs again.', 'maca-restu-pro'),
                'info'
            );
        }
    }
    
    /**
     * Save QR code settings
     */
    private function save_qr_settings() {
        // phpcs:disable WordPress.Security.NonceVerification.Missing
        $qr_category = isset($_POST['qr_category']) ? intval(wp_unslash($_POST['qr_category'])) : '';
        $qr_title = isset($_POST['qr_title']) ? sanitize_text_field(wp_unslash($_POST['qr_title'])) : '';
        $qr_subtitle = isset($_POST['qr_subtitle']) ? sanitize_text_field(wp_unslash($_POST['qr_subtitle'])) : '';
        $qr_logo = isset($_POST['qr_logo']) ? esc_url_raw(wp_unslash($_POST['qr_logo'])) : '';
        $qr_menu_show_logo = isset($_POST['qr_menu_show_logo']) ? '1' : '0';
        $qr_print_show_logo = isset($_POST['qr_print_show_logo']) ? '1' : '0';
        $qr_display_mode = isset($_POST['qr_display_mode']) ? sanitize_text_field(wp_unslash($_POST['qr_display_mode'])) : 'full_page';
        $qr_paper_size = isset($_POST['qr_paper_size']) ? sanitize_text_field(wp_unslash($_POST['qr_paper_size'])) : 'a4';
        $qr_slug = isset($_POST['qr_slug']) ? sanitize_title(wp_unslash($_POST['qr_slug'])) : 'qrmeny';
        // phpcs:enable WordPress.Security.NonceVerification.Missing
        if ($qr_slug === '') {
            $qr_slug = 'qrmeny';
        }

        $old_slug = get_option('maca_menulist_qr_slug', 'qrmeny');
        update_option('maca_menulist_qr_slug', $qr_slug);
        if ($old_slug !== $qr_slug) {
            maca_menulist_flush_rewrite_rules();
        }

        update_option('maca_menulist_qr_category', $qr_category);
        update_option('maca_menulist_qr_title', $qr_title);
        update_option('maca_menulist_qr_subtitle', $qr_subtitle);
        update_option('maca_menulist_qr_logo', $qr_logo);
        update_option('maca_menulist_qr_menu_show_logo', $qr_menu_show_logo);
        update_option('maca_menulist_qr_print_show_logo', $qr_print_show_logo);
        update_option('maca_menulist_qr_display_mode', $qr_display_mode);
        update_option('maca_menulist_qr_paper_size', $qr_paper_size);

        add_settings_error('maca_qr', 'success', __('QR code settings saved successfully.', 'maca-restu-pro'), 'updated');
    }
    
    /**
     * Render settings page
     */
    public function render_settings_page() {
        $content_mode = maca_menulist_get_content_mode();
        $dishes_pro_active = maca_menulist_pro_has_feature('dishes');
        $takeaway_pro_active = maca_menulist_pro_has_feature('takeaway');
        $public_overview_pro_active = maca_menulist_pro_has_feature('public_overview');
        $dishes_mode_effective = maca_menulist_is_dishes_mode();
        $price_currency = maca_menulist_get_price_currency();
        $display_mode = get_option('maca_menulist_display_mode', 'inline');
        $button_layout = get_option('maca_menulist_button_layout', 'horizontal');
        $pdf_display_mode = get_option('maca_menulist_pdf_display_mode', 'full_page');
        $show_menu_title = get_option('maca_menulist_show_menu_title', '1') === '1';
        $website_menu_page_title = get_option('maca_menulist_website_menu_page_title', '');
        $website_menu_page_title_en = get_option('maca_menulist_website_menu_page_title_en', '');
        $qr_menu_page_title = get_option('maca_menulist_qr_menu_page_title', '');
        $qr_menu_page_title_en = get_option('maca_menulist_qr_menu_page_title_en', '');
        $menu_page_title_placeholder = function_exists('maca_menulist_get_menu_page_title_fallback')
            ? maca_menulist_get_menu_page_title_fallback()
            : __('Our menu', 'maca-restu-pro');
        $public_keep_files_during_migration = get_option('maca_menulist_public_keep_files_during_migration', '0') === '1';
        $dual_language_menu = get_option('maca_menulist_dual_language_menu', '0') === '1';
        $menu_language_switcher = get_option('maca_menulist_menu_language_switcher', '1') === '1';
        $site_language_label = maca_menulist_get_local_language_label();
        $show_schedule_notes = get_option('maca_menulist_show_schedule_notes', '1') === '1';
        $dish_category_filter = get_option('maca_menulist_dish_category_filter', '1') === '1';
        $dish_category_nav = maca_menulist_get_dish_category_nav_mode();
        $dish_clickable_images = get_option('maca_menulist_dish_clickable_images', '0') === '1';
        $dish_menu_theme = maca_menulist_get_dish_menu_theme();
        $dish_menu_themes = maca_menulist_get_dish_menu_themes();
        $dish_menu_layout = maca_menulist_get_dish_menu_layout();
        $dish_menu_layouts = maca_menulist_get_dish_menu_layouts();
        $campaign_exclusive_mode = get_option('maca_menulist_campaign_exclusive_mode', '1') === '1';
        $dish_guest_ratings = get_option('maca_menulist_dish_guest_ratings', '0') === '1';
        $table_order = get_option('maca_menulist_table_order', '0') === '1';
        $table_order_line_notes = get_option('maca_menulist_table_order_line_notes', '1') === '1';
        $table_order_order_note = get_option('maca_menulist_table_order_order_note', '1') === '1';
        $table_order_show_prices = get_option('maca_menulist_table_order_show_prices', '1') === '1';
        $table_order_guest_status = get_option('maca_menulist_table_order_guest_status', '') === '1';
        $table_order_delivery_mode = maca_menulist_get_table_order_delivery_mode();
        $table_order_staff_pin = '';
        $table_order_staff_pin_set = maca_menulist_get_table_order_staff_pin() !== '';
        $table_order_staff_pin_needs_resave = $table_order_staff_pin_set
            && function_exists('maca_menulist_table_order_staff_pin_is_hmac')
            && !maca_menulist_table_order_staff_pin_is_hmac(maca_menulist_get_table_order_staff_pin());
        $waiter_order_slug = maca_menulist_get_waiter_order_slug();
        $kitchen_order_slug = maca_menulist_get_kitchen_order_slug();
        $management_overview_slug = maca_menulist_get_management_overview_slug();
        $management_overview_pin_set = maca_menulist_get_management_overview_pin() !== '';
        $menu_footer_enabled = get_option('maca_menulist_menu_footer_enabled', '1') === '1';
        $menu_footer_restaurant_name = get_option('maca_menulist_menu_footer_restaurant_name', '');
        $menu_footer_address = get_option('maca_menulist_menu_footer_address', '');
        $menu_footer_phone = get_option('maca_menulist_menu_footer_phone', '');
        $menu_footer_email = get_option('maca_menulist_menu_footer_email', '');
        $menu_footer_website = get_option('maca_menulist_menu_footer_website', '');
        $menu_footer_vat_number = maca_menulist_get_vat_number();
        $vat_rate_dine_in = maca_menulist_get_stored_vat_rate('dine_in');
        $vat_rate_takeaway = maca_menulist_get_stored_vat_rate('takeaway');
        $vat_rate_alcohol = maca_menulist_get_stored_vat_rate('alcohol');
        $vat_rate_dine_in_upcoming = maca_menulist_get_stored_vat_rate_upcoming('dine_in');
        $vat_rate_takeaway_upcoming = maca_menulist_get_stored_vat_rate_upcoming('takeaway');
        $vat_rate_alcohol_upcoming = maca_menulist_get_stored_vat_rate_upcoming('alcohol');
        $vat_rate_dine_in_upcoming_date = maca_menulist_get_stored_vat_rate_upcoming_date('dine_in');
        $vat_rate_takeaway_upcoming_date = maca_menulist_get_stored_vat_rate_upcoming_date('takeaway');
        $vat_rate_alcohol_upcoming_date = maca_menulist_get_stored_vat_rate_upcoming_date('alcohol');
        $service_mode = maca_menulist_get_service_mode();
        $offering_mode = function_exists('maca_menulist_get_offering_mode') ? maca_menulist_get_offering_mode() : 'dine_in_only';
        $takeaway_slug = function_exists('maca_menulist_get_takeaway_slug') ? maca_menulist_get_takeaway_slug() : 'hamtmat';
        $takeaway_url = function_exists('maca_menulist_get_takeaway_url') ? maca_menulist_get_takeaway_url() : '';
        $takeaway_page_title = get_option('maca_menulist_takeaway_page_title', '');
        $menu_footer_allergy_text = get_option('maca_menulist_menu_footer_allergy_text', '');
        $menu_footer_allergy_text_en = get_option('maca_menulist_menu_footer_allergy_text_en', '');
        $menu_footer_price_text = get_option('maca_menulist_menu_footer_price_text', '');
        $menu_footer_price_text_en = get_option('maca_menulist_menu_footer_price_text_en', '');
        $menu_footer_serves_alcohol = get_option('maca_menulist_menu_footer_serves_alcohol', '0') === '1';
        $menu_footer_age_text = get_option('maca_menulist_menu_footer_age_text', '');
        $menu_footer_age_text_en = get_option('maca_menulist_menu_footer_age_text_en', '');
        $menu_print_title = get_option('maca_menulist_menu_print_title', '');
        $menu_print_title_en = get_option('maca_menulist_menu_print_title_en', '');
        $menu_print_theme = maca_menulist_get_menu_print_theme();
        $menu_print_layout = get_option('maca_menulist_menu_print_layout', 'compact');
        $menu_print_logo = get_option('maca_menulist_menu_print_logo', '');
        $menu_print_paper_size = get_option('maca_menulist_menu_print_paper_size', '');
        $menu_print_themes = maca_menulist_get_menu_print_themes();
        $onboarding_enabled = function_exists('maca_menulist_onboarding_is_enabled') && maca_menulist_onboarding_is_enabled();
        $settings_tab      = maca_menulist_get_active_settings_tab($content_mode);

        ?>
        <div class="wrap maca-settings-wrap">
            <h1><?php esc_html_e('Settings', 'maca-restu-pro'); ?></h1>
            
            <?php settings_errors('maca_settings'); ?>
            <?php settings_errors('maca_bookings'); ?>

            <?php
            if ($content_mode !== 'dishes' && maca_menulist_table_order_uses_server()) {
                ?>
                <div class="notice notice-warning">
                    <p>
                        <?php
                        echo wp_kses_post(
                            sprintf(
                                /* translators: 1: waiter URL path, 2: kitchen URL path */
                                __('You are using <strong>PDF/image menus</strong>. Waiter and kitchen pages (%1$s, %2$s) only work in <strong>online menu mode</strong> with table ordering enabled. Switch content type to dishes and save, or use migration mode to show PDFs while building the online menu.', 'maca-restu-pro'),
                                '<code>/' . esc_html($waiter_order_slug) . '/</code>',
                                '<code>/' . esc_html($kitchen_order_slug) . '/</code>'
                            )
                        );
                        ?>
                    </p>
                </div>
                <?php
            }

            if ($content_mode === 'dishes' && !$dishes_pro_active) {
                echo wp_kses_post(maca_menulist_pro_locked_notice('dishes'));
            }

            maca_menulist_render_settings_tab_nav($settings_tab, $content_mode);
            ?>
            
            <form method="post" action="" class="maca-settings-form">
                <?php wp_nonce_field('maca_save', 'maca_nonce'); ?>
                <input type="hidden" name="maca_action" value="save">
                <input type="hidden" name="maca_type" value="settings">
                <input type="hidden" name="maca_settings_tab" id="maca_settings_tab" value="<?php echo esc_attr($settings_tab); ?>">
                
                <div class="maca-settings-sections"
                     data-active-tab="<?php echo esc_attr($settings_tab); ?>"
                     data-content-mode="<?php echo esc_attr($content_mode); ?>">

                <section class="maca-settings-section maca-settings-tab-panel" id="maca-settings-restaurant" data-settings-tab="restaurant">
                    <h2 class="maca-settings-section-title"><?php esc_html_e('Restaurant details', 'maca-restu-pro'); ?></h2>
                    <p class="maca-settings-section-desc description"><?php esc_html_e('Name and contact details used in the menu footer, printable menu, and table reservation emails.', 'maca-restu-pro'); ?></p>
                    <table class="form-table" role="presentation">
                    <tr>
                        <th scope="row">
                            <label for="maca_menu_footer_restaurant_name"><?php esc_html_e('Restaurant name', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <input type="text" id="maca_menu_footer_restaurant_name" name="maca_menu_footer_restaurant_name" value="<?php echo esc_attr($menu_footer_restaurant_name); ?>" class="regular-text">
                            <p class="description"><?php esc_html_e('Used in the menu footer and as the sender name (From) on all guest emails from maca Restu — table reservations, waitlist, and payment confirmations.', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="maca_menu_footer_address"><?php esc_html_e('Address', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <textarea id="maca_menu_footer_address" name="maca_menu_footer_address" rows="3" class="large-text"><?php echo esc_textarea($menu_footer_address); ?></textarea>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="maca_menu_footer_phone"><?php esc_html_e('Phone', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <input type="text" id="maca_menu_footer_phone" name="maca_menu_footer_phone" value="<?php echo esc_attr($menu_footer_phone); ?>" class="regular-text">
                            <p class="description"><?php esc_html_e('Shown with a phone icon in the menu footer (website, QR, and print).', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="maca_menu_footer_email"><?php esc_html_e('Email', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <input type="email" id="maca_menu_footer_email" name="maca_menu_footer_email" value="<?php echo esc_attr($menu_footer_email); ?>" class="regular-text" placeholder="info@example.com">
                            <p class="description"><?php esc_html_e('Used for payment confirmations and shown with an email icon on menus. Table Reservation email is set under Table Reservations → Table settings.', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="maca_menu_footer_website"><?php esc_html_e('Website', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <input type="url" id="maca_menu_footer_website" name="maca_menu_footer_website" value="<?php echo esc_attr($menu_footer_website); ?>" class="regular-text" placeholder="<?php echo esc_attr(home_url('/')); ?>">
                            <p class="description"><?php esc_html_e('Shown with a globe icon. Leave empty to use the WordPress site URL.', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="maca_menu_footer_vat_number"><?php esc_html_e('VAT number', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <input type="text" id="maca_menu_footer_vat_number" name="maca_menu_footer_vat_number" value="<?php echo esc_attr($menu_footer_vat_number); ?>" class="regular-text" placeholder="SE123456789001">
                            <p class="description"><?php esc_html_e('Your VAT registration number (Momsregistreringsnummer). Shown in the menu footer and on printable menus.', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="maca_offering_mode"><?php esc_html_e('Guest offering', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <select id="maca_offering_mode" name="maca_offering_mode">
                                <option value="dine_in_only" <?php selected($offering_mode, 'dine_in_only'); ?>><?php esc_html_e('Dine-in only (tables / QR)', 'maca-restu-pro'); ?></option>
                                <option value="takeaway_only" <?php selected($offering_mode, 'takeaway_only'); ?> <?php disabled(!$takeaway_pro_active); ?>><?php esc_html_e('Takeaway only', 'maca-restu-pro'); ?></option>
                                <option value="both" disabled><?php esc_html_e('Both dine-in and takeaway (coming soon)', 'maca-restu-pro'); ?></option>
                            </select>
                            <p class="description"><?php esc_html_e('Takeaway only enables the takeaway menu URL and ordering without a table. Food VAT for new orders follows the active channel.', 'maca-restu-pro'); ?></p>
                            <?php if (!$takeaway_pro_active) : ?>
                                <?php echo wp_kses_post(maca_menulist_pro_locked_notice('takeaway')); ?>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <tr class="maca-settings-takeaway-row" <?php echo (!$takeaway_pro_active || $offering_mode !== 'takeaway_only') ? 'style="display:none;"' : ''; ?>>
                        <th scope="row">
                            <label for="maca_takeaway_slug"><?php esc_html_e('Takeaway menu URL slug', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <input type="text" id="maca_takeaway_slug" name="maca_takeaway_slug" value="<?php echo esc_attr($takeaway_slug); ?>" class="regular-text">
                            <?php if ($takeaway_url !== '') : ?>
                                <p class="description">
                                    <?php esc_html_e('Public URL:', 'maca-restu-pro'); ?>
                                    <a href="<?php echo esc_url($takeaway_url); ?>" target="_blank" rel="noopener"><?php echo esc_html($takeaway_url); ?></a>
                                </p>
                            <?php endif; ?>
                            <p class="description"><?php esc_html_e('Permanent link for your website menu — e.g. /hamtmat/. Also embed with shortcode [maca_takeaway_menu].', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    <tr class="maca-settings-takeaway-row" <?php echo (!$takeaway_pro_active || $offering_mode !== 'takeaway_only') ? 'style="display:none;"' : ''; ?>>
                        <th scope="row">
                            <label for="maca_takeaway_page_title"><?php esc_html_e('Takeaway page title', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <input type="text" id="maca_takeaway_page_title" name="maca_takeaway_page_title" value="<?php echo esc_attr($takeaway_page_title); ?>" class="regular-text" placeholder="<?php esc_attr_e('Order takeaway', 'maca-restu-pro'); ?>">
                        </td>
                    </tr>
                    <input type="hidden" name="maca_service_mode" value="<?php echo esc_attr($service_mode); ?>">
                    <tr>
                        <th scope="row"><?php esc_html_e('VAT rates', 'maca-restu-pro'); ?></th>
                        <td>
                            <fieldset>
                                <legend class="screen-reader-text"><?php esc_html_e('VAT rates', 'maca-restu-pro'); ?></legend>
                                <?php
                                $vat_rate_rows = array(
                                    'dine_in' => array(
                                        'label' => __('Dine-in (eat on premises)', 'maca-restu-pro'),
                                        'current' => $vat_rate_dine_in,
                                        'upcoming' => $vat_rate_dine_in_upcoming,
                                        'date' => $vat_rate_dine_in_upcoming_date,
                                        'placeholder' => '12',
                                    ),
                                    'takeaway' => array(
                                        'label' => __('Takeaway', 'maca-restu-pro'),
                                        'current' => $vat_rate_takeaway,
                                        'upcoming' => $vat_rate_takeaway_upcoming,
                                        'date' => $vat_rate_takeaway_upcoming_date,
                                        'placeholder' => '6',
                                    ),
                                    'alcohol' => array(
                                        'label' => __('Alcohol', 'maca-restu-pro'),
                                        'current' => $vat_rate_alcohol,
                                        'upcoming' => $vat_rate_alcohol_upcoming,
                                        'date' => $vat_rate_alcohol_upcoming_date,
                                        'placeholder' => '25',
                                    ),
                                );
                                foreach ($vat_rate_rows as $vat_key => $vat_row) :
                                    ?>
                                <div class="maca-vat-rate-group" style="margin-bottom:1.25em;padding-bottom:1em;border-bottom:1px solid #dcdcde;">
                                    <p><strong><?php echo esc_html($vat_row['label']); ?></strong></p>
                                    <p>
                                        <label for="maca_vat_rate_<?php echo esc_attr($vat_key); ?>"><?php esc_html_e('Current rate', 'maca-restu-pro'); ?></label><br>
                                        <input type="number" id="maca_vat_rate_<?php echo esc_attr($vat_key); ?>" name="maca_vat_rate_<?php echo esc_attr($vat_key); ?>" value="<?php echo esc_attr($vat_row['current']); ?>" class="small-text" min="0" max="100" step="0.01" placeholder="<?php echo esc_attr($vat_row['placeholder']); ?>"> %
                                    </p>
                                    <p>
                                        <label for="maca_vat_rate_<?php echo esc_attr($vat_key); ?>_upcoming"><?php esc_html_e('Upcoming rate', 'maca-restu-pro'); ?></label><br>
                                        <input type="number" id="maca_vat_rate_<?php echo esc_attr($vat_key); ?>_upcoming" name="maca_vat_rate_<?php echo esc_attr($vat_key); ?>_upcoming" value="<?php echo esc_attr($vat_row['upcoming']); ?>" class="small-text" min="0" max="100" step="0.01"> %
                                    </p>
                                    <p>
                                        <label for="maca_vat_rate_<?php echo esc_attr($vat_key); ?>_upcoming_date"><?php esc_html_e('Upcoming rate from', 'maca-restu-pro'); ?></label><br>
                                        <input type="date" id="maca_vat_rate_<?php echo esc_attr($vat_key); ?>_upcoming_date" name="maca_vat_rate_<?php echo esc_attr($vat_key); ?>_upcoming_date" value="<?php echo esc_attr($vat_row['date']); ?>">
                                    </p>
                                </div>
                                    <?php
                                endforeach;
                                ?>
                                <p class="description"><?php esc_html_e('Current and scheduled VAT rates for food, non-alcoholic beverages, and alcohol. The upcoming rate applies from the chosen date (site timezone, start of day) in the menu footer, order emails, and VAT breakdown. Orders use the rate that applied when the guest paid. In Sweden (2026): dine-in 12%, takeaway 6%, alcohol 25%.', 'maca-restu-pro'); ?></p>
                            </fieldset>
                        </td>
                    </tr>
                    </table>

                    <h3 class="maca-settings-subsection-title"><?php esc_html_e('Public overview (read-only)', 'maca-restu-pro'); ?></h3>
                    <p class="description"><?php esc_html_e('Let managers view live statistics outside wp-admin. The page is read-only — no data or settings can be changed.', 'maca-restu-pro'); ?></p>
                    <?php if (!$public_overview_pro_active) : ?>
                        <?php echo wp_kses_post(maca_menulist_pro_locked_notice('public_overview')); ?>
                    <?php else : ?>
                    <table class="form-table" role="presentation">
                    <tr>
                        <th scope="row">
                            <label for="maca_management_overview_pin"><?php esc_html_e('Manager PIN', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <?php
                            $management_pin_attrs = maca_menulist_admin_secret_input_attrs(
                                $management_overview_pin_set,
                                array(
                                    'id' => 'maca_management_overview_pin',
                                    'name' => 'maca_management_overview_pin',
                                    'inputmode' => 'numeric',
                                    'autocomplete' => 'off',
                                )
                            );
                            ?>
                            <input <?php echo maca_menulist_admin_secret_field_attr_string($management_pin_attrs); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>>
                            <p class="description">
                                <?php
                                if ($management_overview_pin_set) {
                                    esc_html_e('Required for the public overview page. Separate from the staff PIN. Leave blank to keep the existing PIN.', 'maca-restu-pro');
                                } else {
                                    esc_html_e('Required for the public overview page. Separate from the staff PIN.', 'maca-restu-pro');
                                }
                                ?>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="maca_management_overview_slug"><?php esc_html_e('Overview page slug', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <input type="text" id="maca_management_overview_slug" name="maca_management_overview_slug" value="<?php echo esc_attr($management_overview_slug); ?>" class="regular-text">
                            <p class="description">
                                <a href="<?php echo esc_url(maca_menulist_get_management_overview_url()); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html(maca_menulist_get_management_overview_url()); ?></a>
                            </p>
                        </td>
                    </tr>
                    </table>
                    <?php endif; ?>
                    <?php if (function_exists('maca_menulist_onboarding_is_enabled')) : ?>
                    <table class="form-table" role="presentation">
                    <tr>
                        <th scope="row"><?php maca_menulist_ob_e('Kom igång-guide', 'Getting started wizard'); ?></th>
                        <td>
                            <label for="maca_onboarding_enabled">
                                <input type="checkbox" id="maca_onboarding_enabled" name="maca_onboarding_enabled" value="1" <?php checked($onboarding_enabled); ?>>
                                <?php maca_menulist_ob_e('Visa kom igång-guiden', 'Show getting started wizard'); ?>
                            </label>
                            <p class="description">
                                <?php maca_menulist_ob_e(
                                    'Steg-för-steg-guide under maca Restu → Kom igång. Stäng av om du vill konfigurera pluginet utan guiden.',
                                    'Step-by-step wizard under maca Restu → Getting started. Turn off if you prefer to configure the plugin without the wizard.'
                                ); ?>
                            </p>
                        </td>
                    </tr>
                    </table>
                    <?php endif; ?>
                </section>

                <section class="maca-settings-section maca-settings-tab-panel" id="maca-settings-menu" data-settings-tab="menu">
                    <h2 class="maca-settings-section-title"><?php esc_html_e('Menu & content', 'maca-restu-pro'); ?></h2>
                    <table class="form-table" role="presentation">
                    <tr>
                        <th scope="row">
                            <label for="maca_content_mode"><?php esc_html_e('Menu Content Type', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <select id="maca_content_mode" name="maca_content_mode">
                                <option value="files" <?php selected($content_mode, 'files'); ?>><?php esc_html_e('Upload PDF/image menus', 'maca-restu-pro'); ?></option>
                                <option value="dishes" <?php selected($content_mode, 'dishes'); ?> <?php disabled(!$dishes_pro_active); ?>><?php esc_html_e('Online menu in the plugin (Pro)', 'maca-restu-pro'); ?></option>
                            </select>
                            <p class="description"><?php esc_html_e('Choose whether to manage menus as uploaded files or as an online menu with individual dishes, categories, descriptions, and prices. Online menu is a Pro feature.', 'maca-restu-pro'); ?></p>
                            <?php if ($dishes_pro_active) : ?>
                                <p style="margin-top: 10px;">
                                    <input type="checkbox" id="maca_public_keep_files_during_migration" name="maca_public_keep_files_during_migration" value="1" <?php checked($public_keep_files_during_migration); ?>>
                                    <label for="maca_public_keep_files_during_migration"><?php esc_html_e('Migration mode: keep PDF/image menus live on website + QR while you build the online menu in admin', 'maca-restu-pro'); ?></label>
                                </p>
                                <p class="description"><?php esc_html_e('Use this when moving from file menus to online menus. Turn it off when you are ready to publish the online menu publicly.', 'maca-restu-pro'); ?></p>
                            <?php endif; ?>
                            <?php if (!$dishes_pro_active) : ?>
                                <?php echo wp_kses_post(maca_menulist_pro_locked_notice('dishes')); ?>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="maca_qr_menu_page_title"><?php echo esc_html(maca_menulist_admin_primary_field_label(__('QR menu page title', 'maca-restu-pro'))); ?></label>
                        </th>
                        <td>
                            <input type="text" id="maca_qr_menu_page_title" name="maca_qr_menu_page_title" value="<?php echo esc_attr($qr_menu_page_title); ?>" class="regular-text" placeholder="<?php echo esc_attr($menu_page_title_placeholder); ?>">
                            <p class="description"><?php esc_html_e('Heading at the top of the QR menu page (e.g. /qrmeny/). Replaces the default “Our menu” / “Vår meny”. Leave empty to use restaurant name or the default.', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    <?php if (maca_menulist_admin_show_local_content_fields()) : ?>
                    <tr>
                        <th scope="row">
                            <label for="maca_qr_menu_page_title_en"><?php echo esc_html(maca_menulist_bilingual_field_label(__('QR menu page title', 'maca-restu-pro'), true)); ?></label>
                        </th>
                        <td>
                            <input type="text" id="maca_qr_menu_page_title_en" name="maca_qr_menu_page_title_en" value="<?php echo esc_attr($qr_menu_page_title_en); ?>" class="regular-text" placeholder="<?php echo esc_attr($menu_page_title_placeholder); ?>">
                        </td>
                    </tr>
                    <?php endif; ?>
                    <tr>
                        <th scope="row">
                            <label for="maca_website_menu_page_title"><?php echo esc_html(maca_menulist_admin_primary_field_label(__('Website menu page title', 'maca-restu-pro'))); ?></label>
                        </th>
                        <td>
                            <input type="text" id="maca_website_menu_page_title" name="maca_website_menu_page_title" value="<?php echo esc_attr($website_menu_page_title); ?>" class="regular-text" placeholder="<?php echo esc_attr($menu_page_title_placeholder); ?>">
                            <p class="description"><?php esc_html_e('Heading above the menu on website pages with [maca_menu_list]. Leave empty to use the same title as the QR menu page.', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    <?php if (maca_menulist_admin_show_local_content_fields()) : ?>
                    <tr>
                        <th scope="row">
                            <label for="maca_website_menu_page_title_en"><?php echo esc_html(maca_menulist_bilingual_field_label(__('Website menu page title', 'maca-restu-pro'), true)); ?></label>
                        </th>
                        <td>
                            <input type="text" id="maca_website_menu_page_title_en" name="maca_website_menu_page_title_en" value="<?php echo esc_attr($website_menu_page_title_en); ?>" class="regular-text" placeholder="<?php echo esc_attr($menu_page_title_placeholder); ?>">
                        </td>
                    </tr>
                    <?php endif; ?>
                    <?php if (
                        maca_menulist_admin_show_local_content_fields()
                        && defined('MACA_MENULIST_PRO')
                        && MACA_MENULIST_PRO
                        && function_exists('maca_menulist_pro_has_feature')
                        && !maca_menulist_pro_has_feature('bilingual_menus')
                    ) : ?>
                    <tr>
                        <th scope="row"><?php esc_html_e('Menu languages', 'maca-restu-pro'); ?></th>
                        <td><?php echo wp_kses_post(maca_menulist_pro_locked_notice('bilingual_menus')); ?></td>
                    </tr>
                    <?php elseif (maca_menulist_admin_show_local_content_fields() && maca_menulist_bilingual_menus_available()) : ?>
                    <tr>
                        <th scope="row"><?php esc_html_e('Local menu language', 'maca-restu-pro'); ?></th>
                        <td>
                            <p><strong><?php echo esc_html($site_language_label); ?></strong></p>
                            <p class="description">
                                <?php
                                echo wp_kses_post(
                                    sprintf(
                                        /* translators: %s: link to Settings → General */
                                        __('Uses the WordPress site language from %s. Guests can switch between this language and English with flag buttons on the menu and QR page.', 'maca-restu-pro'),
                                        '<a href="' . esc_url(admin_url('options-general.php')) . '">' . esc_html__('Settings → General', 'maca-restu-pro') . '</a>'
                                    )
                                );
                                ?>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="maca_menu_language_switcher"><?php esc_html_e('Language switcher', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <input type="checkbox" id="maca_menu_language_switcher" name="maca_menu_language_switcher" value="1" <?php checked($menu_language_switcher && !$dual_language_menu); ?> <?php disabled($dual_language_menu); ?>>
                            <label for="maca_menu_language_switcher"><?php esc_html_e('Show flag buttons on the website menu and QR page (local language / English)', 'maca-restu-pro'); ?></label>
                            <p class="description"><?php esc_html_e('Guests pick one language at a time. Disabled when dual-language menus are enabled.', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="maca_dual_language_menu"><?php esc_html_e('Dual-language menus', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <input type="checkbox" id="maca_dual_language_menu" name="maca_dual_language_menu" value="1" <?php checked($dual_language_menu); ?>>
                            <label for="maca_dual_language_menu"><?php esc_html_e('Show both English and local language on public menus', 'maca-restu-pro'); ?></label>
                            <p class="description"><?php esc_html_e('When both texts are filled in, guests see e.g. “Beef tartare / Råbiff”. Useful for international guests. When off, guests can switch between local and English with the flag buttons on the menu and QR page.', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    <?php endif; ?>
                    </table>
                </section>

                <?php
                if (maca_menulist_guest_ui_strings_available()) {
                    maca_menulist_render_admin_guest_strings_panel();
                }
                ?>

                <section class="maca-settings-section maca-settings-tab-panel maca-setting-dishes-only" id="maca-settings-dish-menu" data-settings-tab="dishes" <?php echo !$dishes_mode_effective ? 'style="display:none;"' : ''; ?>>
                    <h2 class="maca-settings-section-title"><?php esc_html_e('Online menu (Pro)', 'maca-restu-pro'); ?></h2>
                    <table class="form-table" role="presentation">
                    <tr>
                        <th scope="row">
                            <label for="maca_price_currency"><?php esc_html_e('Price Currency', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <input type="text" id="maca_price_currency" name="maca_price_currency" value="<?php echo esc_attr($price_currency); ?>" class="small-text">
                            <p class="description"><?php esc_html_e('Currency label shown after dish prices, e.g. kr, SEK, €, $', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="maca_dish_menu_theme"><?php esc_html_e('Online menu theme', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <select id="maca_dish_menu_theme" name="maca_dish_menu_theme">
                                <?php foreach ($dish_menu_themes as $theme_key => $theme_label) : ?>
                                    <option value="<?php echo esc_attr($theme_key); ?>" <?php selected($dish_menu_theme, $theme_key); ?>>
                                        <?php echo esc_html($theme_label); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <p class="description"><?php esc_html_e('Appearance of the online menu on your website, QR page, and takeaway page. Print menu uses a separate theme under Menu footer below.', 'maca-restu-pro'); ?></p>
                            <div class="maca-dish-menu-theme-preview-wrap" aria-live="polite">
                                <p class="maca-dish-menu-theme-preview-label"><?php esc_html_e('Preview', 'maca-restu-pro'); ?></p>
                                <?php maca_menulist_render_dish_menu_theme_preview($dish_menu_theme, $dish_menu_layout); ?>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="maca_dish_menu_layout"><?php esc_html_e('Dish layout', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <select id="maca_dish_menu_layout" name="maca_dish_menu_layout">
                                <?php foreach ($dish_menu_layouts as $layout_key => $layout_label) : ?>
                                    <option value="<?php echo esc_attr($layout_key); ?>" <?php selected($dish_menu_layout, $layout_key); ?>>
                                        <?php echo esc_html($layout_label); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <p class="description"><?php esc_html_e('Rows shows one dish per line. Grid shows dishes as cards in a responsive column layout. Applies to all online menu themes.', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="maca_dish_category_filter"><?php esc_html_e('Category filters', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <input type="checkbox" id="maca_dish_category_filter" name="maca_dish_category_filter" value="1" <?php checked($dish_category_filter); ?>>
                            <label for="maca_dish_category_filter"><?php esc_html_e('Show category filters on the online menu (website and QR page)', 'maca-restu-pro'); ?></label>
                            <p class="description"><?php esc_html_e('Guests can filter dishes by category, e.g. appetizer, main course, or dessert.', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="maca_dish_category_nav"><?php esc_html_e('Category navigation', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <select id="maca_dish_category_nav" name="maca_dish_category_nav" class="regular-text">
                                <option value="buttons" <?php selected($dish_category_nav, 'buttons'); ?>><?php esc_html_e('Filter buttons (horizontal)', 'maca-restu-pro'); ?></option>
                                <option value="dropdown" <?php selected($dish_category_nav, 'dropdown'); ?>><?php esc_html_e('Compact dropdown list', 'maca-restu-pro'); ?></option>
                            </select>
                            <p class="description"><?php esc_html_e('How guests jump between dish categories on the website menu and QR page. Requires category filters to be enabled above.', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="maca_dish_clickable_images"><?php esc_html_e('Clickable dish images', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <input type="checkbox" id="maca_dish_clickable_images" name="maca_dish_clickable_images" value="1" <?php checked($dish_clickable_images); ?>>
                            <label for="maca_dish_clickable_images"><?php esc_html_e('Allow guests to tap dish images to view a larger version', 'maca-restu-pro'); ?></label>
                            <p class="description"><?php esc_html_e('Applies to the website menu and QR page when dishes have an image.', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="maca_campaign_exclusive_mode"><?php esc_html_e('Exklusivt kampanjläge', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <input type="checkbox" id="maca_campaign_exclusive_mode" name="maca_campaign_exclusive_mode" value="1" <?php checked($campaign_exclusive_mode); ?>>
                            <label for="maca_campaign_exclusive_mode"><?php esc_html_e('När en kampanj är aktiv: dölj vanliga kategorier och visa endast kampanjrätter', 'maca-restu-pro'); ?></label>
                            <p class="description"><?php esc_html_e('Passar för tidsstyrda menyer som Sommarmeny, Quizkväll eller Lunchkampanj.', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="maca_dish_guest_ratings"><?php esc_html_e('Guest dish ratings', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <input type="checkbox" id="maca_dish_guest_ratings" name="maca_dish_guest_ratings" value="1" <?php checked($dish_guest_ratings); ?>>
                            <label for="maca_dish_guest_ratings"><?php esc_html_e('Allow guests to rate each dish from 1 to 5 stars', 'maca-restu-pro'); ?></label>
                            <p class="description"><?php esc_html_e('Shows star ratings on the website menu and QR page. Each guest can rate a dish once (stored in a browser cookie).', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    </table>
                </section>

                <section class="maca-settings-section maca-settings-tab-panel maca-setting-dishes-only" id="maca-settings-menu-footer" data-settings-tab="dishes" <?php echo !$dishes_mode_effective ? 'style="display:none;"' : ''; ?>>
                    <h2 class="maca-settings-section-title"><?php esc_html_e('Menu footer', 'maca-restu-pro'); ?></h2>
                    <p class="maca-settings-section-desc description"><?php esc_html_e('Legal and informational text at the bottom of the online menu on website, QR, and print.', 'maca-restu-pro'); ?></p>
                    <table class="form-table" role="presentation">
                    <tr>
                        <th scope="row">
                            <label for="maca_menu_footer_enabled"><?php esc_html_e('Menu footer', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <input type="checkbox" id="maca_menu_footer_enabled" name="maca_menu_footer_enabled" value="1" <?php checked($menu_footer_enabled); ?>>
                            <label for="maca_menu_footer_enabled"><?php esc_html_e('Show allergy, price, and contact information at the bottom of the online menu', 'maca-restu-pro'); ?></label>
                            <p class="description"><?php esc_html_e('Recommended for restaurants. Shown on the website, QR menu, and printable menu.', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    <tr class="maca-menu-footer-fields">
                        <th scope="row">
                            <label for="maca_menu_footer_allergy_text"><?php echo esc_html(maca_menulist_admin_primary_field_label(__('Allergy information', 'maca-restu-pro'))); ?></label>
                        </th>
                        <td>
                            <textarea id="maca_menu_footer_allergy_text" name="maca_menu_footer_allergy_text" rows="3" class="large-text" placeholder="<?php echo esc_attr(maca_menulist_get_menu_footer_default_text('allergy')); ?>"><?php echo esc_textarea($menu_footer_allergy_text); ?></textarea>
                            <?php if (!maca_menulist_admin_show_local_content_fields()) : ?>
                                <p class="description"><?php esc_html_e('Leave empty to use the default text.', 'maca-restu-pro'); ?></p>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php if (maca_menulist_admin_show_local_content_fields()) : ?>
                    <tr class="maca-menu-footer-fields">
                        <th scope="row">
                            <label for="maca_menu_footer_allergy_text_en"><?php echo esc_html(maca_menulist_bilingual_field_label(__('Allergy information', 'maca-restu-pro'), true)); ?></label>
                        </th>
                        <td>
                            <textarea id="maca_menu_footer_allergy_text_en" name="maca_menu_footer_allergy_text_en" rows="3" class="large-text" placeholder="<?php echo esc_attr(maca_menulist_get_menu_footer_default_text('allergy')); ?>"><?php echo esc_textarea($menu_footer_allergy_text_en); ?></textarea>
                            <p class="description"><?php esc_html_e('Leave empty to use the default text.', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    <?php endif; ?>
                    <tr class="maca-menu-footer-fields">
                        <th scope="row">
                            <label for="maca_menu_footer_price_text"><?php echo esc_html(maca_menulist_admin_primary_field_label(__('Price information', 'maca-restu-pro'))); ?></label>
                        </th>
                        <td>
                            <textarea id="maca_menu_footer_price_text" name="maca_menu_footer_price_text" rows="2" class="large-text" placeholder="<?php echo esc_attr(maca_menulist_get_menu_footer_default_text('price')); ?>"><?php echo esc_textarea($menu_footer_price_text); ?></textarea>
                            <?php if (!maca_menulist_admin_show_local_content_fields()) : ?>
                                <p class="description"><?php esc_html_e('Leave empty to use the default text.', 'maca-restu-pro'); ?></p>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php if (maca_menulist_admin_show_local_content_fields()) : ?>
                    <tr class="maca-menu-footer-fields">
                        <th scope="row">
                            <label for="maca_menu_footer_price_text_en"><?php echo esc_html(maca_menulist_bilingual_field_label(__('Price information', 'maca-restu-pro'), true)); ?></label>
                        </th>
                        <td>
                            <textarea id="maca_menu_footer_price_text_en" name="maca_menu_footer_price_text_en" rows="2" class="large-text" placeholder="<?php echo esc_attr(maca_menulist_get_menu_footer_default_text('price')); ?>"><?php echo esc_textarea($menu_footer_price_text_en); ?></textarea>
                            <p class="description"><?php esc_html_e('Leave empty to use the default text.', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    <?php endif; ?>
                    <tr class="maca-menu-footer-fields">
                        <th scope="row">
                            <label for="maca_menu_footer_serves_alcohol"><?php esc_html_e('Alcohol service', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <input type="checkbox" id="maca_menu_footer_serves_alcohol" name="maca_menu_footer_serves_alcohol" value="1" <?php checked($menu_footer_serves_alcohol); ?>>
                            <label for="maca_menu_footer_serves_alcohol"><?php esc_html_e('Show age limit notice in the menu footer', 'maca-restu-pro'); ?></label>
                        </td>
                    </tr>
                    <tr class="maca-menu-footer-fields maca-menu-footer-alcohol">
                        <th scope="row">
                            <label for="maca_menu_footer_age_text"><?php echo esc_html(maca_menulist_admin_primary_field_label(__('Age limit notice', 'maca-restu-pro'))); ?></label>
                        </th>
                        <td>
                            <textarea id="maca_menu_footer_age_text" name="maca_menu_footer_age_text" rows="2" class="large-text" placeholder="<?php echo esc_attr(maca_menulist_get_menu_footer_default_text('age')); ?>"><?php echo esc_textarea($menu_footer_age_text); ?></textarea>
                            <?php if (!maca_menulist_admin_show_local_content_fields()) : ?>
                                <p class="description"><?php esc_html_e('Shown when alcohol service is enabled. Leave empty to use the default text.', 'maca-restu-pro'); ?></p>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php if (maca_menulist_admin_show_local_content_fields()) : ?>
                    <tr class="maca-menu-footer-fields maca-menu-footer-alcohol">
                        <th scope="row">
                            <label for="maca_menu_footer_age_text_en"><?php echo esc_html(maca_menulist_bilingual_field_label(__('Age limit notice', 'maca-restu-pro'), true)); ?></label>
                        </th>
                        <td>
                            <textarea id="maca_menu_footer_age_text_en" name="maca_menu_footer_age_text_en" rows="2" class="large-text" placeholder="<?php echo esc_attr(maca_menulist_get_menu_footer_default_text('age')); ?>"><?php echo esc_textarea($menu_footer_age_text_en); ?></textarea>
                            <p class="description"><?php esc_html_e('Shown when alcohol service is enabled. Leave empty to use the default text.', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    <?php endif; ?>
                    </table>
                </section>

                <section class="maca-settings-section maca-settings-tab-panel maca-setting-dishes-only" id="maca-settings-print-menu" data-settings-tab="dishes" <?php echo !$dishes_mode_effective ? 'style="display:none;"' : ''; ?>>
                    <h2 class="maca-settings-section-title"><?php esc_html_e('Printable menu', 'maca-restu-pro'); ?></h2>
                    <p class="maca-settings-section-desc description"><?php esc_html_e('Layout for Dishes → Print menu (paper or PDF).', 'maca-restu-pro'); ?></p>
                    <table class="form-table" role="presentation">
                    <tr>
                        <th scope="row">
                            <label for="maca_menu_print_title"><?php echo esc_html(maca_menulist_admin_primary_field_label(__('Print menu title', 'maca-restu-pro'))); ?></label>
                        </th>
                        <td>
                            <input type="text" id="maca_menu_print_title" name="maca_menu_print_title" value="<?php echo esc_attr($menu_print_title); ?>" class="regular-text" placeholder="<?php echo esc_attr(maca_menulist_get_qr_guest_page_title()); ?>">
                            <p class="description"><?php esc_html_e('Title on the printable menu from Dishes → Print menu. Defaults to restaurant name or “Our menu”.', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    <?php if (maca_menulist_admin_show_local_content_fields()) : ?>
                    <tr>
                        <th scope="row">
                            <label for="maca_menu_print_title_en"><?php echo esc_html(maca_menulist_bilingual_field_label(__('Print menu title', 'maca-restu-pro'), true)); ?></label>
                        </th>
                        <td>
                            <input type="text" id="maca_menu_print_title_en" name="maca_menu_print_title_en" value="<?php echo esc_attr($menu_print_title_en); ?>" class="regular-text" placeholder="<?php echo esc_attr(maca_menulist_get_qr_guest_page_title()); ?>">
                        </td>
                    </tr>
                    <?php endif; ?>
                    <tr>
                        <th scope="row">
                            <label for="maca_menu_print_theme"><?php esc_html_e('Print menu theme', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <select id="maca_menu_print_theme" name="maca_menu_print_theme">
                                <?php foreach ($menu_print_themes as $theme_key => $theme_label) : ?>
                                    <option value="<?php echo esc_attr($theme_key); ?>" <?php selected($menu_print_theme, $theme_key); ?>>
                                        <?php echo esc_html($theme_label); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <p class="description">
                                <?php esc_html_e('Classic: serif with double frame. Modern: sans-serif with accent colour. Minimal: clean layout without frame.', 'maca-restu-pro'); ?>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="maca_menu_print_paper_size"><?php esc_html_e('Print paper size', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <select id="maca_menu_print_paper_size" name="maca_menu_print_paper_size">
                                <option value="" <?php selected($menu_print_paper_size, ''); ?>><?php esc_html_e('Same as QR code print', 'maca-restu-pro'); ?></option>
                                <option value="a4" <?php selected($menu_print_paper_size, 'a4'); ?>><?php esc_html_e('A4', 'maca-restu-pro'); ?></option>
                                <option value="a5" <?php selected($menu_print_paper_size, 'a5'); ?>><?php esc_html_e('A5', 'maca-restu-pro'); ?></option>
                            </select>
                            <p class="description"><?php esc_html_e('Used when saving the printable menu as PDF. Zero page margin avoids browser URL/date footers.', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="maca_menu_print_layout"><?php esc_html_e('Print layout density', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <select id="maca_menu_print_layout" name="maca_menu_print_layout">
                                <option value="compact" <?php selected($menu_print_layout, 'compact'); ?>><?php esc_html_e('Compact (fewer page breaks)', 'maca-restu-pro'); ?></option>
                                <option value="standard" <?php selected($menu_print_layout, 'standard'); ?>><?php esc_html_e('Standard (more spacing)', 'maca-restu-pro'); ?></option>
                            </select>
                            <p class="description"><?php esc_html_e('Switch between compact and standard spacing in printable menus so you can compare PDF output.', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="maca_menu_print_logo"><?php esc_html_e('Print menu logo', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <input type="text" id="maca_menu_print_logo" name="maca_menu_print_logo" value="<?php echo esc_attr($menu_print_logo); ?>" class="regular-text">
                            <button type="button" class="button" id="upload_menu_print_logo"><?php esc_html_e('Upload Logo', 'maca-restu-pro'); ?></button>
                            <p class="description"><?php esc_html_e('Shown centered above the menu title on the print page. Leave empty to use the QR menu logo if set.', 'maca-restu-pro'); ?></p>
                            <?php
                            $menu_print_logo_preview = $menu_print_logo !== '' ? $menu_print_logo : (function_exists('maca_menulist_get_qr_menu_logo_url') ? maca_menulist_get_qr_menu_logo_url() : get_option('maca_menulist_qr_logo', ''));
                            if ($menu_print_logo_preview !== '') :
                                ?>
                                <p><img id="maca_menu_print_logo_preview" src="<?php echo esc_url($menu_print_logo_preview); ?>" alt="<?php esc_attr_e('Logo', 'maca-restu-pro'); ?>" style="max-width: 180px; max-height: 100px; margin-top: 10px;"></p>
                            <?php else : ?>
                                <p><img id="maca_menu_print_logo_preview" src="" alt="<?php esc_attr_e('Logo', 'maca-restu-pro'); ?>" style="max-width: 180px; max-height: 100px; margin-top: 10px; display: none;"></p>
                            <?php endif; ?>
                        </td>
                    </tr>
                    </table>
                </section>

                <section class="maca-settings-section maca-settings-tab-panel maca-setting-dishes-only" id="maca-settings-table-order" data-settings-tab="orders" <?php echo !$dishes_mode_effective ? 'style="display:none;"' : ''; ?>>
                    <h2 class="maca-settings-section-title"><?php esc_html_e('Table ordering', 'maca-restu-pro'); ?></h2>
                    <table class="form-table" role="presentation">
                    <tr>
                        <th scope="row">
                            <label for="maca_table_order"><?php esc_html_e('Guest order list', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <input type="checkbox" id="maca_table_order" name="maca_table_order" value="1" <?php checked($table_order); ?>>
                            <label for="maca_table_order"><?php esc_html_e('Let guests mark dishes and drinks with quantity for the table order', 'maca-restu-pro'); ?></label>
                            <p class="description"><?php esc_html_e('Add ?bord=12 to the QR URL to pre-fill the table number.', 'maca-restu-pro'); ?></p>
                            <p style="margin-top: 10px;">
                                <label for="maca_table_order_delivery_mode"><strong><?php esc_html_e('Delivery mode', 'maca-restu-pro'); ?></strong></label><br>
                                <select id="maca_table_order_delivery_mode" name="maca_table_order_delivery_mode">
                                    <option value="guest_screen" <?php selected($table_order_delivery_mode, 'guest_screen'); ?>><?php esc_html_e('Guest screen only (device)', 'maca-restu-pro'); ?></option>
                                    <option value="waiter" <?php selected($table_order_delivery_mode, 'waiter'); ?>><?php esc_html_e('Waiter page (server)', 'maca-restu-pro'); ?></option>
                                    <option value="kitchen" <?php selected($table_order_delivery_mode, 'kitchen'); ?>><?php esc_html_e('Kitchen page (server)', 'maca-restu-pro'); ?></option>
                                    <option value="both" <?php selected($table_order_delivery_mode, 'both'); ?>><?php esc_html_e('Waiter and kitchen pages (server)', 'maca-restu-pro'); ?></option>
                                </select>
                            </p>
                            <p class="description" style="margin-top: 10px;">
                                <a href="<?php echo esc_url(function_exists('maca_menulist_personal_admin_url') ? maca_menulist_personal_admin_url(array('tab' => 'screens')) : admin_url('admin.php?page=maca-restu-personal&tab=screens')); ?>">
                                    <?php esc_html_e('Personal → Staff screens', 'maca-restu-pro'); ?>
                                </a>
                                —
                                <?php esc_html_e('Staff PIN, waiter/kitchen URLs, personalliggare and permalink refresh.', 'maca-restu-pro'); ?>
                            </p>
                            <?php if ($table_order_staff_pin_needs_resave) : ?>
                                <p><strong style="color:#b32d2e;"><?php esc_html_e('Re-enter your staff PIN under Personal → Staff screens and save once — required after the latest update.', 'maca-restu-pro'); ?></strong></p>
                            <?php endif; ?>
                            <fieldset style="margin-top: 10px;">
                                <label>
                                    <input type="checkbox" name="maca_table_order_line_notes" value="1" <?php checked($table_order_line_notes); ?>>
                                    <?php esc_html_e('Note per item', 'maca-restu-pro'); ?>
                                </label>
                                <br>
                                <label>
                                    <input type="checkbox" name="maca_table_order_order_note" value="1" <?php checked($table_order_order_note); ?>>
                                    <?php esc_html_e('Order note', 'maca-restu-pro'); ?>
                                </label>
                                <br>
                                <label>
                                    <input type="checkbox" name="maca_table_order_show_prices" value="1" <?php checked($table_order_show_prices); ?>>
                                    <?php esc_html_e('Show prices in order summary', 'maca-restu-pro'); ?>
                                </label>
                                <br>
                                <label>
                                    <input type="checkbox" name="maca_table_order_guest_status" value="1" <?php checked($table_order_guest_status || maca_menulist_table_order_guest_status_enabled()); ?>>
                                    <?php esc_html_e('Show order status to guests after submit (kitchen progress)', 'maca-restu-pro'); ?>
                                </label>
                            </fieldset>
                        </td>
                    </tr>
                    </table>
                </section>

                <section class="maca-settings-section maca-settings-tab-panel" id="maca-settings-opening-hours" data-settings-tab="hours">
                    <h2 class="maca-settings-section-title"><?php esc_html_e('Opening hours', 'maca-restu-pro'); ?></h2>
                    <p class="maca-settings-section-desc description"><?php esc_html_e('Weekly opening hours for [maca_opening_hours] on your website (no subscription required). Also used for table reservations when that Pro feature is enabled. Date-specific exceptions are on the Exceptions tab.', 'maca-restu-pro'); ?></p>
                    <?php maca_menulist_render_opening_hours_fields(); ?>
                </section>

                <section class="maca-settings-section maca-settings-tab-panel maca-setting-files-only" id="maca-settings-pdf-menus" data-settings-tab="pdf" <?php echo $dishes_mode_effective ? 'style="display:none;"' : ''; ?>>
                    <h2 class="maca-settings-section-title"><?php esc_html_e('PDF and image menus', 'maca-restu-pro'); ?></h2>
                    <table class="form-table" role="presentation">
                    <tr>
                        <th scope="row">
                            <label for="maca_display_mode"><?php esc_html_e('Menu Display Mode', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <select id="maca_display_mode" name="maca_display_mode">
                                <option value="inline" <?php selected($display_mode, 'inline'); ?>><?php esc_html_e('Inline (on same page)', 'maca-restu-pro'); ?></option>
                                <option value="popup" <?php selected($display_mode, 'popup'); ?>><?php esc_html_e('Popup modal', 'maca-restu-pro'); ?></option>
                                <option value="new_page" <?php selected($display_mode, 'new_page'); ?>><?php esc_html_e('New page (target=_blank)', 'maca-restu-pro'); ?></option>
                            </select>
                            <p class="description"><?php esc_html_e('Choose how menus open when guests click a category (website shortcode/block and QR menu page). Clear any page cache after changing.', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="maca_button_layout"><?php esc_html_e('Button Layout', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <select id="maca_button_layout" name="maca_button_layout">
                                <option value="horizontal" <?php selected($button_layout, 'horizontal'); ?>><?php esc_html_e('Horizontal (row)', 'maca-restu-pro'); ?></option>
                                <option value="vertical" <?php selected($button_layout, 'vertical'); ?>><?php esc_html_e('Vertical (column)', 'maca-restu-pro'); ?></option>
                                <option value="fit_width" <?php selected($button_layout, 'fit_width'); ?>><?php esc_html_e('Fit Width (responsive)', 'maca-restu-pro'); ?></option>
                                <option value="fit_height" <?php selected($button_layout, 'fit_height'); ?>><?php esc_html_e('Fit Height (responsive)', 'maca-restu-pro'); ?></option>
                            </select>
                            <p class="description"><?php esc_html_e('Choose how category buttons are arranged.', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="maca_pdf_display_mode"><?php esc_html_e('PDF Display Mode', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <select id="maca_pdf_display_mode" name="maca_pdf_display_mode">
                                <option value="full_page" <?php selected($pdf_display_mode, 'full_page'); ?>><?php esc_html_e('Full Page (scrollable)', 'maca-restu-pro'); ?></option>
                                <option value="full_width" <?php selected($pdf_display_mode, 'full_width'); ?>><?php esc_html_e('Full Width (fit to screen)', 'maca-restu-pro'); ?></option>
                            </select>
                            <p class="description"><?php esc_html_e('Choose how PDF menus are displayed in new page mode.', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="maca_show_menu_title"><?php esc_html_e('Menu title', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <input type="checkbox" id="maca_show_menu_title" name="maca_show_menu_title" value="1" <?php checked($show_menu_title); ?>>
                            <label for="maca_show_menu_title"><?php esc_html_e('Show menu title above the menu file', 'maca-restu-pro'); ?></label>
                            <p class="description"><?php esc_html_e('Applies to the website shortcode and block. QR menu page uses the page title instead.', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="maca_show_schedule_notes"><?php esc_html_e('Serving hours on website', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <input type="checkbox" id="maca_show_schedule_notes" name="maca_show_schedule_notes" value="1" <?php checked($show_schedule_notes); ?>>
                            <label for="maca_show_schedule_notes"><?php esc_html_e('Show serving hours when a menu is outside its live schedule', 'maca-restu-pro'); ?></label>
                            <p class="description"><?php esc_html_e('Website visitors can browse all published menus. The QR page only shows menus that are live right now.', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    </table>
                </section>

                </div><!-- .maca-settings-sections -->
                
                <?php submit_button(__('Save Settings', 'maca-restu-pro')); ?>
            </form>

            <?php maca_menulist_render_booking_exceptions_settings_panel(); ?>

            <script>
                jQuery(document).ready(function($) {
                    function toggleContentModeFields() {
                        var mode = $('#maca_content_mode').val();
                        if (mode === 'dishes') {
                            $('.maca-setting-files-only').hide();
                            toggleMenuFooterFields();
                        } else {
                            $('.maca-setting-files-only').show();
                            $('.maca-setting-dishes-only').hide();
                        }
                        if (typeof window.macaMenulistRefreshSettingsPanels === 'function') {
                            window.macaMenulistRefreshSettingsPanels();
                        }
                    }

                    function toggleMenuFooterFields() {
                        var enabled = $('#maca_menu_footer_enabled').is(':checked');
                        if (enabled) {
                            $('.maca-menu-footer-fields').show();
                        } else {
                            $('.maca-menu-footer-fields').hide();
                        }

                        if ($('#maca_menu_footer_serves_alcohol').is(':checked')) {
                            $('.maca-menu-footer-alcohol').show();
                        } else {
                            $('.maca-menu-footer-alcohol').hide();
                        }
                    }

                    function toggleLanguageSwitcherField() {
                        var dual = $('#maca_dual_language_menu').is(':checked');
                        var $switcher = $('#maca_menu_language_switcher');

                        if (dual) {
                            $switcher.prop('checked', false).prop('disabled', true);
                        } else {
                            $switcher.prop('disabled', false);
                        }
                    }

                    $('#maca_content_mode').on('change', toggleContentModeFields);
                    $('#maca_menu_footer_enabled, #maca_menu_footer_serves_alcohol').on('change', toggleMenuFooterFields);
                    $('#maca_dual_language_menu').on('change', toggleLanguageSwitcherField);
                    toggleContentModeFields();
                    toggleMenuFooterFields();
                    toggleLanguageSwitcherField();

                    $('#upload_menu_print_logo').on('click', function(e) {
                        e.preventDefault();
                        var frame = wp.media({
                            title: <?php echo wp_json_encode(__('Select print menu logo', 'maca-restu-pro')); ?>,
                            button: { text: <?php echo wp_json_encode(__('Use this logo', 'maca-restu-pro')); ?> },
                            multiple: false
                        });
                        frame.on('select', function() {
                            var attachment = frame.state().get('selection').first().toJSON();
                            $('#maca_menu_print_logo').val(attachment.url);
                            $('#maca_menu_print_logo_preview').attr('src', attachment.url).show();
                        });
                        frame.open();
                    });
                });
            </script>
        </div>
        <?php
    }
    
    /**
     * Render guide page
     */
    public function render_guide_page() {
        require_once MACA_MENULIST_PLUGIN_DIR . 'includes/markdown.php';

        // Detect language and load appropriate guide file
        $locale = get_locale();
        $lang = substr($locale, 0, 2); // Get first 2 characters (e.g., 'sv' from 'sv_SE')
        
        if ($lang === 'sv') {
            $guide_file = MACA_MENULIST_PLUGIN_DIR . 'docs/GUIDE-sv.md';
        } else {
            $guide_file = MACA_MENULIST_PLUGIN_DIR . 'docs/GUIDE-en.md';
        }
        
        // Fallback to English if language file doesn't exist
        if (!file_exists($guide_file)) {
            $guide_file = MACA_MENULIST_PLUGIN_DIR . 'docs/GUIDE-en.md';
        }
        
        ?>
        <div class="wrap">
            <h1><?php esc_html_e('User Guide', 'maca-restu-pro'); ?></h1>
            
            <div class="maca-guide-content">
                <?php
                if (file_exists($guide_file)) {
                    $guide_html = maca_menulist_render_markdown_file($guide_file);
                    if ($guide_html === '') {
                        echo '<p>' . esc_html__('Guide file is empty or could not be read.', 'maca-restu-pro') . '</p>';
                    } else {
                        echo $guide_html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Sanitized in maca_menulist_render_markdown_file().
                    }
                } else {
                    echo '<p>' . esc_html__('Guide file not found.', 'maca-restu-pro') . '</p>';
                }
                ?>
            </div>
        </div>
        <?php
    }
    
    /**
     * Handle QR print page
     */
    public function handle_qr_print_page() {
        if (!isset($_GET['maca_qr_print']) || sanitize_text_field(wp_unslash($_GET['maca_qr_print'])) !== '1') {
            return;
        }

        if (!maca_menulist_user_can_manage_plugin()) {
            wp_die(esc_html__('You do not have permission to view this page.', 'maca-restu-pro'));
        }

        $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';
        if (!wp_verify_nonce($nonce, 'maca_qr_print')) {
            wp_die(esc_html__('Invalid request.', 'maca-restu-pro'));
        }

        $qr_title = get_option('maca_menulist_qr_title', __('Scan for Menu', 'maca-restu-pro'));
            $qr_subtitle = get_option('maca_menulist_qr_subtitle', __('Point your camera to view our menu', 'maca-restu-pro'));
            $qr_logo = get_option('maca_menulist_qr_logo', '');
            $qr_print_logo = function_exists('maca_menulist_get_qr_print_logo_url')
                ? maca_menulist_get_qr_print_logo_url()
                : $qr_logo;
            $qr_paper_size = get_option('maca_menulist_qr_paper_size', 'a4');
            $qr_category = intval(get_option('maca_menulist_qr_category', 0));
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce verified above; table number is encoded in QR only.
            $table_number = isset($_GET['bord']) ? sanitize_text_field(wp_unslash($_GET['bord'])) : '';
            $qr_url = maca_menulist_get_qr_url($qr_category, $table_number);
            
            // Set page size for print
            $page_size = $qr_paper_size === 'a5' ? 'A5' : 'A4';
            
            // Render clean print page
            echo '<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>' . esc_html($qr_title) . '</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            background: #f5f5f5;
        }
        .qr-frame {
            background: white;
            padding: 50px;
            border: 3px solid #0073aa;
            border-radius: 15px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.15);
            max-width: 500px;
        }
        .qr-container {
            text-align: center;
        }
        .qr-logo {
            margin-bottom: 30px;
        }
        .qr-logo img {
            max-width: 200px;
            max-height: 200px;
        }
        .qr-title {
            font-size: 28px;
            font-weight: bold;
            margin-bottom: 30px;
            color: #333;
        }
        .qr-code {
            margin: 30px 0;
        }
        .qr-code img {
            width: 250px;
            height: 250px;
        }
        .qr-subtitle {
            font-size: 16px;
            color: #666;
            margin-top: 30px;
        }
        .qr-table {
            font-size: 22px;
            font-weight: 700;
            color: #0073aa;
            margin-top: 20px;
        }
        @media print {
            @page {
                margin: 0;
                size: ' . esc_attr($page_size) . ';
            }
            body {
                background: white;
                margin: 0;
                padding: 0;
            }
            .qr-frame {
                border: 3px solid #0073aa;
                border-radius: 15px;
                padding: 30px;
                box-shadow: none;
                max-width: none;
            }
            button {
                display: none;
            }
        }
    </style>
</head>
<body>
    <div class="qr-frame">
        <div class="qr-container">';
            
            if ($qr_print_logo !== '') {
                echo '<div class="qr-logo">
                    <img src="' . esc_url($qr_print_logo) . '" alt="Logo">
                </div>';
            }
            
            echo '<h1 class="qr-title">' . esc_html($qr_title) . '</h1>';
            if ($table_number !== '') {
                /* translators: %s: table number */
                echo '<p class="qr-table">' . esc_html(sprintf(__('Table %s', 'maca-restu-pro'), $table_number)) . '</p>';
            }
            echo '<div class="qr-code">
                <img src="https://api.qrserver.com/v1/create-qr-code/?size=250x250&data=' . urlencode($qr_url) . '" alt="QR Code">
            </div>
            <p class="qr-subtitle">' . esc_html($qr_subtitle) . '</p>
            <div style="margin-top: 40px; text-align: center;">
                <button onclick="window.print()" style="padding: 12px 24px; background: #0073aa; color: white; border: none; border-radius: 5px; cursor: pointer; font-size: 16px;">' . esc_html__('Print / Save as PDF', 'maca-restu-pro') . '</button>
            </div>
        </div>
    </div>
</body>
</html>';

        exit;
    }
    
    /**
     * Render QR Code page
     */
    public function render_qr_page() {
        // Get all published pages
        $pages = get_pages(array('post_status' => 'publish'));
        $selected_page = get_option('maca_menulist_qr_page', '');
        $qr_title = get_option('maca_menulist_qr_title', __('Scan for Menu', 'maca-restu-pro'));
        $qr_subtitle = get_option('maca_menulist_qr_subtitle', __('Point your camera to view our menu', 'maca-restu-pro'));
        $qr_logo = get_option('maca_menulist_qr_logo', '');
        $qr_menu_show_logo = get_option('maca_menulist_qr_menu_show_logo', '1') === '1';
        $qr_print_show_logo = get_option('maca_menulist_qr_print_show_logo', '1') === '1';
        $qr_category = get_option('maca_menulist_qr_category', '');
        $qr_display_mode = get_option('maca_menulist_qr_display_mode', 'full_page');
        $qr_paper_size = get_option('maca_menulist_qr_paper_size', 'a4');
        $qr_slug = maca_menulist_get_qr_slug();
        $qr_url = maca_menulist_get_qr_url();
        $qr_print_url = wp_nonce_url(admin_url('admin.php?page=maca-restu-qr&maca_qr_print=1'), 'maca_qr_print');
        $table_order_enabled = maca_menulist_table_order_enabled();
        $takeaway_url = function_exists('maca_menulist_get_takeaway_url') ? maca_menulist_get_takeaway_url() : '';
        $takeaway_ordering = function_exists('maca_menulist_takeaway_ordering_enabled') && maca_menulist_takeaway_ordering_enabled();
        
        $categories = maca_menulist_db_get_categories(false);
        
        ?>
        <div class="wrap">
            <h1><?php esc_html_e('QR Code Generator', 'maca-restu-pro'); ?></h1>
            
            <div class="maca-qr-generator">
                <form method="post" action="">
                    <?php wp_nonce_field('maca_save', 'maca_nonce'); ?>
                    <input type="hidden" name="maca_action" value="save_qr">
                    
                    <table class="form-table">
                        <tr>
                            <th scope="row">
                                <label for="qr_slug"><?php esc_html_e('Short URL slug', 'maca-restu-pro'); ?></label>
                            </th>
                            <td>
                                <code><?php echo esc_html(home_url('/')); ?></code>
                                <input type="text" id="qr_slug" name="qr_slug" value="<?php echo esc_attr($qr_slug); ?>" class="regular-text" style="width: 120px;">
                                <code>/</code>
                                <p class="description">
                                    <?php
                                    echo esc_html__('Public menu link:', 'maca-restu-pro') . ' ';
                                    echo '<a href="' . esc_url($qr_url) . '" target="_blank" rel="noopener">' . esc_html($qr_url) . '</a>';
                                    ?>
                                </p>
                                <p class="description"><?php esc_html_e('Use only lowercase letters, numbers and hyphens. Save to apply. Category-specific links: /slug/ID (e.g. /qrmeny/3/).', 'maca-restu-pro'); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="qr_category"><?php esc_html_e('Select Category', 'maca-restu-pro'); ?></label>
                            </th>
                            <td>
                                <select id="qr_category" name="qr_category" class="regular-text">
                                    <option value=""><?php esc_html_e('-- Show all categories --', 'maca-restu-pro'); ?></option>
                                    <?php foreach ($categories as $cat): ?>
                                        <option value="<?php echo esc_attr($cat->id); ?>" <?php selected($qr_category, $cat->id); ?>>
                                            <?php echo esc_html(maca_menulist_get_category_display_name($cat)); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <p class="description"><?php esc_html_e('Select a specific category to show, or leave empty to show all categories.', 'maca-restu-pro'); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="qr_title"><?php esc_html_e('QR Code Title', 'maca-restu-pro'); ?></label>
                            </th>
                            <td>
                                <input type="text" id="qr_title" name="qr_title" value="<?php echo esc_attr($qr_title); ?>" class="regular-text">
                                <p class="description"><?php esc_html_e('Title to display above the QR code when printing.', 'maca-restu-pro'); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="qr_subtitle"><?php esc_html_e('QR Code Subtitle', 'maca-restu-pro'); ?></label>
                            </th>
                            <td>
                                <input type="text" id="qr_subtitle" name="qr_subtitle" value="<?php echo esc_attr($qr_subtitle); ?>" class="regular-text">
                                <p class="description"><?php esc_html_e('Subtitle to display below the QR code when printing.', 'maca-restu-pro'); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="qr_logo"><?php esc_html_e('Logo Image', 'maca-restu-pro'); ?></label>
                            </th>
                            <td>
                                <input type="text" id="qr_logo" name="qr_logo" value="<?php echo esc_attr($qr_logo); ?>" class="regular-text">
                                <button type="button" class="button" id="upload_qr_logo"><?php esc_html_e('Upload Logo', 'maca-restu-pro'); ?></button>
                                <p class="description"><?php esc_html_e('Logo image used for the QR menu page and/or QR print page (see options below).', 'maca-restu-pro'); ?></p>
                                <?php if (!empty($qr_logo)) : ?>
                                    <div class="image-preview">
                                        <img src="<?php echo esc_url($qr_logo); ?>" alt="<?php esc_attr_e('Logo', 'maca-restu-pro'); ?>" style="max-width: 100px; margin-top: 10px;">
                                    </div>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php esc_html_e('Show logo on', 'maca-restu-pro'); ?></th>
                            <td>
                                <label>
                                    <input type="checkbox" id="qr_menu_show_logo" name="qr_menu_show_logo" value="1" <?php checked($qr_menu_show_logo); ?>>
                                    <?php esc_html_e('QR menu page', 'maca-restu-pro'); ?>
                                </label>
                                <br>
                                <label>
                                    <input type="checkbox" id="qr_print_show_logo" name="qr_print_show_logo" value="1" <?php checked($qr_print_show_logo); ?>>
                                    <?php esc_html_e('QR code print page', 'maca-restu-pro'); ?>
                                </label>
                                <p class="description"><?php esc_html_e('Choose separately whether the logo appears when guests open the menu (e.g. /qrmeny/) and on the printable QR code page in admin.', 'maca-restu-pro'); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="qr_display_mode"><?php esc_html_e('QR inline layout', 'maca-restu-pro'); ?></label>
                            </th>
                            <td>
                                <select id="qr_display_mode" name="qr_display_mode" class="regular-text">
                                    <option value="full_page" <?php selected($qr_display_mode, 'full_page'); ?>><?php esc_html_e('Full Page', 'maca-restu-pro'); ?></option>
                                    <option value="full_width" <?php selected($qr_display_mode, 'full_width'); ?>><?php esc_html_e('Full Width', 'maca-restu-pro'); ?></option>
                                </select>
                                <p class="description"><?php esc_html_e('Only used when Menu Display Mode (Settings) is Inline. Full Page covers the screen; Full Width shows the menu below the buttons.', 'maca-restu-pro'); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="qr_paper_size"><?php esc_html_e('Paper Size', 'maca-restu-pro'); ?></label>
                            </th>
                            <td>
                                <select id="qr_paper_size" name="qr_paper_size" class="regular-text">
                                    <option value="a4" <?php selected($qr_paper_size, 'a4'); ?>><?php esc_html_e('A4', 'maca-restu-pro'); ?></option>
                                    <option value="a5" <?php selected($qr_paper_size, 'a5'); ?>><?php esc_html_e('A5', 'maca-restu-pro'); ?></option>
                                </select>
                                <p class="description"><?php esc_html_e('Paper size for QR code print.', 'maca-restu-pro'); ?></p>
                            </td>
                        </tr>
                        <?php if (maca_menulist_table_order_enabled()) : ?>
                        <tr>
                            <th scope="row">
                                <label for="qr_table_number"><?php esc_html_e('Table number', 'maca-restu-pro'); ?></label>
                            </th>
                            <td>
                                <input type="text" id="qr_table_number" name="qr_table_number" value="" class="small-text" inputmode="numeric" placeholder="<?php esc_attr_e('e.g. 4', 'maca-restu-pro'); ?>">
                                <p class="description"><?php esc_html_e('Optional. The QR code links to the menu with this table number pre-filled when guests order. Print one QR code per table.', 'maca-restu-pro'); ?></p>
                            </td>
                        </tr>
                        <?php endif; ?>
                    </table>
                    
                    <?php submit_button(__('Generate QR Code', 'maca-restu-pro')); ?>
                </form>
                
                <?php if (!empty($qr_category) || !empty($categories)): ?>
                    <div class="maca-qr-preview" style="margin-top: 30px; padding: 20px; border: 1px solid #ccc; background: #f9f9f9;">
                        <h2><?php esc_html_e('QR Code Preview', 'maca-restu-pro'); ?></h2>
                        <div id="maca-qr-code-container" style="text-align: center; padding: 20px; background: white; max-width: 400px; margin: 0 auto;">
                            <div id="maca-qr-logo-preview" style="margin-bottom: 20px;<?php echo ($qr_print_show_logo && $qr_logo !== '') ? '' : ' display:none;'; ?>">
                                <?php if ($qr_logo !== '') : ?>
                                    <img src="<?php echo esc_url($qr_logo); ?>" alt="<?php esc_attr_e('Logo', 'maca-restu-pro'); ?>" style="max-width: 150px; max-height: 150px;">
                                <?php endif; ?>
                            </div>
                            <h3 id="maca-qr-title-preview" style="margin: 10px 0;"><?php echo esc_html($qr_title); ?></h3>
                            <p id="maca-qr-table-preview" class="description" style="display:none; margin: 0 0 10px; font-size: 18px; font-weight: 700; color: #0073aa;"></p>
                            <div id="maca-qr-code" style="margin: 20px 0;">
                                <img src="https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=<?php echo urlencode($qr_url); ?>" alt="QR Code">
                            </div>
                            <p id="maca-qr-subtitle-preview" style="margin: 10px 0; color: #666;"><?php echo esc_html($qr_subtitle); ?></p>
                        </div>
                        <p style="text-align: center; margin-top: 20px;">
                            <a href="<?php echo esc_url($qr_print_url); ?>" id="maca-qr-print-link" class="button button-primary"><?php esc_html_e('Open Print Page', 'maca-restu-pro'); ?></a>
                            <a href="<?php echo esc_url($qr_url); ?>" id="maca-qr-preview-menu-link" target="_blank" class="button" style="margin-left: 10px;"><?php esc_html_e('Preview Menu Page', 'maca-restu-pro'); ?></a>
                        </p>
                    </div>
                <?php endif; ?>

                <?php if ($takeaway_ordering && $takeaway_url !== '') : ?>
                    <div class="maca-qr-preview" style="margin-top: 30px; padding: 20px; border: 1px solid #c3c4c7; background: #f0f6fc;">
                        <h2><?php esc_html_e('Takeaway menu QR', 'maca-restu-pro'); ?></h2>
                        <p><?php esc_html_e('Use this QR or link on your website for takeaway ordering (no table number).', 'maca-restu-pro'); ?></p>
                        <p><a href="<?php echo esc_url($takeaway_url); ?>" target="_blank" rel="noopener"><?php echo esc_html($takeaway_url); ?></a></p>
                        <p style="text-align: center;">
                            <img src="https://api.qrserver.com/v1/create-qr-code/?size=200x200&amp;data=<?php echo esc_attr(rawurlencode($takeaway_url)); ?>" alt="<?php esc_attr_e('Takeaway menu QR code', 'maca-restu-pro'); ?>">
                        </p>
                        <p class="description"><?php esc_html_e('Shortcode for a WordPress page: [maca_takeaway_menu]', 'maca-restu-pro'); ?></p>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        
        <script>
            jQuery(document).ready(function($) {
                var qrBaseUrl = <?php echo wp_json_encode($qr_url); ?>;
                var qrPrintBaseUrl = <?php echo wp_json_encode($qr_print_url); ?>;
                var tableOrderEnabled = <?php echo $table_order_enabled ? 'true' : 'false'; ?>;
                var tableLabel = <?php
                echo wp_json_encode(
                    /* translators: %s: table number */
                    __('Table %s', 'maca-restu-pro')
                );
                ?>;

                function buildQrUrl(tableNumber) {
                    if (!tableNumber) {
                        return qrBaseUrl;
                    }
                    var separator = qrBaseUrl.indexOf('?') >= 0 ? '&' : '?';
                    return qrBaseUrl + separator + 'bord=' + encodeURIComponent(tableNumber);
                }

                function updateQrTableLinks() {
                    if (!tableOrderEnabled) {
                        return;
                    }

                    var tableNumber = ($('#qr_table_number').val() || '').trim();
                    var url = buildQrUrl(tableNumber);
                    var printUrl = qrPrintBaseUrl;

                    $('#maca-qr-code img').attr(
                        'src',
                        'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=' + encodeURIComponent(url)
                    );
                    $('#maca-qr-preview-menu-link').attr('href', url);

                    if (tableNumber) {
                        printUrl += (printUrl.indexOf('?') >= 0 ? '&' : '?') + 'bord=' + encodeURIComponent(tableNumber);
                        $('#maca-qr-table-preview').text(tableLabel.replace('%s', tableNumber)).show();
                    } else {
                        $('#maca-qr-table-preview').hide().text('');
                    }

                    $('#maca-qr-print-link').attr('href', printUrl);
                }

                $('#qr_table_number').on('input change', updateQrTableLinks);

                function syncQrLogoPreview() {
                    var logoUrl = ($('#qr_logo').val() || '').trim();
                    var showPrintLogo = $('#qr_print_show_logo').is(':checked');
                    var $preview = $('#maca-qr-logo-preview');

                    if (!showPrintLogo || logoUrl === '') {
                        $preview.hide();
                        return;
                    }

                    $preview.show();
                    if ($preview.find('img').length) {
                        $preview.find('img').attr('src', logoUrl);
                    } else {
                        $preview.html(
                            $('<img>', {
                                src: logoUrl,
                                alt: <?php echo wp_json_encode(__('Logo', 'maca-restu-pro')); ?>,
                                css: { maxWidth: '150px', maxHeight: '150px' }
                            })
                        );
                    }
                }

                $('#qr_menu_show_logo, #qr_print_show_logo').on('change', syncQrLogoPreview);
                $('#qr_logo').on('change input', syncQrLogoPreview);
                syncQrLogoPreview();

                $('#upload_qr_logo').on('click', function(e) {
                    e.preventDefault();
                    
                    var mediaUploader = wp.media({
                        title: '<?php esc_html_e('Select Logo', 'maca-restu-pro'); ?>',
                        button: {
                            text: '<?php esc_html_e('Use This Image', 'maca-restu-pro'); ?>'
                        },
                        multiple: false
                    });
                    
                    mediaUploader.on('select', function() {
                        var attachment = mediaUploader.state().get('selection').first().toJSON();
                        $('#qr_logo').val(attachment.url);
                        syncQrLogoPreview();
                        $('.image-preview').html('<img src="' + attachment.url + '" alt="<?php esc_html_e('Logo', 'maca-restu-pro'); ?>" style="max-width: 100px; margin-top: 10px;">');
                    });
                    
                    mediaUploader.open();
                });
            });
        </script>
        <?php
    }
}
