<?php
/**
 * Admin UI for dish categories and dishes.
 *
 * @package Maca_Menu_List
 */

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

require_once MACA_MENULIST_PLUGIN_DIR . 'includes/admin-dish-list-filters.php';

class Maca_Menu_List_Admin_Dishes {

    /**
     * Constructor.
     */
    public function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'), 20);
        add_action('admin_init', array($this, 'handle_form_submission'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
        add_action('wp_ajax_maca_reorder_dishes', array($this, 'ajax_reorder_dishes'));
        add_action('wp_ajax_maca_reorder_dish_categories', array($this, 'ajax_reorder_dish_categories'));

        require_once MACA_MENULIST_PLUGIN_DIR . 'includes/admin-table-orders.php';
        new Maca_MenuList_Admin_Table_Orders();

        require_once MACA_MENULIST_PLUGIN_DIR . 'includes/admin-dish-stats.php';
        new Maca_MenuList_Admin_Dish_Stats();

        require_once MACA_MENULIST_PLUGIN_DIR . 'includes/admin-campaigns.php';
        new Maca_MenuList_Admin_Campaigns();

        if (!function_exists('maca_menulist_pdf_parse_menu_text')) {
            require_once MACA_MENULIST_PLUGIN_DIR . 'includes/dish-pdf-import.php';
        }

        require_once MACA_MENULIST_PLUGIN_DIR . 'includes/admin-dish-pdf-import.php';
        new Maca_MenuList_Admin_Dish_Pdf_Import();

        require_once MACA_MENULIST_PLUGIN_DIR . 'includes/admin-dish-csv.php';
        new Maca_MenuList_Admin_Dish_Csv();
    }

    /**
     * Register dish admin pages when in dishes mode.
     */
    public function add_admin_menu() {
        if (!maca_menulist_is_dishes_mode()) {
            return;
        }

        add_submenu_page(
            'maca-restu',
            __('Menykategorier', 'maca-restu-pro'),
            __('Menykategorier', 'maca-restu-pro'),
            maca_menulist_admin_required_cap(),
            'maca-restu-dish-categories',
            array($this, 'render_dish_categories_page')
        );

        add_submenu_page(
            'maca-restu',
            __('Rätter', 'maca-restu-pro'),
            __('Rätter', 'maca-restu-pro'),
            maca_menulist_admin_required_cap(),
            'maca-restu-dishes',
            array($this, 'render_dishes_page')
        );

        add_submenu_page(
            'maca-restu',
            __('Allergener', 'maca-restu-pro'),
            __('Allergener', 'maca-restu-pro'),
            maca_menulist_admin_required_cap(),
            'maca-restu-allergens',
            array($this, 'render_allergens_page')
        );
    }

    /**
     * Enqueue scripts for dish reorder screen.
     *
     * @param string $hook Admin page hook suffix.
     */
    public function enqueue_admin_scripts($hook) {
        // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only view switch.
        $action = isset($_GET['action']) ? sanitize_text_field(wp_unslash($_GET['action'])) : 'list';
        // phpcs:enable WordPress.Security.NonceVerification.Recommended

        $enqueue_sortable = false;
        $localize = array();

        if ($hook === 'maca-restu_page_maca-restu-dishes' && $action === 'sort') {
            $enqueue_sortable = true;
            $localize['macaMenulistDishSort'] = array(
                'ajaxUrl' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('maca_reorder_dishes'),
                'saved' => __('Ordning sparad.', 'maca-restu-pro'),
                'error' => __('Kunde inte spara ordningen. Försök igen.', 'maca-restu-pro'),
            );
        }

        if ($hook === 'maca-restu_page_maca-restu-dish-categories' && $action === 'list') {
            $enqueue_sortable = true;
            $localize['macaMenulistDishCategorySort'] = array(
                'ajaxUrl' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('maca_reorder_dish_categories'),
                'saved' => __('Ordning sparad.', 'maca-restu-pro'),
                'error' => __('Kunde inte spara ordningen. Försök igen.', 'maca-restu-pro'),
            );
        }

        if ($hook === 'maca-restu_page_maca-restu-dishes' && $action === 'list') {
            wp_enqueue_script(
                'maca-menulist-admin-dish-list-search',
                MACA_MENULIST_PLUGIN_URL . 'assets/js/admin-dish-list-search.js',
                array('jquery'),
                MACA_MENULIST_VERSION,
                true
            );
            wp_localize_script(
                'maca-menulist-admin-dish-list-search',
                'macaMenulistDishListSearch',
                array(
                    'noResults' => __('No dishes match your search.', 'maca-restu-pro'),
                    /* translators: 1: visible dish count, 2: total dish count */
                    'countLabel' => __('Showing %1$d of %2$d dishes', 'maca-restu-pro'),
                )
            );
        }

        if (!$enqueue_sortable) {
            return;
        }

        wp_enqueue_script('jquery-ui-sortable');
        wp_enqueue_script(
            'maca-menulist-admin-dish-sort',
            MACA_MENULIST_PLUGIN_URL . 'assets/js/admin-dish-sort.js',
            array('jquery', 'jquery-ui-sortable'),
            MACA_MENULIST_VERSION,
            true
        );

        foreach ($localize as $object_name => $data) {
            wp_localize_script('maca-menulist-admin-dish-sort', $object_name, $data);
        }
    }

    /**
     * AJAX: save dish sort order within a category.
     */
    public function ajax_reorder_dishes() {
        check_ajax_referer('maca_reorder_dishes', 'nonce');

        if (!maca_menulist_user_can_manage_plugin() || !maca_menulist_pro_has_feature('dishes')) {
            wp_send_json_error(array('message' => 'forbidden'), 403);
        }

        // phpcs:disable WordPress.Security.NonceVerification.Missing -- Verified above.
        $category_id = isset($_POST['category_id']) ? intval(wp_unslash($_POST['category_id'])) : 0;
        $dish_ids_raw = isset($_POST['dish_ids']) ? wp_unslash($_POST['dish_ids']) : '';
        // phpcs:enable WordPress.Security.NonceVerification.Missing

        $dish_ids = json_decode(is_string($dish_ids_raw) ? $dish_ids_raw : '', true);
        if (!is_array($dish_ids)) {
            wp_send_json_error(array('message' => 'invalid'));
        }

        if (!maca_menulist_db_update_dishes_sort_order($category_id, $dish_ids)) {
            wp_send_json_error(array('message' => 'update_failed'));
        }

        do_action('maca_menulist_site_chat_content_changed');

        wp_send_json_success();
    }

    /**
     * AJAX: save dish category sort order.
     */
    public function ajax_reorder_dish_categories() {
        check_ajax_referer('maca_reorder_dish_categories', 'nonce');

        if (!maca_menulist_user_can_manage_plugin() || !maca_menulist_pro_has_feature('dishes')) {
            wp_send_json_error(array('message' => 'forbidden'), 403);
        }

        // phpcs:disable WordPress.Security.NonceVerification.Missing -- Verified above.
        $category_ids_raw = isset($_POST['category_ids']) ? wp_unslash($_POST['category_ids']) : '';
        // phpcs:enable WordPress.Security.NonceVerification.Missing

        $category_ids = json_decode(is_string($category_ids_raw) ? $category_ids_raw : '', true);
        if (!is_array($category_ids)) {
            wp_send_json_error(array('message' => 'invalid'));
        }

        if (!maca_menulist_db_update_dish_categories_sort_order($category_ids)) {
            wp_send_json_error(array('message' => 'update_failed'));
        }

        do_action('maca_menulist_site_chat_content_changed');

        wp_send_json_success();
    }

    /**
     * Handle dish form submissions.
     */
    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;
        }

        $type = isset($_POST['maca_type']) ? sanitize_text_field(wp_unslash($_POST['maca_type'])) : '';

        if ($type !== 'dish_category' && $type !== 'dish' && $type !== 'allergen') {
            return;
        }

        if (!maca_menulist_pro_has_feature('dishes')) {
            return;
        }

        $action = sanitize_text_field(wp_unslash($_POST['maca_action']));

