<?php
/**
 * Short URL / rewrite rules for maca Restu
 *
 * @package Maca_Menu_List
 */

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

/**
 * Get the URL slug used for the public QR menu page.
 */
/**
 * Whether menu titles should be shown above menu files on the website.
 */
function maca_menulist_show_menu_title() {
    return get_option('maca_menulist_show_menu_title', '1') === '1';
}

/**
 * Whether serving-hour notes are shown for menus outside live schedule.
 */
function maca_menulist_show_schedule_notes() {
    return get_option('maca_menulist_show_schedule_notes', '1') === '1';
}

/**
 * Default menu page title when no custom text is configured.
 *
 * @return string
 */
function maca_menulist_get_default_menu_page_title() {
    if (function_exists('maca_menulist_guest_ui_string')) {
        return maca_menulist_guest_ui_string('Our menu');
    }

    return __('Our menu', 'maca-restu-pro');
}

/**
 * Shared fallback chain for public menu page titles.
 *
 * @return string
 */
function maca_menulist_get_menu_page_title_fallback() {
    $restaurant_name = trim((string) get_option('maca_menulist_menu_footer_restaurant_name', ''));

    if ($restaurant_name !== '') {
        return $restaurant_name;
    }

    return maca_menulist_get_default_menu_page_title();
}

/**
 * Heading on website pages that embed [maca_menu_list].
 *
 * @return string
 */
function maca_menulist_get_website_menu_page_title() {
    if (function_exists('maca_menulist_get_menu_page_title_option_text')) {
        $title = maca_menulist_get_menu_page_title_option_text('website_menu_page_title');

        if ($title !== '') {
            return $title;
        }
    }

    return maca_menulist_get_qr_menu_page_title();
}

/**
 * Heading on the public QR menu page when guests scan the code.
 * The printable QR image uses maca_menulist_qr_title / qr_subtitle instead.
 *
 * @return string
 */
function maca_menulist_get_qr_menu_page_title() {
    if (function_exists('maca_menulist_get_menu_page_title_option_text')) {
        $title = maca_menulist_get_menu_page_title_option_text('qr_menu_page_title');

        if ($title !== '') {
            return $title;
        }
    }

    return maca_menulist_get_menu_page_title_fallback();
}

/**
 * @deprecated 1.13.3 Use maca_menulist_get_qr_menu_page_title().
 * @return string
 */
function maca_menulist_get_qr_guest_page_title() {
    return maca_menulist_get_qr_menu_page_title();
}

/**
 * Uploaded logo URL shared by QR menu and QR print.
 *
 * @return string
 */
function maca_menulist_get_qr_logo_url() {
    return esc_url((string) get_option('maca_menulist_qr_logo', ''));
}

/**
 * Whether the logo should appear on the public QR menu page.
 *
 * @return bool
 */
function maca_menulist_qr_menu_show_logo() {
    return get_option('maca_menulist_qr_menu_show_logo', '1') === '1';
}

/**
 * Whether the logo should appear on the printable QR code page.
 *
 * @return bool
 */
function maca_menulist_qr_print_show_logo() {
    return get_option('maca_menulist_qr_print_show_logo', '1') === '1';
}

/**
 * Logo URL for the public QR / takeaway menu page, if enabled.
 *
 * @return string
 */
function maca_menulist_get_qr_menu_logo_url() {
    if (!maca_menulist_qr_menu_show_logo()) {
        return '';
    }

    return maca_menulist_get_qr_logo_url();
}

/**
 * Logo URL for the admin QR print page, if enabled.
 *
 * @return string
 */
function maca_menulist_get_qr_print_logo_url() {
    if (!maca_menulist_qr_print_show_logo()) {
        return '';
    }

    return maca_menulist_get_qr_logo_url();
}

/**
 * Render the QR menu logo above the page title when enabled.
 *
 * @return void
 */
function maca_menulist_render_qr_menu_logo() {
    $logo_url = maca_menulist_get_qr_menu_logo_url();

    if ($logo_url === '') {
        return;
    }

    echo '<div class="maca-qr-menu-logo" style="text-align: center; margin-bottom: 20px;">';
    echo '<img src="' . esc_url($logo_url) . '" alt="' . esc_attr__('Logo', 'maca-restu-pro') . '" style="max-width: 150px; height: auto;">';
    echo '</div>';
}

