<?php
/**
 * Minimal staff board API bootstrap (avoids loading the full plugin stack on POST).
 *
 * @package Maca_Menu_List
 */

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

/**
 * Load only the PHP files required for staff board JSON API handlers.
 *
 * @return void
 */
function maca_menulist_load_staff_api_minimal_stack() {
    static $loaded = false;

    if ($loaded) {
        return;
    }

    $loaded = true;
    $dir = MACA_MENULIST_PLUGIN_DIR . 'includes/';

    require_once $dir . 'rewrites.php';
    require_once $dir . 'pro/features.php';
    require_once $dir . 'pro/license.php';
    require_once $dir . 'dishes.php';
    require_once $dir . 'db.php';
    require_once $dir . 'db-waiters.php';
    require_once $dir . 'db-table-orders.php';
    require_once $dir . 'table-orders.php';
    require_once $dir . 'waiters.php';
    require_once $dir . 'takeaway.php';
    require_once $dir . 'staff-rest.php';
}

/**
 * Staff board POST actions that can be served from the minimal stack.
 *
 * @return string[]
 */
function maca_menulist_get_staff_fast_api_actions() {
    return array(
        'maca_verify_staff_pin',
        'maca_get_staff_table_summary',
        'maca_get_staff_orders',
        'maca_handle_staff_order',
        'maca_update_staff_order_table',
    );
}

/**
 * Try to answer staff board POST before the full plugin boots.
 *
 * @return void
 */
function maca_menulist_try_staff_api_fast_path() {
    // Minimal stack before full boot caused HTTP 500 on shared hosting; use early_dispatch instead.
    return;

    if (strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? 'GET')) !== 'POST') {
        return;
    }

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

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

    if (!defined('MACA_MENULIST_STAFF_API_REQUEST') || !MACA_MENULIST_STAFF_API_REQUEST) {
        return;
    }

    if (!function_exists('maca_menulist_early_is_staff_page_request')
        || !maca_menulist_early_is_staff_page_request()) {
        return;
    }

    $action = function_exists('maca_menulist_early_staff_post_action')
        ? maca_menulist_early_staff_post_action()
        : '';

    if ($action === '' || !in_array($action, maca_menulist_get_staff_fast_api_actions(), true)) {
        return;
    }

    maca_menulist_load_staff_api_minimal_stack();

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

    try {
        maca_menulist_maybe_early_dispatch_staff_post();
    } catch (Throwable $fast_path_error) {
        if (function_exists('maca_menulist_debug_log')) {
            maca_menulist_debug_log(
                'staff fast path error: ' . $fast_path_error->getMessage() . ' @ ' . $fast_path_error->getFile() . ':' . $fast_path_error->getLine()
            );
        }
    }
}

add_action('plugins_loaded', 'maca_menulist_try_staff_api_fast_path', 0);