        if ($type === 'dish_category') {
            if ($action === 'add' || $action === 'edit') {
                $this->save_dish_category();
            } elseif ($action === 'delete') {
                $this->delete_dish_category();
            }
        } elseif ($type === 'dish') {
            if ($action === 'add' || $action === 'edit') {
                $this->save_dish();
            } elseif ($action === 'delete') {
                $this->delete_dish();
            }
        } elseif ($type === 'allergen') {
            if ($action === 'add' || $action === 'edit') {
                $this->save_allergen();
            } elseif ($action === 'delete') {
                $this->delete_allergen();
            } elseif ($action === 'restore_defaults') {
                $this->restore_default_allergens();
            }
        }
    }

    /**
     * Save dish category.
     */
    private function save_dish_category() {
        // phpcs:disable WordPress.Security.NonceVerification.Missing
        $name = sanitize_text_field(wp_unslash($_POST['dish_category_name'] ?? ''));
        $name_en = sanitize_text_field(wp_unslash($_POST['dish_category_name_en'] ?? ''));
        $sort_order = isset($_POST['sort_order']) ? intval(wp_unslash($_POST['sort_order'])) : 0;
        $is_active = isset($_POST['dish_category_is_active']) ? 1 : 0;
        $category_id = isset($_POST['dish_category_id']) ? intval(wp_unslash($_POST['dish_category_id'])) : 0;
        $schedule = maca_menulist_parse_schedule_from_request();
        // phpcs:enable WordPress.Security.NonceVerification.Missing

        if (maca_menulist_admin_content_field_missing($name, $name_en)) {
            add_settings_error(
                'maca_dish_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,
            'sort_order' => $sort_order,
            'is_active' => $is_active,
            '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'],
        );

        if ($category_id > 0) {
            $result = maca_menulist_db_update_dish_category($category_id, $row);
        } else {
            $result = maca_menulist_db_insert_dish_category($row);
        }

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

        add_settings_error('maca_dish_category', 'success', __('Dish category saved successfully.', 'maca-restu-pro'), 'updated');
        do_action('maca_menulist_site_chat_content_changed');
    }

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

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

        maca_menulist_db_delete_dish_category($category_id);
        add_settings_error('maca_dish_category', 'success', __('Dish category deleted.', 'maca-restu-pro'), 'updated');
        do_action('maca_menulist_site_chat_content_changed');
    }

    /**
     * Save dish.
     */
    private function save_dish() {
        // phpcs:disable WordPress.Security.NonceVerification.Missing
        $title = sanitize_text_field(wp_unslash($_POST['dish_title'] ?? ''));
        $title_en = sanitize_text_field(wp_unslash($_POST['dish_title_en'] ?? ''));
        $description = sanitize_textarea_field(wp_unslash($_POST['dish_description'] ?? ''));
        $description_en = sanitize_textarea_field(wp_unslash($_POST['dish_description_en'] ?? ''));
        $category_id = isset($_POST['dish_category_id']) ? intval(wp_unslash($_POST['dish_category_id'])) : 0;
        $price_raw = isset($_POST['dish_price']) ? wp_unslash($_POST['dish_price']) : '';
        $price_raw = is_string($price_raw) ? str_replace(',', '.', trim($price_raw)) : '';
        $price = ($price_raw !== '') ? floatval($price_raw) : null;
        $price_takeaway_raw = isset($_POST['dish_price_takeaway']) ? wp_unslash($_POST['dish_price_takeaway']) : '';
        $price_takeaway_raw = is_string($price_takeaway_raw) ? str_replace(',', '.', trim($price_takeaway_raw)) : '';
        $price_takeaway = ($price_takeaway_raw !== '') ? floatval($price_takeaway_raw) : null;
        $takeaway_active = isset($_POST['dish_takeaway_active']) ? 1 : 0;
        $image_url = maca_menulist_normalize_url(esc_url_raw(wp_unslash($_POST['dish_image_url'] ?? '')));
        $is_active = isset($_POST['dish_is_active']) ? 1 : 0;
        $dish_id = isset($_POST['dish_id']) ? intval(wp_unslash($_POST['dish_id'])) : 0;
        $allergen_ids = isset($_POST['dish_allergens']) ? array_map('intval', (array) wp_unslash($_POST['dish_allergens'])) : array();
        $campaign_ids = isset($_POST['dish_campaigns']) ? array_map('intval', (array) wp_unslash($_POST['dish_campaigns'])) : array();
        $vat_code = isset($_POST['dish_vat_code']) ? maca_menulist_sanitize_dish_vat_code(wp_unslash($_POST['dish_vat_code'])) : 'food';
        // phpcs:enable WordPress.Security.NonceVerification.Missing

        if (maca_menulist_admin_content_field_missing($title, $title_en)) {
            add_settings_error(
                'maca_dish',
                'error',
                maca_menulist_admin_show_local_content_fields()
                    ? __('Dish title is required in English or your local language.', 'maca-restu-pro')
                    : __('Dish title is required.', 'maca-restu-pro')
            );
            return;
        }

        if ($category_id <= 0) {
            add_settings_error('maca_dish', 'error', __('Välj en rättkategori.', 'maca-restu-pro'));
            return;
        }

        if ($dish_id > 0) {
            $existing = maca_menulist_db_get_dish($dish_id);
            $sort_order = $existing ? (int) $existing->sort_order : 0;
        } else {
            global $wpdb;
            $dishes_table = maca_menulist_db_dishes_table();
            $max_sort = $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT MAX(sort_order) FROM $dishes_table WHERE category_id = %d",
                    $category_id
                )
            );
            $sort_order = ($max_sort !== null && $max_sort !== '') ? ((int) $max_sort + 1) : 0;
        }

        $row = array(
            'category_id' => $category_id,
            'title' => $title,
            'title_en' => $title_en,
            'description' => $description,
            'description_en' => $description_en,
            'price' => $price,
            'price_takeaway' => $price_takeaway,
            'takeaway_active' => $takeaway_active,
            'vat_code' => $vat_code,
            'image_url' => $image_url !== '' ? $image_url : null,
            'sort_order' => $sort_order,
            'is_active' => $is_active,
        );

        if ($dish_id > 0) {
            $result = maca_menulist_db_update_dish($dish_id, $row);
            $saved_dish_id = $dish_id;
        } else {
            $result = maca_menulist_db_insert_dish($row);
            global $wpdb;
            $saved_dish_id = (int) $wpdb->insert_id;
        }

        if ($result === false) {
            add_settings_error('maca_dish', 'error', __('Kunde inte spara rätten.', 'maca-restu-pro'));
            return;
        }

        if ($saved_dish_id > 0) {
            maca_menulist_db_set_dish_allergens($saved_dish_id, $allergen_ids);
            maca_menulist_db_set_dish_campaigns($saved_dish_id, $campaign_ids);
        }

        add_settings_error('maca_dish', 'success', __('Rätten sparades.', 'maca-restu-pro'), 'updated');
        do_action('maca_menulist_site_chat_content_changed');
    }

    /**
     * Save allergen.
     */
    private function save_allergen() {
        // phpcs:disable WordPress.Security.NonceVerification.Missing
        $name = sanitize_text_field(wp_unslash($_POST['allergen_name'] ?? ''));
        $name_en = sanitize_text_field(wp_unslash($_POST['allergen_name_en'] ?? ''));
        $sort_order = isset($_POST['sort_order']) ? intval(wp_unslash($_POST['sort_order'])) : 0;
        $allergen_id = isset($_POST['allergen_id']) ? intval(wp_unslash($_POST['allergen_id'])) : 0;
        // phpcs:enable WordPress.Security.NonceVerification.Missing

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

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

        if ($allergen_id > 0) {
            $result = maca_menulist_db_update_allergen($allergen_id, $row);
        } else {
            $result = maca_menulist_db_insert_allergen($row);
        }

        if ($result === false) {
            add_settings_error('maca_allergen', 'error', __('Error saving allergen.', 'maca-restu-pro'));
            return;
        }

        add_settings_error('maca_allergen', 'success', __('Allergen saved successfully.', 'maca-restu-pro'), 'updated');
        do_action('maca_menulist_site_chat_content_changed');
    }

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

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

        maca_menulist_db_delete_allergen($allergen_id);
        add_settings_error('maca_allergen', 'success', __('Allergen deleted.', 'maca-restu-pro'), 'updated');
        do_action('maca_menulist_site_chat_content_changed');
    }

    /**
     * Restore EU default allergens (upsert; keeps custom allergens).
     */
    private function restore_default_allergens() {
        $result = maca_menulist_db_restore_default_allergens();

        add_settings_error(
            'maca_allergen',
            'success',
            sprintf(
                /* translators: 1: number of updated defaults, 2: number of added defaults */
                __('Default allergens restored. %1$d updated, %2$d added. Custom allergens were kept.', 'maca-restu-pro'),
                (int) $result['updated'],
                (int) $result['added']
            ),
            'updated'
        );
    }

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

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

        maca_menulist_db_delete_dish($dish_id);
        add_settings_error('maca_dish', 'success', __('Rätten raderades.', 'maca-restu-pro'), 'updated');
        do_action('maca_menulist_site_chat_content_changed');
    }

    /**
     * Render dish categories page.
     */
    public function render_dish_categories_page() {
        if (!maca_menulist_pro_has_feature('dishes')) {
            ?>
            <div class="wrap">
                <h1><?php esc_html_e('Menykategorier', 'maca-restu-pro'); ?></h1>
                <?php echo wp_kses_post(maca_menulist_pro_locked_notice('dishes')); ?>
            </div>
            <?php
            return;
        }

        // phpcs:disable WordPress.Security.NonceVerification.Recommended
        $action = isset($_GET['action']) ? sanitize_text_field(wp_unslash($_GET['action'])) : 'list';
        $category_id = isset($_GET['dish_category_id']) ? intval($_GET['dish_category_id']) : 0;
        // phpcs:enable WordPress.Security.NonceVerification.Recommended

        ?>
        <div class="wrap">
            <h1><?php esc_html_e('Menykategorier', 'maca-restu-pro'); ?></h1>
            <p class="description"><?php esc_html_e('Create categories for your dishes, such as appetizer, lunch, dinner, dessert, or drinks. Set optional QR schedule per category. Drag categories on the list to set menu order; order is saved automatically.', 'maca-restu-pro'); ?></p>

            <?php settings_errors('maca_dish_category'); ?>

            <?php if ($action === 'add' || $action === 'edit') : ?>
                <?php $this->render_dish_category_form($action, $category_id); ?>
            <?php else : ?>
                <?php $this->render_dish_categories_list(); ?>
            <?php endif; ?>
        </div>
        <?php
    }

    /**
     * Render dish category form.
     *
     * @param string $action Action type.
     * @param int    $category_id Category ID.
     */
    private function render_dish_category_form($action, $category_id) {
        $category = null;
        if ($action === 'edit' && $category_id > 0) {
            $category = maca_menulist_db_get_dish_category($category_id);
        }

        $name = $category ? $category->name : '';
        $name_en = ($category && isset($category->name_en)) ? $category->name_en : '';
        $sort_order = $category ? $category->sort_order : 0;
        $is_active = $category ? (int) ($category->is_active ?? 1) : 1;
        $start_date = $category ? maca_menulist_format_datetime_local_value($category->start_date) : '';
        $end_date = $category ? maca_menulist_format_datetime_local_value($category->end_date) : '';
        $time_start = ($category && !empty($category->time_start)) ? substr($category->time_start, 0, 5) : '';
        $time_end = ($category && !empty($category->time_end)) ? substr($category->time_end, 0, 5) : '';
        $selected_days = $category ? maca_menulist_parse_days_of_week($category->days_of_week ?? '') : array();
        $weekday_labels = maca_menulist_weekday_labels_ordered();

        ?>
        <h2><?php echo esc_html($action === 'add' ? __('Add Dish Category', 'maca-restu-pro') : __('Edit Dish Category', 'maca-restu-pro')); ?></h2>
        <?php
        $dish_category_nav = array(
            'action' => $action,
            'current_id' => $category_id,
            'records' => maca_menulist_db_get_dish_categories(),
            'list_url' => admin_url('admin.php?page=maca-restu-dish-categories'),
            'edit_page' => 'maca-restu-dish-categories',
            'edit_id_param' => 'dish_category_id',
        );
        maca_menulist_render_admin_record_navigation($dish_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="dish_category">
            <input type="hidden" name="dish_category_id" value="<?php echo esc_attr($category_id); ?>">

            <table class="form-table">
                <tr>
                    <th scope="row">
                        <label for="dish_category_name"><?php echo esc_html(maca_menulist_admin_primary_field_label(__('Category Name', 'maca-restu-pro'))); ?></label>
                    </th>
                    <td>
                        <input type="text" id="dish_category_name" name="dish_category_name" value="<?php echo esc_attr($name); ?>" class="regular-text">
                        <?php if (!maca_menulist_admin_show_local_content_fields()) : ?>
                            <p class="description"><?php esc_html_e('E.g. Appetizer, Main course, Dessert, Drinks', 'maca-restu-pro'); ?></p>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php if (maca_menulist_admin_show_local_content_fields()) : ?>
                <tr>
                    <th scope="row">
                        <label for="dish_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="dish_category_name_en" name="dish_category_name_en" value="<?php echo esc_attr($name_en); ?>" class="regular-text">
                        <p class="description"><?php esc_html_e('E.g. Appetizer, Main course, Dessert, Drinks', '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 on the menu. You can also drag categories on the list to reorder.', 'maca-restu-pro'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="dish_category_is_active"><?php esc_html_e('Aktiv', 'maca-restu-pro'); ?></label>
                    </th>
                    <td>
                        <input type="checkbox" id="dish_category_is_active" name="dish_category_is_active" value="1" <?php checked($is_active, 1); ?>>
                        <label for="dish_category_is_active"><?php esc_html_e('Show this category on the menu', 'maca-restu-pro'); ?></label>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label><?php esc_html_e('Schedule (QR menu)', 'maca-restu-pro'); ?></label>
                    </th>
                    <td>
                        <p class="description" style="margin-top:0;">
                            <?php esc_html_e('Optional. Limits when this category and its dishes appear on the QR menu (/qrmeny/). The website menu and shortcode follow start and end dates only (weekdays and daily times are ignored).', 'maca-restu-pro'); ?>
                        </p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="dish_category_start_date"><?php esc_html_e('Start Date', 'maca-restu-pro'); ?></label>
                    </th>
                    <td>
                        <input type="datetime-local" id="dish_category_start_date" name="start_date" value="<?php echo esc_attr($start_date); ?>">
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="dish_category_end_date"><?php esc_html_e('End Date', 'maca-restu-pro'); ?></label>
                    </th>
                    <td>
                        <input type="datetime-local" id="dish_category_end_date" name="end_date" value="<?php echo esc_attr($end_date); ?>">
                    </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 for every day. Example: lunch category Monday–Friday only.', 'maca-restu-pro'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="dish_category_time_start"><?php esc_html_e('Daily start time', 'maca-restu-pro'); ?></label>
                    </th>
                    <td>
                        <input type="time" id="dish_category_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. Leave empty for all day.', 'maca-restu-pro'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="dish_category_time_end"><?php esc_html_e('Daily end time', 'maca-restu-pro'); ?></label>
                    </th>
                    <td>
                        <input type="time" id="dish_category_time_end" name="time_end" value="<?php echo esc_attr($time_end); ?>">
                        <p class="description"><?php esc_html_e('Optional: e.g. 14:00. Overnight ranges like 22:00–02:00 are supported.', '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($dish_category_nav, array('modifier' => 'bottom'))); ?>
        </form>
        <?php
    }

    /**
     * Render dish categories list.
     */
    private function render_dish_categories_list() {
        $categories = maca_menulist_db_get_dish_categories();

        ?>
        <style>
            .maca-dish-category-sort-list.is-saving {
                opacity: 0.65;
                pointer-events: none;
            }
            .maca-dish-category-sort-list tr.ui-sortable-helper {
                box-shadow: 0 4px 14px rgba(0, 0, 0, 0.12);
                background: #fff;
            }
            .maca-dish-category-sort-handle {
                width: 28px;
                color: #787c82;
                font-size: 18px;
                line-height: 1;
                cursor: grab;
                user-select: none;
                text-align: center;
            }
            .maca-dish-category-sort-handle:active {
                cursor: grabbing;
            }
            .maca-dish-category-sort-notice {
                max-width: 720px;
                margin: 0 0 16px;
            }
            .maca-dish-category-sort-list tr.maca-dish-category-inactive td {
                color: #646970;
            }
            .maca-dish-category-inactive-label {
                color: #b32d2e;
                font-weight: 600;
            }
        </style>

        <p>
            <a href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-dish-categories&action=add')); ?>" class="button button-primary">
                <?php esc_html_e('Lägg till rättkategori', 'maca-restu-pro'); ?>
            </a>
        </p>

        <?php if (empty($categories)) : ?>
            <p><?php esc_html_e('Inga rättkategorier hittades. Lägg till din första kategori ovan.', 'maca-restu-pro'); ?></p>
        <?php else : ?>
            <p class="description"><?php esc_html_e('Drag categories up or down to change their order on the menu and QR page.', 'maca-restu-pro'); ?></p>

            <div class="notice notice-success maca-dish-category-sort-notice" style="display:none;">
                <p></p>
            </div>

            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th class="column-sort" style="width:36px;" aria-hidden="true"></th>
                        <th><?php esc_html_e('Namn', 'maca-restu-pro'); ?></th>
                        <th><?php esc_html_e('Aktiv', 'maca-restu-pro'); ?></th>
                        <th><?php esc_html_e('Schedule (QR)', 'maca-restu-pro'); ?></th>
                        <th><?php esc_html_e('QR status', 'maca-restu-pro'); ?></th>
                        <th><?php esc_html_e('Åtgärder', 'maca-restu-pro'); ?></th>
                    </tr>
                </thead>
                <tbody class="maca-dish-category-sort-list">
                    <?php foreach ($categories as $category) : ?>
                        <tr data-category-id="<?php echo esc_attr($category->id); ?>"<?php echo maca_menulist_dish_category_is_active($category) ? '' : ' class="maca-dish-category-inactive"'; ?>>
                            <td>
                                <span class="maca-dish-category-sort-handle" aria-hidden="true" title="<?php esc_attr_e('Drag to reorder', 'maca-restu-pro'); ?>">&#9776;</span>
                            </td>
                            <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 (maca_menulist_dish_category_is_active($category)) {
                                    esc_html_e('Ja', 'maca-restu-pro');
                                } else {
                                    echo '<span class="maca-dish-category-inactive-label">' . esc_html__('Nej', 'maca-restu-pro') . '</span>';
                                }
                                ?>
                            </td>
                            <td><small><?php echo esc_html(maca_menulist_format_schedule_summary($category)); ?></small></td>
                            <td>
                                <?php
                                $status = maca_menulist_get_dish_category_status($category);
                                $status_labels = array(
                                    'active' => __('Aktiv nu', 'maca-restu-pro'),
                                    'inactive' => __('Inaktiv', 'maca-restu-pro'),
                                    'scheduled' => __('Schemalagd', 'maca-restu-pro'),
                                    'expired' => __('Utgången', 'maca-restu-pro'),
                                    'outside_hours' => __('Utanför tid', 'maca-restu-pro'),
                                );
                                echo esc_html(isset($status_labels[$status]) ? $status_labels[$status] : $status);
                                ?>
                            </td>
                            <td>
                                <a href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-dish-categories&action=edit&dish_category_id=' . $category->id)); ?>" class="button button-small">
                                    <?php esc_html_e('Redigera', '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="dish_category">
                                    <input type="hidden" name="dish_category_id" value="<?php echo esc_attr($category->id); ?>">
                                    <button type="submit" class="button button-small" onclick="return confirm('<?php echo esc_js(__('Are you sure? All dishes in this category will also be deleted.', 'maca-restu-pro')); ?>');">
                                        <?php esc_html_e('Radera', 'maca-restu-pro'); ?>
                                    </button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
        <?php
    }

    /**
     * Render dishes page.
     */
    public function render_dishes_page() {
        if (!maca_menulist_pro_has_feature('dishes')) {
            ?>
            <div class="wrap">
                <h1><?php esc_html_e('Rätter', 'maca-restu-pro'); ?></h1>
                <?php echo wp_kses_post(maca_menulist_pro_locked_notice('dishes')); ?>
            </div>
            <?php
            return;
        }

        // phpcs:disable WordPress.Security.NonceVerification.Recommended
        $action = isset($_GET['action']) ? sanitize_text_field(wp_unslash($_GET['action'])) : 'list';
        $dish_id = isset($_GET['dish_id']) ? intval($_GET['dish_id']) : 0;
        // phpcs:enable WordPress.Security.NonceVerification.Recommended

        ?>
        <div class="wrap">
            <h1><?php esc_html_e('Rätter', 'maca-restu-pro'); ?></h1>
            <p class="description"><?php esc_html_e('Lägg till rätter med titel, beskrivning, pris och valfri bild. Varje rätt tillhör en rättkategori.', 'maca-restu-pro'); ?></p>

            <?php maca_menulist_render_admin_vat_settings_summary(); ?>

            <?php settings_errors('maca_dish'); ?>

            <?php if ($action === 'add' || $action === 'edit') : ?>
                <?php $this->render_dish_form($action, $dish_id); ?>
            <?php elseif ($action === 'sort') : ?>
                <?php $this->render_dishes_sort(); ?>
            <?php else : ?>
                <?php $this->render_dishes_list(); ?>
            <?php endif; ?>
        </div>
        <?php
    }

    /**
     * Render dish form.
     *
     * @param string $action Action type.
     * @param int    $dish_id Dish ID.
     */
    private function render_dish_form($action, $dish_id) {
        $dish = null;
        if ($action === 'edit' && $dish_id > 0) {
            $dish = maca_menulist_db_get_dish($dish_id);
        }

        $category_id = $dish ? $dish->category_id : 0;
        $title = $dish ? $dish->title : '';
        $title_en = ($dish && isset($dish->title_en)) ? $dish->title_en : '';
        $description = $dish ? $dish->description : '';
        $description_en = ($dish && isset($dish->description_en)) ? $dish->description_en : '';
        $price = ($dish && $dish->price !== null && $dish->price !== '') ? $dish->price : '';
        $price_takeaway = ($dish && isset($dish->price_takeaway) && $dish->price_takeaway !== null && $dish->price_takeaway !== '') ? $dish->price_takeaway : '';
        $takeaway_active = $dish ? (int) ($dish->takeaway_active ?? 1) : 1;
        $image_url = $dish ? $dish->image_url : '';
        $is_active = $dish ? (int) $dish->is_active : 1;
        $categories = maca_menulist_db_get_dish_categories();
        $allergens = maca_menulist_db_get_allergens();
        $campaigns = maca_menulist_db_get_campaigns();
        $selected_allergen_ids = ($dish_id > 0) ? maca_menulist_db_get_dish_allergen_ids($dish_id) : array();
        $selected_campaign_ids = ($dish_id > 0) ? maca_menulist_db_get_dish_campaign_ids($dish_id) : array();
        $vat_code = ($dish && !empty($dish->vat_code)) ? maca_menulist_sanitize_dish_vat_code($dish->vat_code) : 'food';
        $vat_code_options = maca_menulist_get_dish_vat_code_options();
        $currency = maca_menulist_get_price_currency();

        ?>
        <h2><?php echo esc_html($action === 'add' ? __('Add Dish', 'maca-restu-pro') : __('Edit Dish', 'maca-restu-pro')); ?></h2>
        <?php
        $list_issue = $this->get_dishes_list_issue_filter();
        $dish_nav = array(
            'action' => $action,
            'current_id' => $dish_id,
            'records' => maca_menulist_filter_dishes_for_list_issue(
                maca_menulist_db_get_dishes(false),
                $list_issue
            ),
            'list_url' => maca_menulist_admin_dishes_list_url($list_issue),
            'edit_page' => 'maca-restu-dishes',
            'edit_id_param' => 'dish_id',
        );
        maca_menulist_render_admin_record_navigation($dish_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="dish">
            <input type="hidden" name="dish_id" value="<?php echo esc_attr($dish_id); ?>">

            <table class="form-table">
                <tr>
                    <th scope="row">
                        <label for="dish_category_id"><?php esc_html_e('Kategori', 'maca-restu-pro'); ?></label>
                    </th>
                    <td>
                        <select id="dish_category_id" name="dish_category_id" required>
                            <option value=""><?php esc_html_e('Välj en kategori', 'maca-restu-pro'); ?></option>
                            <?php foreach ($categories as $cat) : ?>
                                <option value="<?php echo esc_attr($cat->id); ?>" <?php selected($category_id, $cat->id); ?>>
                                    <?php
                                    $cat_label = maca_menulist_get_dish_category_display_name($cat);
                                    if (!maca_menulist_dish_category_is_active($cat)) {
                                        $cat_label .= ' (' . __('inactive', 'maca-restu-pro') . ')';
                                    }
                                    echo esc_html($cat_label);
                                    ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <?php if (empty($categories)) : ?>
                            <p class="description">
                                <?php esc_html_e('Inga rättkategorier hittades.', 'maca-restu-pro'); ?>
                                <a href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-dish-categories&action=add')); ?>"><?php esc_html_e('Create a category first', 'maca-restu-pro'); ?></a>
                            </p>
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="dish_title"><?php echo esc_html(maca_menulist_admin_primary_field_label(__('Titel', 'maca-restu-pro'))); ?></label>
                    </th>
                    <td>
                        <input type="text" id="dish_title" name="dish_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="dish_title_en"><?php echo esc_html(maca_menulist_bilingual_field_label(__('Titel', 'maca-restu-pro'), true)); ?></label>
                    </th>
                    <td>
                        <input type="text" id="dish_title_en" name="dish_title_en" value="<?php echo esc_attr($title_en); ?>" class="regular-text">
                    </td>
                </tr>
                <?php endif; ?>
                <tr>
                    <th scope="row">
                        <label for="dish_description"><?php echo esc_html(maca_menulist_admin_primary_field_label(__('Beskrivning', 'maca-restu-pro'))); ?></label>
                    </th>
                    <td>
                        <textarea id="dish_description" name="dish_description" rows="4" class="large-text"><?php echo esc_textarea($description); ?></textarea>
                    </td>
                </tr>
                <?php if (maca_menulist_admin_show_local_content_fields()) : ?>
                <tr>
                    <th scope="row">
                        <label for="dish_description_en"><?php echo esc_html(maca_menulist_bilingual_field_label(__('Beskrivning', 'maca-restu-pro'), true)); ?></label>
                    </th>
                    <td>
                        <textarea id="dish_description_en" name="dish_description_en" rows="4" class="large-text"><?php echo esc_textarea($description_en); ?></textarea>
                    </td>
                </tr>
                <?php endif; ?>
                <tr>
                    <th scope="row"><?php esc_html_e('Allergener', 'maca-restu-pro'); ?></th>
                    <td>
                        <?php if (empty($allergens)) : ?>
                            <p class="description">
                                <?php esc_html_e('Inga allergener definierade ännu.', 'maca-restu-pro'); ?>
                                <a href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-allergens&action=add')); ?>"><?php esc_html_e('Lägg till allergener först', 'maca-restu-pro'); ?></a>
                            </p>
                        <?php else : ?>
                            <fieldset class="maca-dish-allergen-checkboxes">
                                <legend class="screen-reader-text"><?php esc_html_e('Allergener', 'maca-restu-pro'); ?></legend>
                                <?php foreach ($allergens as $allergen) : ?>
                                    <label style="display:block;margin-bottom:6px;">
                                        <input type="checkbox" name="dish_allergens[]" value="<?php echo esc_attr($allergen->id); ?>" <?php checked(in_array((int) $allergen->id, $selected_allergen_ids, true)); ?>>
                                        <?php echo esc_html(maca_menulist_get_allergen_admin_label($allergen)); ?>
                                    </label>
                                <?php endforeach; ?>
                            </fieldset>
                            <p class="description"><?php esc_html_e('Selected allergens are shown in italics under the dish description on the menu.', 'maca-restu-pro'); ?></p>
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php esc_html_e('Kampanjmenyer', 'maca-restu-pro'); ?></th>
                    <td>
                        <?php if (empty($campaigns)) : ?>
                            <p class="description">
                                <?php esc_html_e('Inga kampanjer finns ännu.', 'maca-restu-pro'); ?>
                                <a href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-campaigns&action=add')); ?>"><?php esc_html_e('Skapa en kampanj först', 'maca-restu-pro'); ?></a>
                            </p>
                        <?php else : ?>
                            <fieldset class="maca-dish-campaign-checkboxes">
                                <legend class="screen-reader-text"><?php esc_html_e('Kampanjmenyer', 'maca-restu-pro'); ?></legend>
                                <?php foreach ($campaigns as $campaign) : ?>
                                    <label style="display:block;margin-bottom:6px;">
                                        <input type="checkbox" name="dish_campaigns[]" value="<?php echo esc_attr($campaign->id); ?>" <?php checked(in_array((int) $campaign->id, $selected_campaign_ids, true)); ?>>
                                        <?php echo esc_html(maca_menulist_get_campaign_admin_label($campaign)); ?>
                                    </label>
                                <?php endforeach; ?>
                            </fieldset>
                            <p class="description"><?php esc_html_e('Markerade rätter visas även i kampanjdelen när kampanjen är schemalagd.', 'maca-restu-pro'); ?></p>
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="dish_price"><?php esc_html_e('Pris', 'maca-restu-pro'); ?></label>
                    </th>
                    <td>
                        <input type="text" id="dish_price" name="dish_price" value="<?php echo esc_attr($price); ?>" class="small-text">
                        <span><?php echo esc_html($currency); ?></span>
                        <p class="description"><?php esc_html_e('Leave empty if no price should be shown. Prices are incl. VAT. For dine-in / default menu display.', 'maca-restu-pro'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="dish_price_takeaway"><?php esc_html_e('Takeaway price', 'maca-restu-pro'); ?></label>
                    </th>
                    <td>
                        <input type="text" id="dish_price_takeaway" name="dish_price_takeaway" value="<?php echo esc_attr($price_takeaway); ?>" class="small-text">
                        <span><?php echo esc_html($currency); ?></span>
                        <p class="description"><?php esc_html_e('Optional. Used on the takeaway menu. Empty = same as the price above.', 'maca-restu-pro'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php esc_html_e('Takeaway', 'maca-restu-pro'); ?></th>
                    <td>
                        <label>
                            <input type="checkbox" name="dish_takeaway_active" value="1" <?php checked($takeaway_active, 1); ?>>
                            <?php esc_html_e('Available for takeaway', 'maca-restu-pro'); ?>
                        </label>
                        <p class="description"><?php esc_html_e('When unchecked, the dish is hidden on the takeaway menu. QR visibility also follows the dish category schedule.', 'maca-restu-pro'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="dish_vat_code"><?php esc_html_e('VAT code', 'maca-restu-pro'); ?></label>
                    </th>
                    <td>
                        <select id="dish_vat_code" name="dish_vat_code">
                            <?php foreach ($vat_code_options as $code => $label) : ?>
                                <?php
                                $rate = maca_menulist_get_vat_rate_for_code($code);
                                $rate_hint = $rate !== '' ? maca_menulist_format_vat_rate_label($rate) : '—';
                                ?>
                                <option value="<?php echo esc_attr($code); ?>" <?php selected($vat_code, $code); ?>>
                                    <?php echo esc_html($label . ' (' . $rate_hint . ')'); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <p class="description"><?php esc_html_e('Used for order confirmation emails and VAT breakdown. Food rate follows your service type setting.', 'maca-restu-pro'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="dish_image_url"><?php esc_html_e('Image', 'maca-restu-pro'); ?></label>
                    </th>
                    <td>
                        <input type="text" id="dish_image_url" name="dish_image_url" value="<?php echo esc_attr($image_url); ?>" class="regular-text">
                        <button type="button" class="button" id="upload_dish_image_button"><?php esc_html_e('Välj bild', 'maca-restu-pro'); ?></button>
                        <p class="description"><?php esc_html_e('Optional image for the dish.', 'maca-restu-pro'); ?></p>
                        <?php if ($image_url) : ?>
                            <div class="maca-dish-image-preview">
                                <img src="<?php echo esc_url($image_url); ?>" alt="<?php echo esc_attr($title); ?>" style="max-width: 120px; margin-top: 10px;">
                            </div>
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="dish_is_active"><?php esc_html_e('Aktiv', 'maca-restu-pro'); ?></label>
                    </th>
                    <td>
                        <input type="checkbox" id="dish_is_active" name="dish_is_active" value="1" <?php checked($is_active, 1); ?>>
                        <label for="dish_is_active"><?php esc_html_e('Show this dish on the menu', 'maca-restu-pro'); ?></label>
                        <p class="description"><?php esc_html_e('Uncheck to hide this dish without affecting other dishes in the category. QR schedule is set on the dish category.', 'maca-restu-pro'); ?></p>
                    </td>
                </tr>
            </table>

            <?php submit_button($action === 'add' ? __('Add Dish', 'maca-restu-pro') : __('Update Dish', 'maca-restu-pro')); ?>
            <?php maca_menulist_render_admin_record_navigation(array_merge($dish_nav, array('modifier' => 'bottom'))); ?>
        </form>

        <script>
            jQuery(document).ready(function($) {
                $('#upload_dish_image_button').on('click', function(e) {
                    e.preventDefault();

                    var mediaUploader = wp.media({
                        title: '<?php echo esc_js(__('Select Dish Image', 'maca-restu-pro')); ?>',
                        button: {
                            text: '<?php echo esc_js(__('Use This Image', 'maca-restu-pro')); ?>'
                        },
                        multiple: false
                    });

                    mediaUploader.on('select', function() {
                        var attachment = mediaUploader.state().get('selection').first().toJSON();
                        $('#dish_image_url').val(attachment.url);
                        $('.maca-dish-image-preview').html('<img src="' + attachment.url + '" alt="" style="max-width: 120px; margin-top: 10px;">');
                    });

                    mediaUploader.open();
                });
            });
        </script>
        <?php
    }

    /**
     * Read and sanitize the active dishes list issue filter from the request.
     *
     * @return string
     */
    private function get_dishes_list_issue_filter() {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only list filter.
        $issue = isset($_GET['issue']) ? sanitize_text_field(wp_unslash($_GET['issue'])) : '';

        return maca_menulist_sanitize_dishes_list_issue($issue);
    }

    /**
     * Notice when the dish list is filtered from the dashboard.
     *
     * @param string $issue       Active issue key.
     * @param int    $shown_count Rows shown.
     * @param int    $total_count Total dishes before filter.
     */
    private function render_dishes_list_issue_notice($issue, $shown_count, $total_count) {
        $label = maca_menulist_get_dishes_list_issue_label($issue);
        if ($label === '') {
            return;
        }

        ?>
        <div class="notice notice-info maca-dishes-list-filter-notice">
            <p>
                <strong><?php echo esc_html($label); ?></strong>
                <?php
                echo esc_html(
                    sprintf(
                        /* translators: 1: filtered count, 2: total dish count */
                        _n(
                            'Showing %1$d of %2$d dish.',
                            'Showing %1$d of %2$d dishes.',
                            $total_count,
                            'maca-restu-pro'
                        ),
                        $shown_count,
                        $total_count
                    )
                );
                ?>
                <a href="<?php echo esc_url(maca_menulist_admin_dishes_list_url()); ?>" class="maca-dishes-list-filter-clear">
                    <?php esc_html_e('Show all dishes', 'maca-restu-pro'); ?>
                </a>
            </p>
        </div>
        <?php
    }

    /**
     * Render dishes list.
     */
    private function render_dishes_list() {
        $issue_filter = $this->get_dishes_list_issue_filter();
        $all_dishes = maca_menulist_db_get_dishes(false);
        $dishes = maca_menulist_filter_dishes_for_list_issue($all_dishes, $issue_filter);
        $show_ratings = maca_menulist_dish_guest_ratings_enabled();
        $menu_print_url = wp_nonce_url(admin_url('admin.php?page=maca-restu-dishes&maca_menu_print=1'), 'maca_menu_print');
        $print_themes = function_exists('maca_menulist_get_menu_print_themes')
            ? maca_menulist_get_menu_print_themes()
            : array('classic' => __('Classic', 'maca-restu-pro'));
        $current_print_theme = function_exists('maca_menulist_get_menu_print_theme')
            ? maca_menulist_get_menu_print_theme()
            : 'classic';
        $current_print_layout = function_exists('maca_menulist_get_menu_print_layout_density')
            ? maca_menulist_get_menu_print_layout_density()
            : 'compact';
        $menu_print_url_with_options = add_query_arg(
            array(
                'theme' => $current_print_theme,
                'layout' => $current_print_layout,
            ),
            $menu_print_url
        );
        $campaign_print_url = '';
        $campaign_print_url_with_options = '';

        if (function_exists('maca_menulist_get_primary_active_campaign')) {
            $active_campaign = maca_menulist_get_primary_active_campaign();
            if ($active_campaign && !empty($active_campaign->id)) {
                $campaign_print_url = wp_nonce_url(
                    admin_url('admin.php?page=maca-restu-dishes&maca_menu_print=1&campaign_id=' . (int) $active_campaign->id),
                    'maca_menu_print'
                );
                $campaign_print_url_with_options = add_query_arg(
                    array(
                        'theme' => $current_print_theme,
                        'layout' => $current_print_layout,
                    ),
                    $campaign_print_url
                );
            }
        }

        if ($issue_filter !== '') {
            $this->render_dishes_list_issue_notice($issue_filter, count($dishes), count($all_dishes));
        }

        ?>
        <p>
            <a href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-dishes&action=add')); ?>" class="button button-primary">
                <?php esc_html_e('Lägg till rätt', 'maca-restu-pro'); ?>
            </a>
            <a href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-dishes&action=sort')); ?>" class="button">
                <?php esc_html_e('Reorder dishes', 'maca-restu-pro'); ?>
            </a>
            <a href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-import-pdf')); ?>" class="button">
                <?php esc_html_e('Importera från PDF', 'maca-restu-pro'); ?>
            </a>
            <a href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-dish-csv')); ?>" class="button">
                <?php esc_html_e('Importera/exportera CSV', 'maca-restu-pro'); ?>
            </a>
        </p>

        <div class="maca-dishes-print-box">
            <h3><?php esc_html_e('Utskriftsinställningar', 'maca-restu-pro'); ?></h3>
            <p class="description"><?php esc_html_e('Välj template och layout innan du skriver ut meny eller aktiv kampanj.', 'maca-restu-pro'); ?></p>
            <div class="maca-dishes-print-box__controls">
                <label for="maca_print_theme"><?php esc_html_e('Menytemplate', 'maca-restu-pro'); ?></label>
                <select id="maca_print_theme" class="regular-text">
                    <?php foreach ($print_themes as $theme_key => $theme_label) : ?>
                        <option value="<?php echo esc_attr($theme_key); ?>" <?php selected($current_print_theme, $theme_key); ?>>
                            <?php echo esc_html($theme_label); ?>
                        </option>
                    <?php endforeach; ?>
                </select>

                <label for="maca_print_layout"><?php esc_html_e('Lista', 'maca-restu-pro'); ?></label>
                <select id="maca_print_layout" class="regular-text">
                    <option value="compact" <?php selected($current_print_layout, 'compact'); ?>><?php esc_html_e('Kompakt', 'maca-restu-pro'); ?></option>
                    <option value="standard" <?php selected($current_print_layout, 'standard'); ?>><?php esc_html_e('Standard', 'maca-restu-pro'); ?></option>
                </select>
            </div>
            <p class="maca-dishes-print-box__actions">
                <a
                    id="maca-print-menu-link"
                    href="<?php echo esc_url($menu_print_url_with_options); ?>"
                    data-base-url="<?php echo esc_url($menu_print_url); ?>"
                    class="button button-primary"
                >
                    <?php esc_html_e('Print menu', 'maca-restu-pro'); ?>
                </a>
                <?php if ($campaign_print_url !== '') : ?>
                    <a
                        id="maca-print-campaign-link"
                        href="<?php echo esc_url($campaign_print_url_with_options); ?>"
                        data-base-url="<?php echo esc_url($campaign_print_url); ?>"
                        class="button"
                    >
                        <?php esc_html_e('Skriv ut aktiv kampanj', 'maca-restu-pro'); ?>
                    </a>
                <?php endif; ?>
            </p>
        </div>

        <script>
            (function () {
                var themeEl = document.getElementById('maca_print_theme');
                var layoutEl = document.getElementById('maca_print_layout');
                var menuLinkEl = document.getElementById('maca-print-menu-link');
                var campaignLinkEl = document.getElementById('maca-print-campaign-link');
                var storageThemeKey = 'maca_menulist_print_theme';
                var storageLayoutKey = 'maca_menulist_print_layout';

                if (!themeEl || !layoutEl || !menuLinkEl) {
                    return;
                }

                function buildUrl(baseUrl) {
                    var url = new URL(baseUrl, window.location.origin);
                    url.searchParams.set('theme', themeEl.value || 'classic');
                    url.searchParams.set('layout', layoutEl.value || 'compact');
                    return url.toString();
                }

                function syncPrintLinks() {
                    menuLinkEl.href = buildUrl(menuLinkEl.getAttribute('data-base-url') || menuLinkEl.href);
                    if (campaignLinkEl) {
                        campaignLinkEl.href = buildUrl(campaignLinkEl.getAttribute('data-base-url') || campaignLinkEl.href);
                    }
                }

                function hasOption(selectEl, value) {
                    if (!selectEl || !value) {
                        return false;
                    }

                    for (var i = 0; i < selectEl.options.length; i++) {
                        if (selectEl.options[i].value === value) {
                            return true;
                        }
                    }

                    return false;
                }

                try {
                    var savedTheme = window.localStorage.getItem(storageThemeKey);
                    var savedLayout = window.localStorage.getItem(storageLayoutKey);

                    if (hasOption(themeEl, savedTheme)) {
                        themeEl.value = savedTheme;
                    }
                    if (hasOption(layoutEl, savedLayout)) {
                        layoutEl.value = savedLayout;
                    }
                } catch (e) {
                    // Ignore storage errors (private mode / blocked storage).
                }

                function persistPrintPrefs() {
                    try {
                        window.localStorage.setItem(storageThemeKey, themeEl.value || 'classic');
                        window.localStorage.setItem(storageLayoutKey, layoutEl.value || 'compact');
                    } catch (e) {
                        // Ignore storage errors and keep UX working.
                    }
                }

                themeEl.addEventListener('change', syncPrintLinks);
                layoutEl.addEventListener('change', syncPrintLinks);
                themeEl.addEventListener('change', persistPrintPrefs);
                layoutEl.addEventListener('change', persistPrintPrefs);
                syncPrintLinks();
                persistPrintPrefs();
            })();
        </script>

        <style>
            .maca-dishes-print-box {
                margin: 0 0 16px;
                padding: 14px 16px;
                border: 1px solid #d0d7de;
                border-radius: 8px;
                background: #fff;
                box-shadow: 0 1px 2px rgba(16, 24, 40, 0.04);
            }
            .maca-dishes-print-box h3 {
                margin: 0 0 4px;
            }
            .maca-dishes-print-box .description {
                margin: 0 0 10px;
            }
            .maca-dishes-print-box__controls {
                display: flex;
                flex-wrap: wrap;
                align-items: center;
                gap: 8px 12px;
            }
            .maca-dishes-print-box__controls label {
                font-weight: 600;
            }
            .maca-dishes-print-box__controls select {
                min-width: 180px;
                margin-right: 4px;
            }
            .maca-dishes-print-box__actions {
                margin: 12px 0 0;
                display: flex;
                flex-wrap: wrap;
                gap: 8px;
            }
            .maca-dishes-list-search {
                margin: 0 0 16px;
                padding: 12px 14px;
                border: 1px solid #d0d7de;
                border-radius: 8px;
                background: #fff;
                display: flex;
                flex-wrap: wrap;
                align-items: center;
                gap: 10px 14px;
            }
            .maca-dishes-list-search label {
                font-weight: 600;
                margin: 0;
            }
            .maca-dishes-list-search-input {
                min-width: min(100%, 320px);
                flex: 1 1 240px;
            }
            .maca-dishes-list-search-meta {
                color: #50575e;
                font-size: 13px;
            }
            .maca-dish-list-row.is-hidden-by-search {
                display: none;
            }
        </style>

        <?php if (empty($dishes)) : ?>
            <p>
                <?php
                if ($issue_filter !== '') {
                    esc_html_e('Inga rätter matchar filtret.', 'maca-restu-pro');
                } else {
                    esc_html_e('Inga rätter hittades. Lägg till din första rätt ovan.', 'maca-restu-pro');
                }
                ?>
            </p>
        <?php else : ?>
            <div class="maca-dishes-list-search">
                <label for="maca-dishes-list-search-input"><?php esc_html_e('Search dishes', 'maca-restu-pro'); ?></label>
                <input
                    type="search"
                    id="maca-dishes-list-search-input"
                    class="regular-text maca-dishes-list-search-input"
                    placeholder="<?php esc_attr_e('Title, category, description, price…', 'maca-restu-pro'); ?>"
                    autocomplete="off"
                    spellcheck="false"
                >
                <span class="maca-dishes-list-search-meta" id="maca-dishes-list-search-meta" aria-live="polite"></span>
            </div>

            <table class="wp-list-table widefat fixed striped" id="maca-dishes-list-table">
                <thead>
                    <tr>
                        <th><?php esc_html_e('Image', 'maca-restu-pro'); ?></th>
                        <th><?php esc_html_e('Titel', 'maca-restu-pro'); ?></th>
                        <th><?php esc_html_e('Kategori', 'maca-restu-pro'); ?></th>
                        <th><?php esc_html_e('Pris', 'maca-restu-pro'); ?></th>
                        <th><?php esc_html_e('VAT code', 'maca-restu-pro'); ?></th>
                        <?php if ($show_ratings) : ?>
                            <th><?php esc_html_e('Rating', 'maca-restu-pro'); ?></th>
                        <?php endif; ?>
                        <th><?php esc_html_e('QR status', 'maca-restu-pro'); ?></th>
                        <th><?php esc_html_e('Åtgärder', 'maca-restu-pro'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($dishes as $dish) : ?>
                        <tr
                            class="maca-dish-list-row"
                            data-search="<?php echo esc_attr(maca_menulist_get_dish_list_search_blob($dish)); ?>"
                        >
                            <td>
                                <?php if (!empty($dish->image_url)) : ?>
                                    <img src="<?php echo esc_url($dish->image_url); ?>" alt="<?php echo esc_attr($dish->title); ?>" style="max-width: 50px; max-height: 50px; object-fit: cover;">
                                <?php else : ?>
                                    <em><?php esc_html_e('Ingen bild', 'maca-restu-pro'); ?></em>
                                <?php endif; ?>
                            </td>
                            <td><strong><?php echo esc_html(maca_menulist_get_admin_content_label($dish->title, isset($dish->title_en) ? $dish->title_en : '')); ?></strong></td>
                            <td><?php echo esc_html($dish->category_name); ?></td>
                            <td><?php echo esc_html(maca_menulist_format_price($dish->price)); ?></td>
                            <td>
                                <?php
                                $dish_vat_code = maca_menulist_sanitize_dish_vat_code($dish->vat_code ?? 'food');
                                $dish_vat_options = maca_menulist_get_dish_vat_code_options();
                                $dish_vat_label = isset($dish_vat_options[ $dish_vat_code ]) ? $dish_vat_options[ $dish_vat_code ] : $dish_vat_code;
                                $dish_vat_rate = maca_menulist_get_vat_rate_for_code($dish_vat_code);
                                echo esc_html(
                                    $dish_vat_rate !== ''
                                        ? $dish_vat_label . ' · ' . maca_menulist_format_vat_rate_label($dish_vat_rate)
                                        : $dish_vat_label
                                );
                                ?>
                            </td>
                            <?php if ($show_ratings) : ?>
                                <?php
                                $rating_summary = maca_menulist_db_get_dish_rating_summary((int) $dish->id);
                                ?>
                                <td>
                                    <?php if ($rating_summary['count'] > 0) : ?>
                                        <?php echo esc_html(number_format($rating_summary['average'], 1, ',', ' ')); ?>
                                        <?php
                                        echo esc_html(
                                            sprintf(
                                                /* translators: %d: number of ratings */
                                                _n('(%d rating)', '(%d ratings)', $rating_summary['count'], 'maca-restu-pro'),
                                                $rating_summary['count']
                                            )
                                        );
                                        ?>
                                    <?php else : ?>
                                        <em><?php esc_html_e('Inga betyg ännu', 'maca-restu-pro'); ?></em>
                                    <?php endif; ?>
                                </td>
                            <?php endif; ?>
                            <td>
                                <?php
                                $status = maca_menulist_get_dish_qr_status($dish);
                                $status_labels = array(
                                    'active' => __('Aktiv nu', 'maca-restu-pro'),
                                    'inactive' => __('Inaktiv', 'maca-restu-pro'),
                                    'scheduled' => __('Schemalagd', 'maca-restu-pro'),
                                    'expired' => __('Utgången', 'maca-restu-pro'),
                                    'outside_hours' => __('Utanför tid', 'maca-restu-pro'),
                                );
                                echo esc_html(isset($status_labels[$status]) ? $status_labels[$status] : $status);
                                ?>
                            </td>
                            <td>
                                <?php
                                $dish_edit_url = admin_url(
                                    'admin.php?page=maca-restu-dishes&action=edit&dish_id=' . (int) $dish->id
                                );
                                if ($issue_filter !== '') {
                                    $dish_edit_url = add_query_arg('issue', $issue_filter, $dish_edit_url);
                                }
                                ?>
                                <a href="<?php echo esc_url($dish_edit_url); ?>" class="button button-small">
                                    <?php esc_html_e('Redigera', '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="dish">
                                    <input type="hidden" name="dish_id" value="<?php echo esc_attr($dish->id); ?>">
                                    <button type="submit" class="button button-small" onclick="return confirm('<?php echo esc_js(__('Are you sure you want to delete this dish?', 'maca-restu-pro')); ?>');">
                                        <?php esc_html_e('Radera', 'maca-restu-pro'); ?>
                                    </button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    <tr class="maca-dish-list-no-results" id="maca-dish-list-no-results" hidden>
                        <td colspan="<?php echo esc_attr($show_ratings ? 8 : 7); ?>">
                            <?php esc_html_e('No dishes match your search.', 'maca-restu-pro'); ?>
                        </td>
                    </tr>
                </tbody>
            </table>
        <?php endif; ?>
        <?php
    }

    /**
     * Render drag-and-drop dish ordering grouped by category.
     */
    private function render_dishes_sort() {
        $categories = maca_menulist_db_get_dish_categories();
        $list_url = maca_menulist_admin_dishes_list_url($this->get_dishes_list_issue_filter());

        ?>
        <style>
            .maca-dish-sort-nav {
                margin: 16px 0 20px;
            }
            .maca-dish-sort-group {
                margin: 0 0 28px;
                max-width: 720px;
            }
            .maca-dish-sort-group h2 {
                margin: 0 0 10px;
                font-size: 16px;
            }
            .maca-dish-sort-list {
                margin: 0;
                padding: 0;
                list-style: none;
                border: 1px solid #c3c4c7;
                border-radius: 4px;
                background: #fff;
            }
            .maca-dish-sort-list.is-saving {
                opacity: 0.65;
                pointer-events: none;
            }
            .maca-dish-sort-item {
                display: flex;
                align-items: center;
                gap: 12px;
                margin: 0;
                padding: 10px 12px;
                border-bottom: 1px solid #e0e0e0;
                background: #fff;
            }
            .maca-dish-sort-item:last-child {
                border-bottom: 0;
            }
            .maca-dish-sort-item.ui-sortable-helper {
                box-shadow: 0 4px 14px rgba(0, 0, 0, 0.12);
            }
            .maca-dish-sort-handle {
                flex: 0 0 auto;
                width: 28px;
                color: #787c82;
                font-size: 18px;
                line-height: 1;
                cursor: grab;
                user-select: none;
                text-align: center;
            }
            .maca-dish-sort-handle:active {
                cursor: grabbing;
            }
            .maca-dish-sort-title {
                flex: 1 1 auto;
                font-weight: 600;
            }
            .maca-dish-sort-meta {
                flex: 0 0 auto;
                color: #646970;
                font-size: 13px;
            }
            .maca-dish-sort-empty {
                margin: 0;
                padding: 12px;
                color: #646970;
                font-style: italic;
            }
            .maca-dish-sort-notice {
                max-width: 720px;
                margin: 0 0 16px;
            }
        </style>

        <div class="maca-dish-sort-nav">
            <a href="<?php echo esc_url($list_url); ?>">&larr; <?php esc_html_e('Back to dish list', 'maca-restu-pro'); ?></a>
        </div>

        <p class="description"><?php esc_html_e('Drag dishes up or down within each category. The order is saved automatically and shown on the menu and QR page.', 'maca-restu-pro'); ?></p>

        <div class="notice notice-success maca-dish-sort-notice" style="display:none;">
            <p></p>
        </div>

        <?php if (empty($categories)) : ?>
            <p><?php esc_html_e('Add a dish category before reordering dishes.', 'maca-restu-pro'); ?></p>
        <?php else : ?>
            <?php foreach ($categories as $category) : ?>
                <?php
                $dishes = maca_menulist_db_get_dishes_by_category((int) $category->id, false);
                ?>
                <div class="maca-dish-sort-group">
                    <h2><?php echo esc_html(maca_menulist_get_dish_category_display_name($category)); ?></h2>
                    <?php if (empty($dishes)) : ?>
                        <p class="maca-dish-sort-empty"><?php esc_html_e('No dishes in this category.', 'maca-restu-pro'); ?></p>
                    <?php else : ?>
                        <ul class="maca-dish-sort-list" data-category-id="<?php echo esc_attr($category->id); ?>">
                            <?php foreach ($dishes as $dish) : ?>
                                <li class="maca-dish-sort-item" data-dish-id="<?php echo esc_attr($dish->id); ?>">
                                    <span class="maca-dish-sort-handle" aria-hidden="true" title="<?php esc_attr_e('Drag to reorder', 'maca-restu-pro'); ?>">&#9776;</span>
                                    <span class="maca-dish-sort-title"><?php echo esc_html(maca_menulist_get_dish_display_title($dish)); ?></span>
                                    <span class="maca-dish-sort-meta">
                                        <?php
                                        echo esc_html(maca_menulist_format_price($dish->price));
                                        if (!(int) $dish->is_active) {
                                            echo ' · ' . esc_html__('Inactive', 'maca-restu-pro');
                                        }
                                        ?>
                                    </span>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
        <?php
    }

    /**
     * Render allergens page.
     */
    public function render_allergens_page() {
        if (!maca_menulist_pro_has_feature('dishes')) {
            ?>
            <div class="wrap">
                <h1><?php esc_html_e('Allergener', 'maca-restu-pro'); ?></h1>
                <?php echo wp_kses_post(maca_menulist_pro_locked_notice('dishes')); ?>
            </div>
            <?php
            return;
        }

        // phpcs:disable WordPress.Security.NonceVerification.Recommended
        $action = isset($_GET['action']) ? sanitize_text_field(wp_unslash($_GET['action'])) : 'list';
        $allergen_id = isset($_GET['allergen_id']) ? intval($_GET['allergen_id']) : 0;
        // phpcs:enable WordPress.Security.NonceVerification.Recommended

        ?>
        <div class="wrap">
            <h1><?php esc_html_e('Allergener', 'maca-restu-pro'); ?></h1>
            <p class="description"><?php esc_html_e('Define allergen labels that can be assigned to dishes, such as gluten, lactose, or nuts.', 'maca-restu-pro'); ?></p>

            <?php settings_errors('maca_allergen'); ?>

            <?php if ($action === 'add' || $action === 'edit') : ?>
                <?php $this->render_allergen_form($action, $allergen_id); ?>
            <?php else : ?>
                <?php $this->render_allergens_list(); ?>
            <?php endif; ?>
        </div>
        <?php
    }

    /**
     * Render allergen form.
     *
     * @param string $action Action type.
     * @param int    $allergen_id Allergen ID.
     */
    private function render_allergen_form($action, $allergen_id) {
        $allergen = null;
        if ($action === 'edit' && $allergen_id > 0) {
            $allergen = maca_menulist_db_get_allergen($allergen_id);
        }

        $name = $allergen ? $allergen->name : '';
        $name_en = $allergen && isset($allergen->name_en) ? $allergen->name_en : '';
        $sort_order = $allergen ? $allergen->sort_order : 0;

        ?>
        <h2><?php echo esc_html($action === 'add' ? __('Add Allergen', 'maca-restu-pro') : __('Edit Allergen', 'maca-restu-pro')); ?></h2>
        <?php
        $allergen_nav = array(
            'action' => $action,
            'current_id' => $allergen_id,
            'records' => maca_menulist_db_get_allergens(),
            'list_url' => admin_url('admin.php?page=maca-restu-allergens'),
            'edit_page' => 'maca-restu-allergens',
            'edit_id_param' => 'allergen_id',
        );
        maca_menulist_render_admin_record_navigation($allergen_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="allergen">
            <input type="hidden" name="allergen_id" value="<?php echo esc_attr($allergen_id); ?>">

            <table class="form-table">
                <tr>
                    <th scope="row">
                        <label for="allergen_name"><?php echo esc_html(maca_menulist_admin_primary_field_label(__('Name', 'maca-restu-pro'))); ?></label>
                    </th>
                    <td>
                        <input type="text" id="allergen_name" name="allergen_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="allergen_name_en"><?php echo esc_html(maca_menulist_bilingual_field_label(__('Name', 'maca-restu-pro'), true)); ?></label>
                    </th>
                    <td>
                        <input type="text" id="allergen_name_en" name="allergen_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="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('Order in checkbox lists and on the menu when multiple allergens are shown.', 'maca-restu-pro'); ?></p>
                    </td>
                </tr>
            </table>

            <?php submit_button($action === 'add' ? __('Add Allergen', 'maca-restu-pro') : __('Update Allergen', 'maca-restu-pro')); ?>
            <?php maca_menulist_render_admin_record_navigation(array_merge($allergen_nav, array('modifier' => 'bottom'))); ?>
        </form>
        <?php
    }

    /**
     * Render allergens list.
     */
    private function render_allergens_list() {
        $allergens = maca_menulist_db_get_allergens();

        ?>
        <p>
            <a href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-allergens&action=add')); ?>" class="button button-primary">
                <?php esc_html_e('Lägg till allergen', '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="restore_defaults">
                <input type="hidden" name="maca_type" value="allergen">
                <button
                    type="submit"
                    class="button"
                    onclick="return confirm('<?php echo esc_js(__('Restore the ten standard EU allergens? Existing matches will be reset to default local and English names. Custom allergens are not removed.', 'maca-restu-pro')); ?>');"
                >
                    <?php esc_html_e('Restore default allergens', 'maca-restu-pro'); ?>
                </button>
            </form>
        </p>

        <?php if (empty($allergens)) : ?>
            <p><?php esc_html_e('Inga allergener hittades. Lägg till din första allergen ovan.', 'maca-restu-pro'); ?></p>
        <?php else : ?>
            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th><?php echo esc_html(maca_menulist_admin_show_local_content_fields() ? maca_menulist_bilingual_field_label(__('Name', 'maca-restu-pro')) : __('Name', 'maca-restu-pro')); ?></th>
                        <?php if (maca_menulist_admin_show_local_content_fields()) : ?>
                            <th><?php echo esc_html(maca_menulist_bilingual_field_label(__('Name', 'maca-restu-pro'), true)); ?></th>
                        <?php endif; ?>
                        <th><?php esc_html_e('Sort Order', 'maca-restu-pro'); ?></th>
                        <th><?php esc_html_e('Åtgärder', 'maca-restu-pro'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($allergens as $allergen) : ?>
                        <tr>
                            <td><strong><?php echo esc_html(maca_menulist_get_admin_content_label($allergen->name, isset($allergen->name_en) ? $allergen->name_en : '')); ?></strong></td>
                            <?php if (maca_menulist_admin_show_local_content_fields()) : ?>
                                <td><?php echo esc_html(isset($allergen->name_en) ? $allergen->name_en : ''); ?></td>
                            <?php endif; ?>
                            <td><?php echo esc_html($allergen->sort_order); ?></td>
                            <td>
                                <a href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-allergens&action=edit&allergen_id=' . $allergen->id)); ?>" class="button button-small">
                                    <?php esc_html_e('Redigera', '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="allergen">
                                    <input type="hidden" name="allergen_id" value="<?php echo esc_attr($allergen->id); ?>">
                                    <button type="submit" class="button button-small" onclick="return confirm('<?php echo esc_js(__('Are you sure? This allergen will be removed from all dishes.', 'maca-restu-pro')); ?>');">
                                        <?php esc_html_e('Radera', 'maca-restu-pro'); ?>
                                    </button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
        <?php
    }
}