function maca_menulist_get_qr_slug() {
    $slug = get_option('maca_menulist_qr_slug', 'qrmeny');
    $slug = sanitize_title($slug);

    if ($slug === '') {
        $slug = 'qrmeny';
    }

    return $slug;
}

/**
 * Build the public QR menu URL.
 *
 * @param int    $category_id  Optional category ID for a category-specific link.
 * @param string $table_number Optional table number (appended as ?bord=).
 */
function maca_menulist_get_qr_url($category_id = 0, $table_number = '') {
    $slug = maca_menulist_get_qr_slug();
    $category_id = intval($category_id);

    if ($category_id > 0) {
        $url = home_url('/' . $slug . '/' . $category_id . '/');
    } else {
        $url = home_url('/' . $slug . '/');
    }

    $table_number = sanitize_text_field($table_number);
    if ($table_number !== '') {
        $url = add_query_arg('bord', $table_number, $url);
    }

    return $url;
}

/**
 * Whether WordPress rewrite API is ready (not before init).
 *
 * @return bool
 */
function maca_menulist_rewrite_api_is_ready() {
    global $wp_rewrite;

    return did_action('init') && isset($wp_rewrite) && $wp_rewrite instanceof WP_Rewrite;
}

/**
 * Schedule a rewrite flush on the next init (safe after activation).
 *
 * @return void
 */
function maca_menulist_schedule_rewrite_flush() {
    update_option('maca_menulist_pending_rewrite_flush', MACA_MENULIST_VERSION);
}

/**
 * Flush rewrites once after activation / slug change (runs on init).
 *
 * @return void
 */
function maca_menulist_run_pending_rewrite_flush() {
    if (get_option('maca_menulist_pending_rewrite_flush') !== MACA_MENULIST_VERSION) {
        return;
    }

    delete_option('maca_menulist_pending_rewrite_flush');

    if (!maca_menulist_rewrite_api_is_ready()) {
        return;
    }

    maca_menulist_flush_rewrite_rules();
    delete_option('maca_menulist_activation_fatal');
}

/**
 * Register rewrite rules for the short QR menu URL.
 */
function maca_menulist_register_rewrites() {
    if (!maca_menulist_rewrite_api_is_ready()) {
        return;
    }

    if (!function_exists('maca_menulist_get_management_overview_slug')) {
        require_once MACA_MENULIST_PLUGIN_DIR . 'includes/management-overview.php';
    }

    $slug = maca_menulist_get_qr_slug();

    add_rewrite_rule(
        '^' . preg_quote($slug, '/') . '/([0-9]+)/?$',
        'index.php?maca_qr_menu=1&maca_qr_category=$matches[1]',
        'top'
    );

    add_rewrite_rule(
        '^' . preg_quote($slug, '/') . '/?$',
        'index.php?maca_qr_menu=1',
        'top'
    );

    if (function_exists('maca_menulist_get_takeaway_slug')) {
        $takeaway_slug = maca_menulist_get_takeaway_slug();
        add_rewrite_rule(
            '^' . preg_quote($takeaway_slug, '/') . '/?$',
            'index.php?maca_takeaway_menu=1',
            'top'
        );
    }

    // Always register staff page routes so slugs never return 404.
    // Access control and enable/disable checks happen in frontend handlers.
    $waiter_slug = maca_menulist_get_waiter_order_slug();
    add_rewrite_rule(
        '^' . preg_quote($waiter_slug, '/') . '/?$',
        'index.php?maca_staff_orders=1&maca_staff_view=waiter',
        'top'
    );

    $kitchen_slug = maca_menulist_get_kitchen_order_slug();
    add_rewrite_rule(
        '^' . preg_quote($kitchen_slug, '/') . '/?$',
        'index.php?maca_staff_orders=1&maca_staff_view=kitchen',
        'top'
    );

    $overview_slug = maca_menulist_get_management_overview_slug();
    add_rewrite_rule(
        '^' . preg_quote($overview_slug, '/') . '/?$',
        'index.php?maca_management_overview=1',
        'top'
    );

    if (function_exists('maca_menulist_table_booking_enabled') && maca_menulist_table_booking_guest_cancel_enabled()) {
        $cancel_slug = maca_menulist_get_table_booking_cancel_slug();
        add_rewrite_rule(
            '^' . preg_quote($cancel_slug, '/') . '/?$',
            'index.php?maca_booking_cancel=1',
            'top'
        );
    }

    if (function_exists('maca_menulist_get_attendance_slug')) {
        $attendance_slug = maca_menulist_get_attendance_slug();
        add_rewrite_rule(
            '^' . preg_quote($attendance_slug, '/') . '/kontroll/?$',
            'index.php?maca_attendance=1&maca_attendance_view=kontroll',
            'top'
        );
        add_rewrite_rule(
            '^' . preg_quote($attendance_slug, '/') . '/?$',
            'index.php?maca_attendance=1',
            'top'
        );
    }

    if (function_exists('maca_menulist_get_info_events_ics_filename')) {
        $ics_file = maca_menulist_get_info_events_ics_filename();
        add_rewrite_rule(
            '^' . preg_quote($ics_file, '/') . '/?$',
            'index.php?maca_info_events_ics=1',
            'top'
        );
    }

}

