<?php
/**
 * Takeaway menu channel, offering mode, and dish price helpers.
 *
 * @package Maca_Menu_List
 */

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

/**
 * Restaurant offering modes.
 *
 * @return array<int, string>
 */
function maca_menulist_get_offering_modes() {
    return array('dine_in_only', 'takeaway_only', 'both');
}

/**
 * Current offering mode (dine_in_only, takeaway_only, both).
 *
 * @return string
 */
function maca_menulist_get_offering_mode() {
    $mode = sanitize_key((string) get_option('maca_menulist_offering_mode', ''));

    if ($mode === '' && function_exists('maca_menulist_get_service_mode')) {
        $mode = maca_menulist_get_service_mode() === 'takeaway' ? 'takeaway_only' : 'dine_in_only';
    }

    if (!in_array($mode, maca_menulist_get_offering_modes(), true)) {
        return 'dine_in_only';
    }

    return $mode;
}

/**
 * Whether the restaurant only offers takeaway (stage 1 primary mode).
 *
 * @return bool
 */
function maca_menulist_offering_takeaway_only() {
    return maca_menulist_get_offering_mode() === 'takeaway_only';
}

/**
 * Whether the restaurant only offers dine-in.
 *
 * @return bool
 */
function maca_menulist_offering_dine_in_only() {
    return maca_menulist_get_offering_mode() === 'dine_in_only';
}

/**
 * Whether takeaway ordering channel is active.
 *
 * @return bool
 */
function maca_menulist_takeaway_ordering_enabled() {
    if (function_exists('maca_menulist_pro_has_feature') && !maca_menulist_pro_has_feature('takeaway')) {
        return false;
    }

    if (!function_exists('maca_menulist_table_order_enabled') || !maca_menulist_table_order_enabled()) {
        return false;
    }

    $mode = maca_menulist_get_offering_mode();

    return $mode === 'takeaway_only' || $mode === 'both';
}

/**
 * Whether table/QR ordering is active for dine-in guests.
 *
 * @return bool
 */
function maca_menulist_dine_in_ordering_enabled() {
    if (!function_exists('maca_menulist_table_order_enabled') || !maca_menulist_table_order_enabled()) {
        return false;
    }

    $mode = maca_menulist_get_offering_mode();

    return $mode === 'dine_in_only' || $mode === 'both';
}

/**
 * Guest order channel for the current page render.
 *
 * @return string dine_in|takeaway
 */
function maca_menulist_get_guest_order_channel() {
    $override = maca_menulist_get_guest_order_channel_override();
    if ($override !== null) {
        return $override;
    }

    if (function_exists('maca_menulist_is_takeaway_menu_request') && maca_menulist_is_takeaway_menu_request()) {
        return 'takeaway';
    }

    return 'dine_in';
}

/**
 * Override guest order channel for the current request (e.g. shortcode).
 *
 * @param string $channel dine_in|takeaway
 * @return void
 */
function maca_menulist_set_guest_order_channel($channel) {
    $GLOBALS['maca_menulist_guest_order_channel'] = sanitize_key($channel) === 'takeaway' ? 'takeaway' : 'dine_in';
}

/**
 * Read overridden guest order channel.
 *
 * @return string|null
 */
function maca_menulist_get_guest_order_channel_override() {
    if (!isset($GLOBALS['maca_menulist_guest_order_channel'])) {
        return null;
    }

    return $GLOBALS['maca_menulist_guest_order_channel'] === 'takeaway' ? 'takeaway' : 'dine_in';
}

/**
 * Resolved guest order channel including override.
 *
 * @return string dine_in|takeaway
 */
function maca_menulist_resolve_guest_order_channel() {
    $override = maca_menulist_get_guest_order_channel_override();

    if ($override !== null) {
        return $override;
    }

    return maca_menulist_get_guest_order_channel();
}

/**
 * Whether the current guest UI is takeaway (no table).
 *
 * @return bool
 */
function maca_menulist_is_takeaway_order_channel() {
    return maca_menulist_resolve_guest_order_channel() === 'takeaway';
}

