<?php
/*
 * 我的订单页面
 */

$user_id = get_current_user_id();
$tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : 'all';
$type = isset($_GET['type']) ? sanitize_text_field($_GET['type']) : '';
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;

$status_map = array(
    'all'     => '',
    'pending' => 'pending',
    'paid'    => 'paid',
    'cancel'  => 'cancel',
    'closed'  => 'closed',
);
$current_status = isset($status_map[$tab]) ? $status_map[$tab] : '';

$base_nonce = wp_create_nonce('wp_rest');
$htmx_base = '/wp-json/ppo/v1/user-orders?_wpnonce=' . $base_nonce;

$tabs = array(
    'all'     => '全部订单',
    'pending' => '待支付',
    'paid'    => '已支付',
    'cancel'  => '已取消',
    'closed'  => '已关闭',
);

$filter_params = '';
if (!empty($type)) {
    $filter_params .= '&type=' . urlencode($type);
}

?>
<div id="order-detail-modal" uk-modal="esc-close:false;">
    <div class="uk-modal-dialog uk-modal-body order-detail-dialog uk-animation-scale-up uk-animation-fast uk-margin-auto-vertical">
        <button class="uk-modal-close-default" type="button" uk-close></button>
        <div class="order-detail-inner"></div>
    </div>
</div>

<div class="dash-order user-dash-box">
    <div class="user_order_info">
        <div class="order-tab dashboard-tab big-rounded">
            <?php foreach ($tabs as $key => $label) : ?>
                <?php
                $status_val = $status_map[$key];
                $api_query = 'tab=' . $key;
                if (!empty($type)) {
                    $api_query .= '&type=' . urlencode($type);
                }
                $api_url = $htmx_base . '&' . $api_query . '&page=1';
                $push_url = home_url('/dashboard/order?' . $api_query);
                $htmx = 'href="' . $push_url . '" '
                    . 'hx-get="' . $api_url . '" '
                    . 'hx-target=".order_record_list" '
                    . 'hx-swap="innerHTML" '
                    . 'hx-push-url="' . $push_url . '" '
                    . 'data-skeleton="normal-list" '
                    . 'hx-history="false"';
                $is_active = ($tab === $key);
                ?>
                <a <?php echo $htmx; ?> class="tab-item <?php echo $is_active ? 'active' : ''; ?>"><?php echo $label; ?></a>
            <?php endforeach; ?>
        </div>
        <div class="order_record_list">
            <?php echo user_orders_get_info($page, 10, array('status' => $current_status, 'type' => $type)); ?>
        </div>
    </div>
</div>