/**
 * Register custom query vars.
 */
function maca_menulist_query_vars($vars) {
    if (!is_array($vars)) {
        $vars = array();
    }

    $vars[] = 'maca_qr_menu';
    $vars[] = 'maca_qr_category';
    $vars[] = 'maca_takeaway_menu';
    $vars[] = 'maca_staff_orders';
    $vars[] = 'maca_staff_view';
    $vars[] = 'maca_management_overview';
    $vars[] = 'maca_booking_cancel';
    $vars[] = 'maca_attendance';
    $vars[] = 'maca_attendance_view';
    $vars[] = 'maca_info_events_ics';
    return $vars;
}

/**
 * Flush rewrite rules after activation or QR slug change.
 */
function maca_menulist_flush_rewrite_rules() {
    if (!maca_menulist_rewrite_api_is_ready()) {
        maca_menulist_schedule_rewrite_flush();
        return;
    }

    maca_menulist_register_rewrites();
    flush_rewrite_rules(false);
}

/**
 * One-time cleanup for stale flush flags from older plugin versions.
 */
function maca_menulist_clear_legacy_flush_flag() {
    if (get_option('maca_menulist_flush_flag_cleared') === MACA_MENULIST_VERSION) {
        return;
    }

    delete_option('maca_menulist_flush_rewrite');
    update_option('maca_menulist_flush_flag_cleared', MACA_MENULIST_VERSION);
}

/**
 * Check if the current request is for the QR menu page.
 */
function maca_menulist_is_qr_menu_request() {
    // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Public routing via rewrite rules and query vars.
    if (isset($_GET['maca_qr_menu']) && sanitize_text_field(wp_unslash($_GET['maca_qr_menu'])) === '1') {
        // phpcs:enable WordPress.Security.NonceVerification.Recommended
        return true;
    }
    // phpcs:enable WordPress.Security.NonceVerification.Recommended

    return (string) get_query_var('maca_qr_menu') === '1';
}

/**
 * Check if the current request is for the public takeaway menu page.
 *
 * @return bool
 */
function maca_menulist_is_takeaway_menu_request() {
    // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Public routing via rewrite rules and query vars.
    if (isset($_GET['maca_takeaway_menu']) && sanitize_text_field(wp_unslash($_GET['maca_takeaway_menu'])) === '1') {
        // phpcs:enable WordPress.Security.NonceVerification.Recommended
        return true;
    }
    // phpcs:enable WordPress.Security.NonceVerification.Recommended

    return (string) get_query_var('maca_takeaway_menu') === '1';
}

/**
 * Category ID from the short URL, if any.
 */
function maca_menulist_get_qr_url_category_id() {
    // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Public routing via rewrite rules and query vars.
    if (isset($_GET['maca_qr_category'])) {
        $category_id = intval(wp_unslash($_GET['maca_qr_category']));
        // phpcs:enable WordPress.Security.NonceVerification.Recommended
        return $category_id;
    }
    // phpcs:enable WordPress.Security.NonceVerification.Recommended

    return intval(get_query_var('maca_qr_category'));
}