/**
 * Public takeaway menu slug.
 *
 * @return string
 */
function maca_menulist_get_takeaway_slug() {
    $slug = get_option('maca_menulist_takeaway_slug', 'hamtmat');
    $slug = sanitize_title($slug);

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

    return $slug;
}

/**
 * Takeaway menu page URL.
 *
 * @return string
 */
function maca_menulist_get_takeaway_url() {
    return home_url('/' . maca_menulist_get_takeaway_slug() . '/');
}

/**
 * Page title on the public takeaway menu.
 *
 * @return string
 */
function maca_menulist_get_takeaway_guest_page_title() {
    $stored = trim((string) get_option('maca_menulist_takeaway_page_title', ''));

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

    if (function_exists('maca_menulist_guest_ui_string')) {
        return maca_menulist_guest_ui_string('Order takeaway');
    }

    return __('Order takeaway', 'maca-restu-pro');
}

/**
 * service_mode for new orders on the current channel.
 *
 * @return string dine_in|takeaway
 */
function maca_menulist_get_default_order_service_mode() {
    return maca_menulist_is_takeaway_order_channel() ? 'takeaway' : 'dine_in';
}

/**
 * service_mode stored on an order row.
 *
 * @param object $order Order row.
 * @return string dine_in|takeaway
 */
function maca_menulist_get_order_service_mode($order) {
    if (!empty($order->service_mode)) {
        $mode = sanitize_key((string) $order->service_mode);
        if (in_array($mode, maca_menulist_get_service_modes(), true)) {
            return $mode;
        }
    }

    return 'dine_in';
}

/**
 * Whether takeaway orders require payment before the kitchen can accept them.
 *
 * @return bool
 */
function maca_menulist_takeaway_prepayment_enabled() {
    if (!maca_menulist_takeaway_ordering_enabled()) {
        return false;
    }

    return function_exists('maca_menulist_payments_guest_flow_enabled')
        && maca_menulist_payments_guest_flow_enabled();
}

/**
 * Whether guests can place a new takeaway order (payments must be configured).
 *
 * @return bool
 */
function maca_menulist_takeaway_guest_ordering_allowed() {
    if (!maca_menulist_takeaway_ordering_enabled()) {
        return false;
    }

    return maca_menulist_takeaway_prepayment_enabled();
}

/**
 * Whether takeaway orders can be placed at the current time (opening hours).
 *
 * @return bool
 */
function maca_menulist_takeaway_accepting_orders_now() {
    if (!maca_menulist_takeaway_ordering_enabled()) {
        return false;
    }

    return function_exists('maca_menulist_is_restaurant_open_now')
        && maca_menulist_is_restaurant_open_now();
}

/**
 * Guest message when takeaway ordering is outside opening hours.
 *
 * @return string
 */
function maca_menulist_get_takeaway_outside_hours_notice() {
    if (!function_exists('maca_menulist_get_waitlist_hours_for_date')) {
        return maca_menulist_guest_ui_string('Takeaway is closed right now.');
    }

    $now = maca_menulist_booking_now();
    $date = $now->format('Y-m-d');
    $hours = maca_menulist_get_waitlist_hours_for_date($date);
    $exception = function_exists('maca_menulist_get_booking_exception_for_date')
        ? maca_menulist_get_booking_exception_for_date($date)
        : (function_exists('maca_menulist_db_get_booking_exception_for_date')
            ? maca_menulist_db_get_booking_exception_for_date($date)
            : null);
    $exception_type = $exception && isset($exception->exception_type)
        ? (string) $exception->exception_type
        : '';
    $schedule_text = function_exists('maca_menulist_format_opening_hours_schedule_text')
        ? maca_menulist_format_opening_hours_schedule_text($hours, $exception_type)
        : '';

    if (!empty($hours['note'])) {
        return (string) $hours['note'];
    }

    if (empty($hours['bookable']) || !empty($hours['closed'])) {
        return maca_menulist_guest_ui_string('Takeaway is closed right now. We are closed today.');
    }

    if ($schedule_text !== '') {
        return sprintf(
            maca_menulist_guest_ui_string('Takeaway is closed right now. Today\'s hours: %s.'),
            $schedule_text
        );
    }

    return maca_menulist_guest_ui_string('Takeaway is closed right now.');
}

