<?php
/**
 * Admin UI for table order history and cleanup.
 *
 * @package Maca_Menu_List
 */

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

/**
 * Table orders admin screen.
 */
class Maca_MenuList_Admin_Table_Orders {

    /**
     * Constructor.
     */
    public function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'), 21);
        add_action('admin_init', array($this, 'handle_actions'));
    }

    /**
     * Register submenu when dish mode and table orders are enabled.
     */
    public function add_admin_menu() {
        if (!maca_menulist_is_dishes_mode() || !maca_menulist_table_order_enabled()) {
            return;
        }

        add_submenu_page(
            'maca-restu',
            __('Beställningar', 'maca-restu-pro'),
            __('Beställningar', 'maca-restu-pro'),
            maca_menulist_admin_required_cap(),
            'maca-restu-orders',
            array($this, 'render_page')
        );
    }

    /**
     * Handle delete and purge actions.
     */
    public function handle_actions() {
        if (!isset($_POST['maca_orders_action'])) {
            return;
        }

        if (!isset($_POST['maca_orders_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['maca_orders_nonce'])), 'maca_orders')) {
            return;
        }

        if (!maca_menulist_user_can_manage_plugin()) {
            return;
        }

        if (!maca_menulist_is_dishes_mode() || !maca_menulist_table_order_enabled()) {
            return;
        }

        $action = sanitize_key(wp_unslash($_POST['maca_orders_action']));
        $heavy_actions = array('delete_selected', 'close_staff_board', 'delete_staff_board', 'purge_old');
        if (in_array($action, $heavy_actions, true)) {
            $this->prepare_heavy_order_action();
        }

        if ($action === 'delete_selected') {
            $ids = isset($_POST['order_ids']) ? array_map('absint', (array) wp_unslash($_POST['order_ids'])) : array();
            $ids = array_filter($ids);
            $deleted = maca_menulist_db_delete_table_orders($ids);

            add_settings_error(
                'maca_orders',
                'deleted',
                sprintf(
                    /* translators: %d: number of orders deleted */
                    _n('%d order deleted from the database.', '%d orders deleted from the database.', $deleted, 'maca-restu-pro'),
                    $deleted
                ),
                'success'
            );
            return;
        }

        if ($action === 'close_staff_board') {
            $days = isset($_POST['staff_board_days']) ? absint(wp_unslash($_POST['staff_board_days'])) : 0;
            $closed = maca_menulist_db_close_staff_board_orders($days);

            add_settings_error(
                'maca_orders',
                'staff_board_closed',
                sprintf(
                    /* translators: %d: number of orders closed */
                    _n(
                        '%d open order was closed and removed from the staff screen.',
                        '%d open orders were closed and removed from the staff screen.',
                        $closed,
                        'maca-restu-pro'
                    ),
                    $closed
                ),
                $closed > 0 ? 'success' : 'info'
            );
            return;
        }

        if ($action === 'delete_staff_board') {
            $days = isset($_POST['staff_board_days']) ? absint(wp_unslash($_POST['staff_board_days'])) : 0;
            $deleted = maca_menulist_db_delete_staff_board_orders($days);

            add_settings_error(
                'maca_orders',
                'staff_board_deleted',
                sprintf(
                    /* translators: %d: number of orders deleted */
                    _n(
                        '%d open order was deleted from the database.',
                        '%d open orders were deleted from the database.',
                        $deleted,
                        'maca-restu-pro'
                    ),
                    $deleted
                ),
                $deleted > 0 ? 'success' : 'info'
            );
            return;
        }

        if ($action === 'purge_old') {
            $days = isset($_POST['purge_days']) ? absint(wp_unslash($_POST['purge_days'])) : 0;
            if ($days < 1) {
                add_settings_error(
                    'maca_orders',
                    'purge_invalid',
                    __('Enter how many days old completed orders must be before deletion.', 'maca-restu-pro'),
                    'error'
                );
                return;
            }

            $deleted = maca_menulist_db_delete_old_completed_table_orders($days);
            add_settings_error(
                'maca_orders',
                'purged',
                sprintf(
                    /* translators: 1: number deleted, 2: days */
                    _n(
                        '%1$d completed order older than %2$d days was deleted.',
                        '%1$d completed orders older than %2$d days were deleted.',
                        $deleted,
                        'maca-restu-pro'
                    ),
                    $deleted,
                    $days
                ),
                $deleted > 0 ? 'success' : 'info'
            );
            return;
        }

        if ($action === 'save_auto_purge') {
            $enabled = !empty($_POST['orders_purge_enabled']);
            $days = isset($_POST['orders_purge_days']) ? absint(wp_unslash($_POST['orders_purge_days'])) : 90;
            $time = isset($_POST['orders_purge_time']) ? sanitize_text_field(wp_unslash($_POST['orders_purge_time'])) : '04:00';

            if ($days < 1) {
                add_settings_error(
                    'maca_orders',
                    'auto_purge_invalid',
                    __('Retention must be at least 1 day.', 'maca-restu-pro'),
                    'error'
                );
                return;
            }

            maca_menulist_orders_purge_save_settings($enabled, $days, $time);

            add_settings_error(
                'maca_orders',
                'auto_purge_saved',
                __('Automatic order cleanup settings saved.', 'maca-restu-pro'),
                'success'
            );
        }
    }

    /**
     * Raise limits before bulk order cleanup on shared hosting.
     */
    private function prepare_heavy_order_action() {
        if (function_exists('wp_raise_memory_limit')) {
            wp_raise_memory_limit('admin');
        }

        if (function_exists('set_time_limit')) {
            @set_time_limit(120);
        }
    }

    /**
     * Render list or detail view.
     */
    public function render_page() {
        if (!maca_menulist_user_can_manage_plugin()) {
            return;
        }

        if (!maca_menulist_pro_has_feature('table_orders')) {
            echo maca_menulist_pro_locked_notice('table_orders'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            return;
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only view switch.
        $action = isset($_GET['action']) ? sanitize_key(wp_unslash($_GET['action'])) : 'list';
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only detail view.
        $order_id = isset($_GET['order_id']) ? absint(wp_unslash($_GET['order_id'])) : 0;

        if ($action === 'view' && $order_id > 0) {
            $this->render_detail_page($order_id);
            return;
        }

        $this->render_list_page();
    }

    /**
     * Staff-board bulk cleanup (shown at top of orders list).
     */
    private function render_staff_board_cleanup_card() {
        ?>
        <div class="maca-orders-purge maca-orders-purge--staff card" id="maca-staff-board-cleanup" data-maca-restu-version="<?php echo esc_attr(MACA_MENULIST_VERSION); ?>">
            <h2>
                <?php esc_html_e('Clear open orders from staff screen', 'maca-restu-pro'); ?>
                <span class="maca-orders-version"><?php echo esc_html('maca Restu Pro ' . MACA_MENULIST_VERSION); ?></span>
            </h2>
            <p><?php esc_html_e('Close or delete orders that still appear on the waiter board (new, in progress, ready, served, or paid). Use this to clear old test orders. Closing is recommended; deletion is permanent.', 'maca-restu-pro'); ?></p>
            <p>
                <label for="maca_staff_board_days"><?php esc_html_e('Only orders older than', 'maca-restu-pro'); ?></label>
                <input type="number" min="0" step="1" name="staff_board_days" id="maca_staff_board_days" value="0" class="small-text" form="maca-close-staff-board-form" />
                <?php esc_html_e('days (0 = all open orders on the staff screen)', 'maca-restu-pro'); ?>
            </p>
            <form id="maca-close-staff-board-form" method="post" action="" style="display:inline-block;margin-right:8px;" onsubmit="return confirm('<?php echo esc_js(__('Close matching open orders? They will disappear from the waiter screen.', 'maca-restu-pro')); ?>');">
                <?php wp_nonce_field('maca_orders', 'maca_orders_nonce'); ?>
                <input type="hidden" name="maca_orders_action" value="close_staff_board" />
                <?php submit_button(__('Close open staff orders', 'maca-restu-pro'), 'secondary', 'submit', false); ?>
            </form>
            <form method="post" action="" style="display:inline-block;" onsubmit="return confirm('<?php echo esc_js(__('Permanently delete matching open orders? This cannot be undone.', 'maca-restu-pro')); ?>');">
                <?php wp_nonce_field('maca_orders', 'maca_orders_nonce'); ?>
                <input type="hidden" name="maca_orders_action" value="delete_staff_board" />
                <input type="hidden" name="staff_board_days" value="0" id="maca_staff_board_days_delete" />
                <?php submit_button(__('Delete open staff orders', 'maca-restu-pro'), 'delete', 'submit', false); ?>
            </form>
        </div>
        <?php
    }

    /**
     * Order list with filters and bulk delete.
     */
    private function render_list_page() {
        // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Filter UI only.
        $status_filter = isset($_GET['status_filter']) ? sanitize_key(wp_unslash($_GET['status_filter'])) : 'all';
        $older_than_days = isset($_GET['older_than_days']) ? max(0, absint(wp_unslash($_GET['older_than_days']))) : 0;
        $paged = isset($_GET['paged']) ? max(1, absint(wp_unslash($_GET['paged']))) : 1;
        // phpcs:enable WordPress.Security.NonceVerification.Recommended

        $allowed_filters = array_merge(array('all', 'active', 'completed'), maca_menulist_get_table_order_statuses());
        if (!in_array($status_filter, $allowed_filters, true)) {
            $status_filter = 'all';
        }

        $per_page = 20;
        $query_args = array(
            'status_filter'   => $status_filter,
            'older_than_days' => $older_than_days,
            'paged'           => $paged,
            'per_page'        => $per_page,
            'attach_lines'    => false,
        );

        $total = maca_menulist_db_count_table_orders($query_args);
        $orders = maca_menulist_db_list_table_orders($query_args);
        $total_pages = max(1, (int) ceil($total / $per_page));
        $currency = maca_menulist_get_price_currency();
        $list_url = admin_url('admin.php?page=maca-restu-orders');
        $purge_enabled = maca_menulist_orders_purge_enabled();
        $purge_days_default = maca_menulist_orders_purge_get_days();
        $purge_time = maca_menulist_orders_purge_get_daily_time();
        $purge_last_run = get_option('maca_menulist_orders_purge_last_run', '');
        $purge_last_count = (int) get_option('maca_menulist_orders_purge_last_count', 0);
        $purge_next_run = wp_next_scheduled(MACA_MENULIST_ORDERS_PURGE_CRON_HOOK);

        settings_errors('maca_orders');
        ?>
        <div class="wrap maca-orders-wrap">
            <h1 class="wp-heading-inline"><?php esc_html_e('Order', 'maca-restu-pro'); ?></h1>
            <hr class="wp-header-end" />

            <p class="description">
                <?php esc_html_e('Browse guest table orders stored in the database. Delete individual orders or clean up old completed orders.', 'maca-restu-pro'); ?>
            </p>
            <p>
                <a href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-payment-history')); ?>">
                    <?php esc_html_e('Open payment history', 'maca-restu-pro'); ?>
                </a>
            </p>

            <?php $this->render_staff_board_cleanup_card(); ?>

            <form method="get" action="" class="maca-orders-filter">
                <input type="hidden" name="page" value="maca-restu-orders" />
                <label for="maca_orders_status_filter"><?php esc_html_e('Status', 'maca-restu-pro'); ?></label>
                <select name="status_filter" id="maca_orders_status_filter">
                    <option value="all" <?php selected($status_filter, 'all'); ?>><?php esc_html_e('All orders', 'maca-restu-pro'); ?></option>
                    <option value="active" <?php selected($status_filter, 'active'); ?>><?php esc_html_e('Active (on staff boards)', 'maca-restu-pro'); ?></option>
                    <option value="completed" <?php selected($status_filter, 'completed'); ?>><?php esc_html_e('Completed', 'maca-restu-pro'); ?></option>
                    <?php foreach (maca_menulist_get_table_order_statuses() as $status_key) : ?>
                        <option value="<?php echo esc_attr($status_key); ?>" <?php selected($status_filter, $status_key); ?>>
                            <?php echo esc_html(maca_menulist_get_table_order_status_label($status_key)); ?>
                        </option>
                    <?php endforeach; ?>
                </select>

                <label for="maca_orders_older_than"><?php esc_html_e('Older than (days)', 'maca-restu-pro'); ?></label>
                <input type="number" min="0" step="1" name="older_than_days" id="maca_orders_older_than" value="<?php echo esc_attr((string) $older_than_days); ?>" class="small-text" />
                <span class="description"><?php esc_html_e('0 = any age', 'maca-restu-pro'); ?></span>

                <?php submit_button(__('Filter', 'maca-restu-pro'), 'secondary', '', false); ?>
            </form>

            <form method="post" action="" onsubmit="return confirm('<?php echo esc_js(__('Delete selected orders from the database?', 'maca-restu-pro')); ?>');">
                <?php wp_nonce_field('maca_orders', 'maca_orders_nonce'); ?>
                <input type="hidden" name="maca_orders_action" value="delete_selected" />

                <div class="tablenav top">
                    <div class="alignleft actions bulkactions">
                        <?php submit_button(__('Delete selected', 'maca-restu-pro'), 'delete', 'submit', false); ?>
                    </div>
                    <div class="tablenav-pages">
                        <span class="displaying-num">
                            <?php
                            printf(
                                /* translators: %s: number of orders */
                                esc_html(_n('%s order', '%s orders', $total, 'maca-restu-pro')),
                                esc_html(number_format_i18n($total))
                            );
                            ?>
                        </span>
                        <?php if ($total_pages > 1) : ?>
                            <?php
                            echo wp_kses_post(
                                paginate_links(
                                    array(
                                        'base'      => add_query_arg('paged', '%#%', $list_url),
                                        'format'    => '',
                                        'current'   => $paged,
                                        'total'     => $total_pages,
                                        'add_args'  => array(
                                            'status_filter'   => $status_filter,
                                            'older_than_days' => $older_than_days,
                                        ),
                                    )
                                )
                            );
                            ?>
                        <?php endif; ?>
                    </div>
                </div>

                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <td class="manage-column column-cb check-column">
                                <input type="checkbox" id="maca-orders-select-all" />
                            </td>
                            <th scope="col"><?php esc_html_e('ID', 'maca-restu-pro'); ?></th>
                            <th scope="col"><?php esc_html_e('Table', 'maca-restu-pro'); ?></th>
                            <th scope="col"><?php esc_html_e('Status', 'maca-restu-pro'); ?></th>
                            <th scope="col"><?php esc_html_e('Payment', 'maca-restu-pro'); ?></th>
                            <th scope="col"><?php esc_html_e('How paid', 'maca-restu-pro'); ?></th>
                            <th scope="col"><?php esc_html_e('Created', 'maca-restu-pro'); ?></th>
                            <th scope="col"><?php esc_html_e('Lines', 'maca-restu-pro'); ?></th>
                            <th scope="col"><?php esc_html_e('Total', 'maca-restu-pro'); ?></th>
                            <th scope="col"><?php esc_html_e('Actions', 'maca-restu-pro'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($orders)) : ?>
                            <tr>
                                <td colspan="10"><?php esc_html_e('No orders found.', 'maca-restu-pro'); ?></td>
                            </tr>
                        <?php else : ?>
                            <?php foreach ($orders as $order) : ?>
                                <tr>
                                    <th scope="row" class="check-column">
                                        <input type="checkbox" name="order_ids[]" value="<?php echo esc_attr((string) $order->id); ?>" />
                                    </th>
                                    <td><?php echo esc_html((string) $order->id); ?></td>
                                    <td><?php echo esc_html($order->table_number !== '' ? (string) $order->table_number : '—'); ?></td>
                                    <td><?php echo esc_html(maca_menulist_get_table_order_status_label((string) $order->status)); ?></td>
                                    <td><?php echo esc_html(maca_menulist_get_order_payment_status_label($order)); ?></td>
                                    <td><?php echo esc_html(maca_menulist_get_payment_method_label(isset($order->payment_method) ? (string) $order->payment_method : '')); ?></td>
                                    <td><?php echo esc_html(maca_menulist_format_order_datetime((string) $order->created_at)); ?></td>
                                    <td><?php echo esc_html((string) (int) $order->line_count); ?></td>
                                    <td><?php echo esc_html(maca_menulist_format_order_total((float) $order->order_total, $currency)); ?></td>
                                    <td>
                                        <a href="<?php echo esc_url(add_query_arg(array('action' => 'view', 'order_id' => (int) $order->id), $list_url)); ?>">
                                            <?php esc_html_e('View', 'maca-restu-pro'); ?>
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </form>

            <div class="maca-orders-purge card">
                <h2><?php esc_html_e('Automatic cleanup', 'maca-restu-pro'); ?></h2>
                <p><?php esc_html_e('Delete completed orders (served, paid, or guest left) automatically once per day. Only orders older than the retention period are removed.', 'maca-restu-pro'); ?></p>
                <form method="post" action="">
                    <?php wp_nonce_field('maca_orders', 'maca_orders_nonce'); ?>
                    <input type="hidden" name="maca_orders_action" value="save_auto_purge" />
                    <table class="form-table" role="presentation">
                        <tr>
                            <th scope="row"><?php esc_html_e('Enable automatic cleanup', 'maca-restu-pro'); ?></th>
                            <td>
                                <label>
                                    <input type="checkbox" name="orders_purge_enabled" value="1" <?php checked($purge_enabled); ?> />
                                    <?php esc_html_e('Run daily cleanup of old completed orders', 'maca-restu-pro'); ?>
                                </label>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="maca_orders_purge_days_setting"><?php esc_html_e('Retention (days)', 'maca-restu-pro'); ?></label></th>
                            <td>
                                <input type="number" min="1" step="1" name="orders_purge_days" id="maca_orders_purge_days_setting" value="<?php echo esc_attr((string) $purge_days_default); ?>" class="small-text" required />
                                <p class="description"><?php esc_html_e('Completed orders older than this many days are deleted automatically.', 'maca-restu-pro'); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="maca_orders_purge_time"><?php esc_html_e('Daily time', 'maca-restu-pro'); ?></label></th>
                            <td>
                                <input type="time" name="orders_purge_time" id="maca_orders_purge_time" value="<?php echo esc_attr($purge_time); ?>" />
                                <p class="description"><?php esc_html_e('Site timezone (Settings → General). Default: 04:00.', 'maca-restu-pro'); ?></p>
                            </td>
                        </tr>
                    </table>
                    <?php if ($purge_last_run) : ?>
                        <p class="description">
                            <?php
                            echo esc_html(
                                sprintf(
                                    /* translators: 1: datetime, 2: number deleted */
                                    __('Last automatic run: %1$s (%2$d orders deleted).', 'maca-restu-pro'),
                                    maca_menulist_format_order_datetime((string) $purge_last_run),
                                    (int) $purge_last_count
                                )
                            );
                            ?>
                        </p>
                    <?php endif; ?>
                    <?php if ($purge_enabled && $purge_next_run) : ?>
                        <p class="description">
                            <?php
                            printf(
                                /* translators: %s: datetime */
                                esc_html__('Next scheduled run: %s', 'maca-restu-pro'),
                                esc_html(maca_menulist_format_order_datetime(wp_date('Y-m-d H:i:s', $purge_next_run)))
                            );
                            ?>
                        </p>
                    <?php endif; ?>
                    <?php submit_button(__('Save automatic cleanup', 'maca-restu-pro')); ?>
                </form>
            </div>

            <div class="maca-orders-purge card">
                <h2><?php esc_html_e('Clean up completed orders now', 'maca-restu-pro'); ?></h2>
                <p><?php esc_html_e('Permanently delete completed orders (served, paid, or guest left) that are older than the number of days you enter. This cannot be undone.', 'maca-restu-pro'); ?></p>
                <form method="post" action="" onsubmit="return confirm('<?php echo esc_js(__('Delete all matching completed orders from the database?', 'maca-restu-pro')); ?>');">
                    <?php wp_nonce_field('maca_orders', 'maca_orders_nonce'); ?>
                    <input type="hidden" name="maca_orders_action" value="purge_old" />
                    <label for="maca_orders_purge_days"><?php esc_html_e('Delete completed orders older than', 'maca-restu-pro'); ?></label>
                    <input type="number" min="1" step="1" name="purge_days" id="maca_orders_purge_days" value="<?php echo esc_attr((string) $purge_days_default); ?>" class="small-text" required />
                    <?php esc_html_e('days', 'maca-restu-pro'); ?>
                    <?php submit_button(__('Delete old completed orders', 'maca-restu-pro'), 'delete secondary', 'submit', false); ?>
                </form>
            </div>
        </div>
        <script>
        document.getElementById('maca-orders-select-all')?.addEventListener('change', function () {
            document.querySelectorAll('.maca-orders-wrap input[name="order_ids[]"]').forEach(function (cb) {
                cb.checked = document.getElementById('maca-orders-select-all').checked;
            });
        });
        (function () {
            var daysInput = document.getElementById('maca_staff_board_days');
            var deleteDays = document.getElementById('maca_staff_board_days_delete');
            if (!daysInput || !deleteDays) {
                return;
            }
            var sync = function () {
                deleteDays.value = daysInput.value;
            };
            daysInput.addEventListener('input', sync);
            daysInput.addEventListener('change', sync);
            sync();
        })();
        </script>
        <?php
    }

    /**
     * Single order detail view.
     *
     * @param int $order_id Order ID.
     */
    private function render_detail_page($order_id) {
        $order = maca_menulist_db_get_table_order($order_id);
        if (!$order) {
            echo '<div class="wrap"><p>' . esc_html__('Order not found.', 'maca-restu-pro') . '</p></div>';
            return;
        }

        $orders = maca_menulist_db_attach_table_order_lines(array($order));
        $order = $orders[0];
        $currency = maca_menulist_get_price_currency();
        $list_url = admin_url('admin.php?page=maca-restu-orders');
        $total = 0.0;

        foreach ($order->lines as $line) {
            $price = isset($line->price) ? (float) $line->price : 0.0;
            $qty = isset($line->qty) ? (int) $line->qty : 1;
            $total += $price * $qty;
        }
        ?>
        <div class="wrap maca-orders-wrap">
            <h1>
                <?php
                printf(
                    /* translators: %d: order ID */
                    esc_html__('Order #%d', 'maca-restu-pro'),
                    (int) $order->id
                );
                ?>
            </h1>
            <p>
                <a href="<?php echo esc_url($list_url); ?>">&larr; <?php esc_html_e('Back to order list', 'maca-restu-pro'); ?></a>
            </p>

            <table class="form-table" role="presentation">
                <tr>
                    <th scope="row"><?php esc_html_e('Table', 'maca-restu-pro'); ?></th>
                    <td><?php echo esc_html($order->table_number !== '' ? (string) $order->table_number : '—'); ?></td>
                </tr>
                <tr>
                    <th scope="row"><?php esc_html_e('Status', 'maca-restu-pro'); ?></th>
                    <td><?php echo esc_html(maca_menulist_get_table_order_status_label((string) $order->status)); ?></td>
                </tr>
                <tr>
                    <th scope="row"><?php esc_html_e('Created', 'maca-restu-pro'); ?></th>
                    <td><?php echo esc_html(maca_menulist_format_order_datetime((string) $order->created_at)); ?></td>
                </tr>
                <?php if (!empty($order->handled_at)) : ?>
                    <tr>
                        <th scope="row"><?php esc_html_e('Closed', 'maca-restu-pro'); ?></th>
                        <td><?php echo esc_html(maca_menulist_format_order_datetime((string) $order->handled_at)); ?></td>
                    </tr>
                <?php endif; ?>
                <?php if (!empty($order->order_note)) : ?>
                    <tr>
                        <th scope="row"><?php esc_html_e('Order note', 'maca-restu-pro'); ?></th>
                        <td><?php echo esc_html((string) $order->order_note); ?></td>
                    </tr>
                <?php endif; ?>
            </table>

            <?php if (function_exists('maca_menulist_get_payment_status_label')) : ?>
                <h2><?php esc_html_e('Payment', 'maca-restu-pro'); ?></h2>
                <table class="form-table" role="presentation">
                    <tr>
                        <th scope="row"><?php esc_html_e('Payment status', 'maca-restu-pro'); ?></th>
                        <td><?php echo esc_html(maca_menulist_get_order_payment_status_label($order)); ?></td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e('How paid', 'maca-restu-pro'); ?></th>
                        <td><?php echo esc_html(maca_menulist_get_payment_method_label(isset($order->payment_method) ? (string) $order->payment_method : '')); ?></td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e('Provider', 'maca-restu-pro'); ?></th>
                        <td><?php echo esc_html(maca_menulist_get_payment_provider_label(isset($order->payment_provider) ? (string) $order->payment_provider : '')); ?></td>
                    </tr>
                    <?php if (function_exists('maca_menulist_get_order_tip_amount') && maca_menulist_get_order_tip_amount($order) > 0) : ?>
                        <tr>
                            <th scope="row"><?php esc_html_e('Tip', 'maca-restu-pro'); ?></th>
                            <td><?php echo esc_html(maca_menulist_format_price(maca_menulist_get_order_tip_amount($order))); ?></td>
                        </tr>
                    <?php endif; ?>
                    <?php
                    $payment_balance = maca_menulist_get_order_payment_balance($order);
                    if ($payment_balance['paid'] > 0) :
                        ?>
                        <tr>
                            <th scope="row"><?php esc_html_e('Amount paid', 'maca-restu-pro'); ?></th>
                            <td>
                                <?php
                                echo esc_html(
                                    maca_menulist_format_order_total(
                                        $payment_balance['paid'],
                                        isset($order->payment_currency) ? (string) $order->payment_currency : $currency
                                    )
                                );
                                if ($payment_balance['remaining'] > 0.009) {
                                    echo ' <span class="description">';
                                    echo esc_html(
                                        sprintf(
                                            /* translators: %s: remaining amount */
                                            __('(%s left)', 'maca-restu-pro'),
                                            maca_menulist_format_order_total(
                                                $payment_balance['remaining'],
                                                isset($order->payment_currency) ? (string) $order->payment_currency : $currency
                                            )
                                        )
                                    );
                                    echo '</span>';
                                }
                                ?>
                            </td>
                        </tr>
                    <?php endif; ?>
                    <?php if (!empty($order->paid_at)) : ?>
                        <tr>
                            <th scope="row"><?php esc_html_e('Paid at', 'maca-restu-pro'); ?></th>
                            <td><?php echo esc_html(maca_menulist_format_order_datetime((string) $order->paid_at)); ?></td>
                        </tr>
                    <?php endif; ?>
                    <?php
                    $payment_tx_state = function_exists('maca_menulist_build_order_payment_transactions_state')
                        ? maca_menulist_build_order_payment_transactions_state($order)
                        : array('count' => 0);
                    ?>
                    <?php if ($payment_tx_state['count'] > 0) : ?>
                        <tr>
                            <th scope="row"><?php esc_html_e('Payment transactions', 'maca-restu-pro'); ?></th>
                            <td>
                                <?php
                                if (function_exists('maca_menulist_render_order_payment_transactions_html')) {
                                    echo maca_menulist_render_order_payment_transactions_html($order); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                                }
                                ?>
                            </td>
                        </tr>
                    <?php elseif (!empty($order->payment_external_id)) : ?>
                        <tr>
                            <th scope="row"><?php esc_html_e('External payment ID', 'maca-restu-pro'); ?></th>
                            <td><code><?php echo esc_html((string) $order->payment_external_id); ?></code></td>
                        </tr>
                    <?php endif; ?>
                </table>
            <?php endif; ?>

            <h2><?php esc_html_e('Line items', 'maca-restu-pro'); ?></h2>
            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th scope="col"><?php esc_html_e('Dish', 'maca-restu-pro'); ?></th>
                        <th scope="col"><?php esc_html_e('Qty', 'maca-restu-pro'); ?></th>
                        <th scope="col"><?php esc_html_e('Price', 'maca-restu-pro'); ?></th>
                        <th scope="col"><?php esc_html_e('Note', 'maca-restu-pro'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($order->lines)) : ?>
                        <tr><td colspan="4"><?php esc_html_e('No line items.', 'maca-restu-pro'); ?></td></tr>
                    <?php else : ?>
                        <?php foreach ($order->lines as $line) : ?>
                            <tr>
                                <td><?php echo esc_html((string) $line->title); ?></td>
                                <td><?php echo esc_html((string) (int) $line->qty); ?></td>
                                <td>
                                    <?php
                                    echo esc_html(
                                        $line->price !== null && $line->price !== ''
                                            ? maca_menulist_format_order_total((float) $line->price, $currency)
                                            : '—'
                                    );
                                    ?>
                                </td>
                                <td><?php echo esc_html($line->line_note !== '' ? (string) $line->line_note : '—'); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
                <tfoot>
                    <tr>
                        <th scope="row" colspan="2"><?php esc_html_e('Total', 'maca-restu-pro'); ?></th>
                        <td colspan="2"><?php echo esc_html(maca_menulist_format_order_total($total, $currency)); ?></td>
                    </tr>
                </tfoot>
            </table>

            <form method="post" action="" style="margin-top:1rem;" onsubmit="return confirm('<?php echo esc_js(__('Delete this order from the database?', 'maca-restu-pro')); ?>');">
                <?php wp_nonce_field('maca_orders', 'maca_orders_nonce'); ?>
                <input type="hidden" name="maca_orders_action" value="delete_selected" />
                <input type="hidden" name="order_ids[]" value="<?php echo esc_attr((string) $order->id); ?>" />
                <?php submit_button(__('Delete this order', 'maca-restu-pro'), 'delete'); ?>
            </form>
        </div>
        <?php
    }
}

/**
 * Format order datetime for admin lists.
 *
 * @param string $datetime MySQL datetime.
 * @return string
 */
function maca_menulist_format_order_datetime($datetime) {
    return maca_menulist_format_wp_datetime($datetime);
}

/**
 * Format order total with currency.
 *
 * @param float  $amount   Amount.
 * @param string $currency Currency suffix.
 * @return string
 */
function maca_menulist_format_order_total($amount, $currency) {
    $formatted = number_format_i18n($amount, 2);

    if ($currency !== '') {
        return trim($formatted . ' ' . $currency);
    }

    return $formatted;
}