/**
 * Path segment for the current front-end request (no leading/trailing slashes).
 *
 * @return string
 */
function maca_menulist_get_request_path() {
    global $wp;

    $path = '';
    if (isset($wp->request) && (string) $wp->request !== '') {
        $path = trim((string) $wp->request, '/');
    }

    if ($path === '') {
        $uri_path = '';
        if (isset($_SERVER['REQUEST_URI'])) {
            $uri_path = (string) wp_parse_url(wp_unslash($_SERVER['REQUEST_URI']), PHP_URL_PATH);
        }
        $uri_path = trim($uri_path, '/');

        if (strpos($uri_path, 'index.php/') === 0) {
            $uri_path = trim(substr($uri_path, strlen('index.php/')), '/');
        } elseif ($uri_path === 'index.php') {
            $uri_path = '';
        }

        $home_path = trim((string) wp_parse_url(home_url('/'), PHP_URL_PATH), '/');
        if ($home_path !== '' && strpos($uri_path, $home_path) === 0) {
            $uri_path = trim(substr($uri_path, strlen($home_path)), '/');
        }

        $path = $uri_path;
    }

    return strtolower($path);
}

/**
 * Whether a request path targets a configured staff page slug.
 *
 * Supports exact matches and trailing segments (e.g. language prefix /en/waiter-slug/).
 *
 * @param string $path Request path without leading/trailing slashes.
 * @param string $slug Staff page slug.
 * @return bool
 */
function maca_menulist_request_path_matches_slug($path, $slug) {
    $path = strtolower(trim((string) $path, '/'));
    $slug = strtolower(trim((string) $slug, '/'));

    if ($path === '' || $slug === '') {
        return false;
    }

    if ($path === $slug) {
        return true;
    }

    if (strlen($path) <= strlen($slug) || substr($path, -strlen($slug)) !== $slug) {
        return false;
    }

    $prefix = substr($path, 0, -strlen($slug));

    return $prefix !== '' && substr($prefix, -1) === '/';
}

/**
 * Resolve staff view (waiter|kitchen) from the current request path.
 *
 * @param string|null $path Optional path override.
 * @return string Empty string when no staff route matches.
 */
function maca_menulist_get_staff_view_from_request_path($path = null) {
    if ($path === null) {
        $path = maca_menulist_get_request_path();
    }

    if (!function_exists('maca_menulist_get_waiter_order_slug')) {
        return '';
    }

    if (maca_menulist_request_path_matches_slug($path, maca_menulist_get_waiter_order_slug())) {
        return 'waiter';
    }

    if (maca_menulist_request_path_matches_slug($path, maca_menulist_get_kitchen_order_slug())) {
        return 'kitchen';
    }

    return '';
}

/**
 * Apply staff order query vars and clear 404 state on the main query.
 *
 * @param string $view Staff view: waiter or kitchen.
 * @return void
 */
function maca_menulist_apply_staff_request_query_vars($view) {
    $view = ($view === 'kitchen') ? 'kitchen' : 'waiter';

    set_query_var('maca_staff_orders', '1');
    set_query_var('maca_staff_view', $view);

    global $wp_query;
    if ($wp_query instanceof WP_Query) {
        $wp_query->set('maca_staff_orders', '1');
        $wp_query->set('maca_staff_view', $view);
        $wp_query->is_404 = false;
        $wp_query->is_home = false;
        $wp_query->is_page = false;
        $wp_query->is_singular = false;
    }
}

/**
 * Match staff order URLs even when rewrite rules are stale (avoids theme 404).
 *
 * @return bool True when query vars were set from the request path.
 */
function maca_menulist_bootstrap_staff_request_query_vars() {
    if ((string) get_query_var('maca_staff_orders') === '1') {
        return false;
    }

    $view = maca_menulist_get_staff_view_from_request_path();
    if ($view === '') {
        return false;
    }

    maca_menulist_apply_staff_request_query_vars($view);

    return true;
}

/**
 * Bootstrap staff routes during parse_request (before 404 handling).
 *
 * @param WP $wp WordPress environment instance.
 * @return void
 */
function maca_menulist_parse_request_staff_routes($wp) {
    unset($wp);
    maca_menulist_bootstrap_staff_request_query_vars();
}