/**
 * Output a notice when takeaway ordering is outside opening hours.
 *
 * @return void
 */
function maca_menulist_render_takeaway_hours_notice() {
    $message = maca_menulist_get_takeaway_outside_hours_notice();
    if ($message === '') {
        return;
    }

    echo '<div class="maca-opening-hours-notice maca-takeaway-hours-notice" role="status">';
    echo '<p class="maca-takeaway-hours-notice-text">' . esc_html($message) . '</p>';
    echo '</div>';
}

/**
 * Whether this order is takeaway and must be paid before kitchen/staff workflow.
 *
 * @param object $order Order row.
 * @return bool
 */
function maca_menulist_order_requires_takeaway_prepayment($order) {
    if (!$order || !maca_menulist_takeaway_prepayment_enabled()) {
        return false;
    }

    return maca_menulist_get_order_service_mode($order) === 'takeaway';
}

/**
 * Whether prepayment requirement is satisfied for a takeaway order.
 *
 * @param object $order Order row (with lines when totals matter).
 * @return bool
 */
function maca_menulist_order_takeaway_prepayment_satisfied($order) {
    if (!maca_menulist_order_requires_takeaway_prepayment($order)) {
        return true;
    }

    return function_exists('maca_menulist_order_is_payment_complete')
        && maca_menulist_order_is_payment_complete($order);
}

/**
 * Whether an order should appear on a staff board.
 *
 * @param object $order Order row.
 * @param string $view  Staff view: waiter or kitchen.
 * @return bool
 */
function maca_menulist_order_visible_on_staff_boards($order, $view = 'waiter') {
    $view = sanitize_key($view);

    if (!maca_menulist_order_requires_takeaway_prepayment($order)) {
        return true;
    }

    if (maca_menulist_order_takeaway_prepayment_satisfied($order)) {
        return true;
    }

    // Kitchen only sees takeaway after payment; waiter may register manual payment at the counter.
    if ($view === 'waiter' && function_exists('maca_menulist_payments_allow_manual') && maca_menulist_payments_allow_manual()) {
        return true;
    }

    return false;
}

/**
 * Whether kitchen must not act on an unpaid takeaway order.
 *
 * @param object $order Order row.
 * @return bool
 */
function maca_menulist_order_blocks_kitchen_until_prepayment($order) {
    return maca_menulist_order_requires_takeaway_prepayment($order)
        && !maca_menulist_order_takeaway_prepayment_satisfied($order);
}

/**
 * Filter staff board orders (hide unpaid takeaway from kitchen).
 *
 * @param array<int, object> $orders Orders with lines attached.
 * @param string           $view   Staff view: waiter or kitchen.
 * @return array<int, object>
 */
function maca_menulist_filter_orders_for_staff_boards($orders, $view = 'waiter') {
    if (empty($orders)) {
        return array();
    }

    $view = sanitize_key($view);

    return array_values(
        array_filter(
            $orders,
            static function ($order) use ($view) {
                if ($view === 'kitchen' && function_exists('maca_menulist_order_visible_on_kitchen_board')) {
                    return maca_menulist_order_visible_on_kitchen_board($order);
                }

                return maca_menulist_order_visible_on_staff_boards($order, $view);
            }
        )
    );
}

/**
 * Whether a dish is available on the takeaway channel (schedule + flag).
 *
 * @param object $dish Dish row.
 * @return bool
 */
function maca_menulist_dish_is_available_for_takeaway($dish) {
    if (empty($dish) || empty($dish->is_active)) {
        return false;
    }

    $takeaway_active = isset($dish->takeaway_active) ? (int) $dish->takeaway_active : 1;
    if ($takeaway_active !== 1) {
        return false;
    }

    if (!function_exists('maca_menulist_dish_is_visible_on_qr')) {
        return true;
    }

    return maca_menulist_dish_is_visible_on_qr($dish);
}

