<?php
/**
 * 芋头CMS - 订单详情
 * $db 已由 member/index.php 引入
 */

require_once dirname(__DIR__, 2) . '/core/lib/order_timeout.php';

$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$memberId = isset($_SESSION['member_id']) ? intval($_SESSION['member_id']) : 0;

\Core\Lib\OrderTimeout::cancelExpiredPendingOrders($db);

if ($id <= 0 || $memberId <= 0) {
    header('Location: /member/index.php?page=myorder');
    exit;
}

$order = $db->fetch("SELECT * FROM {$db->table('order')} WHERE id = ? AND member_id = ?", [$id, $memberId]);
if (!$order) {
    echo '<div style="padding:40px;text-align:center;color:#EF4444;">订单不存在</div>';
    exit;
}

$goods = $db->fetchAll("SELECT * FROM {$db->table('order_product')} WHERE order_id = ?", [$id]);

$status_map = [
    '-1' => ['已取消', 'status-canceled'],
    '0' => ['待付款', 'status-pending'],
    '1' => ['已付款', 'status-paid'],
    '2' => ['已发货', 'status-shipped'],
    '3' => ['已完成', 'status-completed'],
    '4' => ['已取消', 'status-canceled'],
];
$s = isset($status_map[$order['status']]) ? $status_map[$order['status']] : ['未知', ''];
?>
<style>
.order-detail-page{padding:20px;}
.order-detail-page .page-header{margin-bottom:20px;}
.order-detail-page h1{font-size:20px;color:#1e293b;margin:0 0 16px 0;}
.order-detail-card{border:1px solid #e5e7eb;border-radius:12px;background:#fff;overflow:hidden;margin-bottom:20px;}
.order-detail-card .card-header{padding:16px 20px;border-bottom:1px solid #e5e7eb;display:flex;justify-content:space-between;align-items:center;}
.order-detail-card .card-header h3{margin:0;font-size:15px;font-weight:600;color:#1e293b;}
.order-detail-card .card-body{padding:20px;}
.order-info-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:16px;margin-bottom:20px;}
.order-info-item label{display:block;font-size:12px;color:#6b7280;margin-bottom:4px;}
.order-info-item .value{font-size:14px;color:#1e293b;font-weight:500;}
.goods-list{border-top:1px solid #e5e7eb;}
.goods-item{display:flex;gap:12px;padding:16px 0;border-bottom:1px solid #f1f5f9;}
.goods-item:last-child{border-bottom:none;}
.goods-item img{width:60px;height:60px;border-radius:8px;object-fit:cover;border:1px solid #e5e7eb;}
.goods-item .goods-info{flex:1;}
.goods-item .goods-title{font-size:14px;color:#1e293b;margin-bottom:4px;}
.goods-item .goods-meta{font-size:12px;color:#6b7280;}
.goods-item .goods-price{font-size:14px;color:#f5a623;font-weight:600;}
.order-total-row{display:flex;justify-content:flex-end;gap:20px;padding:16px 0;border-top:1px solid #e5e7eb;font-size:14px;}
.order-total-row .label{color:#6b7280;}
.order-total-row .value{font-weight:600;color:#1e293b;}
.order-total-row .value.highlight{color:#f5a623;font-size:18px;}
.btn-back{display:inline-flex;align-items:center;gap:6px;padding:10px 20px;background:#5a8f3e;color:#fff;border:none;border-radius:8px;font-size:14px;cursor:pointer;text-decoration:none;}
.btn-back:hover{background:#4a7a32;}
</style>

<div class="order-detail-page">
    <div class="page-header">
        <a href="?page=myorder" class="btn-back">← 返回订单列表</a>
    </div>

    <div class="order-detail-card">
        <div class="card-header">
            <h3>订单信息</h3>
            <span style="padding:4px 12px;border-radius:20px;font-size:12px;background:<?php echo $order['status'] == 0 ? '#fef3c7;color:#d97706' : ($order['status'] == 1 ? '#dbeafe;color:#2563eb' : ($order['status'] == 3 ? '#d1fae5;color:#059669' : '#f3f4f6;color:#6b7280')); ?>;"><?php echo $s[0]; ?></span>
        </div>
        <div class="card-body">
            <div class="order-info-grid">
                <div class="order-info-item">
                    <label>订单编号</label>
                    <div class="value"><?php echo htmlspecialchars($order['order_sn']); ?></div>
                </div>
                <div class="order-info-item">
                    <label>下单时间</label>
                    <div class="value"><?php echo date('Y-m-d H:i', $order['create_time']); ?></div>
                </div>
                <div class="order-info-item">
                    <label>收货人</label>
                    <div class="value"><?php echo htmlspecialchars($order['name'] ?? ''); ?></div>
                </div>
                <div class="order-info-item">
                    <label>联系电话</label>
                    <div class="value"><?php echo htmlspecialchars($order['mobile'] ?? ''); ?></div>
                </div>
                <div class="order-info-item" style="grid-column:1/-1;">
                    <label>收货地址</label>
                    <div class="value"><?php echo htmlspecialchars($order['address'] ?? ''); ?></div>
                </div>
            </div>
        </div>
    </div>

    <div class="order-detail-card">
        <div class="card-header">
            <h3>商品清单</h3>
        </div>
        <div class="card-body" style="padding:0 20px;">
            <div class="goods-list">
                <?php foreach ($goods as $g): ?>
                <div class="goods-item">
                    <img src="<?php echo htmlspecialchars($g['product_image'] ?: $g['litpic'] ?: '/template/agrismart/images/no-product.jpg'); ?>" alt="">
                    <div class="goods-info">
                        <div class="goods-title"><?php echo htmlspecialchars($g['product_title'] ?: $g['product_name']); ?></div>
                        <div class="goods-meta"><?php echo isset($g['specs']) && !empty($g['specs']) ? htmlspecialchars($g['specs']) . ' | ' : ''; ?> x <?php echo $g['quantity']; ?></div>
                        <?php if (intval($order['status']) === 3): ?>
                        <button type="button" class="btn-back" style="margin-top:8px;padding:6px 12px;font-size:12px;" onclick="submitReview(<?php echo intval($order['id']); ?>, <?php echo intval($g['product_id']); ?>)">评价</button>
                        <?php endif; ?>
                    </div>
                    <div class="goods-price">¥<?php echo number_format(floatval($g['total_price'] ?? $g['price'] * $g['quantity']), 2); ?></div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php $totalPrice = isset($order['total_price']) ? floatval($order['total_price']) : floatval($order['product_amount'] ?? 0); ?>
            <?php $payPrice = isset($order['pay_price']) ? floatval($order['pay_price']) : floatval($order['total_amount'] ?? 0); ?>
            <div class="order-total-row">
                <span class="label">商品金额：</span>
                <span class="value">¥<?php echo number_format($totalPrice, 2); ?></span>
                <span class="label">运费：</span>
                <span class="value">¥<?php echo number_format($payPrice - $totalPrice > 0 ? $payPrice - $totalPrice : 0, 2); ?></span>
                <span class="label">应付总额：</span>
                <span class="value highlight">¥<?php echo number_format($payPrice, 2); ?></span>
            </div>
        </div>
    </div>

    <?php
    $expressCompany = trim((string) ($order['express_company'] ?? ''));
    $expressNo = trim((string) (($order['express_no'] ?? '') !== '' ? $order['express_no'] : ($order['ship_no'] ?? '')));
    $shipTime = intval($order['delivery_time'] ?? 0) ?: intval($order['ship_time'] ?? 0);
    $shipNote = trim((string) ($order['ship_note'] ?? ''));
    ?>
    <div class="order-detail-card">
        <div class="card-header">
            <h3>物流信息</h3>
        </div>
        <div class="card-body">
            <div class="order-info-grid">
                <div class="order-info-item">
                    <label>快递公司</label>
                    <div class="value"><?php echo htmlspecialchars($expressCompany !== '' ? $expressCompany : '未发货'); ?></div>
                </div>
                <div class="order-info-item">
                    <label>物流单号</label>
                    <div class="value"><?php echo htmlspecialchars($expressNo !== '' ? $expressNo : '未填写'); ?></div>
                </div>
                <div class="order-info-item">
                    <label>发货时间</label>
                    <div class="value"><?php echo $shipTime > 0 ? date('Y-m-d H:i', $shipTime) : '-'; ?></div>
                </div>
                <div class="order-info-item" style="grid-column:1/-1;">
                    <label>发货备注</label>
                    <div class="value"><?php echo htmlspecialchars($shipNote !== '' ? $shipNote : '-'); ?></div>
                </div>
            </div>
        </div>
    </div>

    <?php if ($order['status'] == 0): ?>
    <div style="text-align:center;margin-top:20px;">
        <a href="/public/order/pay.php?order_id=<?php echo $order['id']; ?>" class="btn-back" style="padding:12px 40px;font-size:16px;">立即付款</a>
    </div>
    <?php elseif (in_array(intval($order['status']), [1, 2, 3], true)): ?>
    <div style="text-align:center;margin-top:20px;">
        <button type="button" class="btn-back" style="padding:12px 40px;font-size:16px;" onclick="applyRefund(<?php echo intval($order['id']); ?>)">申请退款</button>
        <a href="?page=refund" class="btn-back" style="padding:12px 24px;font-size:16px;background:#64748b;margin-left:8px;">查看售后</a>
    </div>
    <?php endif; ?>
</div>
<script>
function applyRefund(orderId) {
    var reason = prompt('请填写退款原因');
    if (reason === null) return;
    reason = reason.trim();
    if (!reason) { alert('请填写退款原因'); return; }
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/api/refund.php', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.setRequestHeader('X-CSRF-Token', <?php echo json_encode(getMemberCsrfToken()); ?>);
    xhr.onload = function() {
        try {
            var res = JSON.parse(xhr.responseText);
            alert(res.msg || '操作完成');
            if (res.code === 200) location.href = '?page=refund';
        } catch (e) {
            alert('提交失败');
        }
    };
    xhr.send('action=apply&order_id=' + encodeURIComponent(orderId) + '&reason=' + encodeURIComponent(reason) + '&csrf_token=' + encodeURIComponent(<?php echo json_encode(getMemberCsrfToken()); ?>));
}
function submitReview(orderId, productId) {
    var rating = prompt('请给商品评分（1-5）：', '5');
    if (rating === null) return;
    rating = parseInt(rating, 10);
    if (!rating || rating < 1 || rating > 5) { alert('评分必须是 1-5'); return; }
    var content = prompt('请填写评价内容：');
    if (content === null) return;
    content = content.trim();
    if (!content) { alert('请填写评价内容'); return; }
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/api/review.php', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.setRequestHeader('X-CSRF-Token', <?php echo json_encode(getMemberCsrfToken()); ?>);
    xhr.onload = function() {
        try {
            var res = JSON.parse(xhr.responseText);
            alert(res.msg || '操作完成');
        } catch (e) {
            alert('提交失败');
        }
    };
    xhr.send('action=submit&order_id=' + encodeURIComponent(orderId) + '&product_id=' + encodeURIComponent(productId) + '&rating=' + encodeURIComponent(rating) + '&content=' + encodeURIComponent(content) + '&csrf_token=' + encodeURIComponent(<?php echo json_encode(getMemberCsrfToken()); ?>));
}
</script>