/**
 * Prevent WordPress from treating staff URLs as theme 404s.
 *
 * @param bool|null $preempt  Whether to short-circuit 404 handling.
 * @param WP_Query  $wp_query Main query instance.
 * @return bool|null
 */
function maca_menulist_prevent_staff_route_404($preempt, $wp_query) {
    if ($preempt) {
        return $preempt;
    }

    if ((string) get_query_var('maca_staff_orders') === '1') {
        if ($wp_query instanceof WP_Query) {
            $wp_query->is_404 = false;
        }

        return true;
    }

    if (maca_menulist_bootstrap_staff_request_query_vars()) {
        return true;
    }

    return $preempt;
}

/**
 * Check if the current request is for a staff order page.
 */
function maca_menulist_is_staff_orders_request() {
    if (defined('MACA_MENULIST_STAFF_PAGE_REQUEST') && MACA_MENULIST_STAFF_PAGE_REQUEST) {
        return true;
    }

    maca_menulist_bootstrap_staff_request_query_vars();
    // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Public routing via rewrite rules and query vars.
    if (isset($_GET['maca_staff_orders']) && sanitize_text_field(wp_unslash($_GET['maca_staff_orders'])) === '1') {
        return true;
    }

    if (isset($_GET['maca_staff_api']) && sanitize_text_field(wp_unslash($_GET['maca_staff_api'])) === '1') {
        return true;
    }
    // phpcs:enable WordPress.Security.NonceVerification.Recommended

    return (string) get_query_var('maca_staff_orders') === '1';
}

/**
 * Staff view from the current request: waiter or kitchen.
 */
function maca_menulist_get_staff_orders_view() {
    // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Public routing via rewrite rules and query vars.
    if (isset($_GET['maca_staff_view'])) {
        $view = sanitize_key(wp_unslash($_GET['maca_staff_view']));
        // phpcs:enable WordPress.Security.NonceVerification.Recommended
        return $view === 'kitchen' ? 'kitchen' : 'waiter';
    }
    // phpcs:enable WordPress.Security.NonceVerification.Recommended

    $view = sanitize_key((string) get_query_var('maca_staff_view'));

    return $view === 'kitchen' ? 'kitchen' : 'waiter';
}

/**
 * Force HTTPS for media URLs when the site is served over SSL.
 */
function maca_menulist_normalize_url($url) {
    if (empty($url)) {
        return '';
    }

    $url = trim($url);

    if (is_ssl() || wp_parse_url(home_url(), PHP_URL_SCHEME) === 'https') {
        return set_url_scheme($url, 'https');
    }

    return $url;
}

/**
 * Normalize menu object URLs for output.
 */
function maca_menulist_normalize_menu($menu) {
    if ($menu && !empty($menu->file_url)) {
        $menu->file_url = maca_menulist_normalize_url($menu->file_url);
    }

    return $menu;
}

/**
 * Normalize category object URLs for output.
 */
function maca_menulist_normalize_category($category) {
    if ($category && !empty($category->thumbnail_url)) {
        $category->thumbnail_url = maca_menulist_normalize_url($category->thumbnail_url);
    }

    return $category;
}

/**
 * Upgrade stored http:// media URLs to https:// in the database.
 */
function maca_menulist_migrate_http_urls() {
    if (wp_parse_url(home_url(), PHP_URL_SCHEME) !== 'https') {
        return;
    }

    $menus = maca_menulist_db_get_menus_with_http_file_urls();
    if ($menus) {
        foreach ($menus as $menu) {
            maca_menulist_db_update_menu_file_url(
                $menu->id,
                maca_menulist_normalize_url($menu->file_url)
            );
        }
    }

    $categories = maca_menulist_db_get_categories_with_http_thumbnails();
    if ($categories) {
        foreach ($categories as $category) {
            maca_menulist_db_update_category_thumbnail(
                $category->id,
                maca_menulist_normalize_url($category->thumbnail_url)
            );
        }
    }
}

add_action('parse_request', 'maca_menulist_parse_request_staff_routes', 0);
add_filter('pre_handle_404', 'maca_menulist_prevent_staff_route_404', 10, 2);