/**
 * Raw price for a dish on a channel (null when unset).
 *
 * @param object $dish    Dish row.
 * @param string $channel dine_in|takeaway
 * @return float|null
 */
function maca_menulist_get_dish_price_raw($dish, $channel = 'dine_in') {
    if (!$dish) {
        return null;
    }

    $channel = sanitize_key($channel) === 'takeaway' ? 'takeaway' : 'dine_in';

    if ($channel === 'takeaway') {
        if (isset($dish->price_takeaway) && $dish->price_takeaway !== null && $dish->price_takeaway !== '') {
            return (float) $dish->price_takeaway;
        }

        if (isset($dish->price) && $dish->price !== null && $dish->price !== '') {
            return (float) $dish->price;
        }

        return null;
    }

    if (isset($dish->price) && $dish->price !== null && $dish->price !== '') {
        return (float) $dish->price;
    }

    return null;
}

/**
 * Formatted dish price for display on a channel.
 *
 * @param object $dish    Dish row.
 * @param string $channel dine_in|takeaway
 * @return string
 */
function maca_menulist_get_dish_price_label($dish, $channel = 'dine_in') {
    $raw = maca_menulist_get_dish_price_raw($dish, $channel);

    return $raw !== null ? maca_menulist_format_price($raw) : '';
}

/**
 * Sanitize offering mode for storage.
 *
 * @param mixed $mode Raw value.
 * @return string
 */
function maca_menulist_sanitize_offering_mode($mode) {
    $mode = sanitize_key((string) $mode);

    if (!in_array($mode, maca_menulist_get_offering_modes(), true)) {
        return 'dine_in_only';
    }

    return $mode;
}

/**
 * Sync legacy service_mode option from offering mode.
 *
 * @param string $offering_mode dine_in_only|takeaway_only|both
 * @return void
 */
function maca_menulist_sync_service_mode_from_offering($offering_mode) {
    if ($offering_mode === 'takeaway_only') {
        update_option('maca_menulist_service_mode', 'takeaway');
        return;
    }

    if ($offering_mode === 'dine_in_only') {
        update_option('maca_menulist_service_mode', 'dine_in');
    }
}

/**
 * Migrate offering_mode option from legacy service_mode once.
 *
 * @return void
 */
function maca_menulist_maybe_migrate_offering_mode_option() {
    if (get_option('maca_menulist_offering_mode_migrated', '') === '1') {
        return;
    }

    $existing = get_option('maca_menulist_offering_mode', '');
    if ($existing !== '') {
        update_option('maca_menulist_offering_mode_migrated', '1', false);
        return;
    }

    $legacy = sanitize_key((string) get_option('maca_menulist_service_mode', 'dine_in'));
    $offering = $legacy === 'takeaway' ? 'takeaway_only' : 'dine_in_only';
    update_option('maca_menulist_offering_mode', $offering, false);
    update_option('maca_menulist_offering_mode_migrated', '1', false);
}

add_action('init', 'maca_menulist_maybe_migrate_offering_mode_option', 4);

/**
 * Pickup name/phone fields in the guest order panel (takeaway channel).
 *
 * @return void
 */
function maca_menulist_render_takeaway_pickup_fields() {
    echo '<label class="maca-table-order-field" for="maca-table-order-pickup-name">';
    echo '<span>' . esc_html(maca_menulist_guest_ui_string('Name for pickup')) . '</span>';
    echo '<input type="text" id="maca-table-order-pickup-name" class="maca-table-order-pickup-name" autocomplete="name">';
    echo '</label>';

    echo '<label class="maca-table-order-field" for="maca-table-order-pickup-phone">';
    echo '<span>' . esc_html(maca_menulist_guest_ui_string('Phone')) . '</span>';
    echo '<input type="tel" id="maca-table-order-pickup-phone" class="maca-table-order-pickup-phone" autocomplete="tel">';
    echo '</label>';
}
