{include file="app/manage/view/index/emlog_nav"}

<input type="hidden" id="csrfToken" value="<?php echo $_SESSION['csrf_token'] ?? ''; ?>">

<h1 class="page-title">
    <i class="fas fa-receipt"></i>
    自营商城 · 订单详情
    <a href="index.php?r=manage/shop/order" class="btn btn-outline-secondary btn-sm ml-3"><i class="fas fa-arrow-left"></i> 返回</a>
</h1>

<?php if (!empty($errorMsg)): ?>
<div class="alert alert-warning"><?php echo htmlspecialchars($errorMsg); ?></div>
<?php else: ?>
<div class="card mb-4">
    <div class="card-header"><h5 class="mb-0"><i class="fas fa-info-circle"></i> 订单信息</h5></div>
    <div class="card-body">
        <div class="row">
            <div class="col-md-6">
                <p><strong>订单号：</strong><?php echo htmlspecialchars($order['order_no']); ?></p>
                <p><strong>用户：</strong><?php echo htmlspecialchars($order['nickname']); ?>（ID:<?php echo $order['uid']; ?>）</p>
                <p><strong>状态：</strong>
                    <?php
                    $cls = array('0'=>'badge-warning','1'=>'badge-info','2'=>'badge-primary','3'=>'badge-success','4'=>'badge-secondary')[$order['status']];
                    ?>
                    <span class="badge <?php echo $cls; ?>"><?php echo $order['status_text']; ?></span>
                </p>
                <p><strong>支付方式：</strong><?php echo $order['pay_type']==2 ? '余额支付' : '微信支付'; ?></p>
            </div>
            <div class="col-md-6">
                <p><strong>收件人：</strong><?php echo htmlspecialchars($order['addr']['addressee']); ?></p>
                <p><strong>手机号：</strong><?php echo htmlspecialchars($order['addr']['mobile']); ?></p>
                <p><strong>地址：</strong><?php echo htmlspecialchars($order['addr']['address']); ?></p>
                <p><strong>备注：</strong><?php echo htmlspecialchars($order['addr']['remark']); ?></p>
            </div>
        </div>
        <hr>
        <div class="row">
            <div class="col-md-4"><strong>订单总额：</strong><span class="text-danger font-weight-bold">¥<?php echo number_format($order['total_fee'], 2); ?></span></div>
            <div class="col-md-4"><strong>实付：</strong>¥<?php echo number_format($order['pay_fee'], 2); ?></div>
            <div class="col-md-4"><strong>余额抵扣：</strong>¥<?php echo number_format($order['balance_fee'], 2); ?></div>
        </div>
        <?php if ($order['express_no']): ?>
        <hr>
        <p><strong>物流：</strong><?php echo htmlspecialchars($order['express_type']); ?> / <?php echo htmlspecialchars($order['express_no']); ?>
            <?php if ($order['ship_time']): ?><small class="text-muted">（发货：<?php echo $order['ship_time']; ?>）</small><?php endif; ?>
        </p>
        <?php endif; ?>
    </div>
</div>

<div class="card">
    <div class="card-header"><h5 class="mb-0"><i class="fas fa-box"></i> 商品明细</h5></div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered">
                <thead class="thead-light">
                    <tr>
                        <th>商品</th>
                        <th class="w-110">单价</th>
                        <th class="w-80">数量</th>
                        <th class="w-110">小计</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach (($order['items'] ?: array()) as $it): ?>
                    <tr>
                        <td>
                            <?php if ($it['cover']): ?><img src="<?php echo htmlspecialchars($it['cover']); ?>" style="width:50px;height:50px;object-fit:cover;border-radius:4px;margin-right:8px;vertical-align:middle;"><?php endif; ?>
                            <?php echo htmlspecialchars($it['title']); ?>
                        </td>
                        <td>¥<?php echo number_format($it['price'], 2); ?></td>
                        <td><?php echo $it['num']; ?></td>
                        <td class="text-danger font-weight-bold">¥<?php echo number_format($it['price'] * $it['num'], 2); ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php if ($order['status'] == 1): ?>
<div class="mt-3">
    <button class="btn btn-success" onclick="ship(<?php echo $order['id']; ?>)"><i class="fas fa-truck"></i> 发货</button>
</div>
<?php endif; ?>
<?php if ($order['status'] == 0 || $order['status'] == 1): ?>
<div class="mt-2">
    <button class="btn btn-danger" onclick="cancel(<?php echo $order['id']; ?>)"><i class="fas fa-times"></i> 取消订单</button>
</div>
<?php endif; ?>
<?php endif; ?>

{include file="app/manage/view/index/emlog_footer"}

<div class="shop-modal d-none" id="shipModal">
    <div class="shop-modal-box">
        <div class="shop-modal-header"><i class="fas fa-truck mr-2"></i> 订单发货</div>
        <div class="shop-modal-body">
            <input type="hidden" id="shipId" value="<?php echo isset($order['id']) ? $order['id'] : 0; ?>">
            <div class="form-group"><label>快递公司</label><input type="text" class="form-control" id="expressType" placeholder="如：顺丰速运"></div>
            <div class="form-group"><label>快递单号</label><input type="text" class="form-control" id="expressNo" placeholder="快递单号"></div>
        </div>
        <div class="shop-modal-footer">
            <button class="btn btn-sm btn-secondary" onclick="closeShip()">取消</button>
            <button class="btn btn-sm btn-primary" id="shipBtn" onclick="doShip()">确认发货</button>
        </div>
    </div>
</div>

<style>
.shop-modal { position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,.45);z-index:10000;display:flex;align-items:center;justify-content:center; }
.shop-modal-box { background:#fff;width:420px;max-width:92%;border-radius:10px;overflow:hidden;box-shadow:0 12px 40px rgba(0,0,0,.25); }
.shop-modal-header { padding:14px 18px;font-weight:600;font-size:16px;border-bottom:1px solid #f0f0f0;background:#f8fafc; }
.shop-modal-body { padding:18px; }
.shop-modal-body .form-group { margin-bottom:14px; }
.shop-modal-footer { padding:12px 18px;border-top:1px solid #f0f0f0;text-align:right; }
.shop-modal-footer .btn { margin-left:8px; }
</style>

<script>
function ship(id) {
    document.getElementById('shipId').value = id;
    document.getElementById('expressType').value = '';
    document.getElementById('expressNo').value = '';
    var m = document.getElementById('shipModal');
    m.classList.remove('d-none'); m.style.display = 'flex';
}
function closeShip() {
    var m = document.getElementById('shipModal');
    m.style.display = 'none'; m.classList.add('d-none');
}
function doShip() {
    var id = document.getElementById('shipId').value;
    var type = document.getElementById('expressType').value.trim();
    var no = document.getElementById('expressNo').value.trim();
    if (!type || !no) { showToast('请填写快递公司与单号', 'danger'); return; }
    var token = document.getElementById('csrfToken').value;
    var btn = document.getElementById('shipBtn');
    btn.disabled = true; btn.textContent = '发货中...';
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'index.php?r=manage/shop/orderShip&_token=' + token, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            btn.disabled = false; btn.textContent = '确认发货';
            try { var r = JSON.parse(xhr.responseText);
                if (r.status === 'y') { showToast(r.info, 'success'); closeShip(); setTimeout(function(){ location.reload(); }, 800); }
                else showToast(r.info, 'danger');
            } catch(e) { showToast('响应异常', 'danger'); }
        }
    };
    xhr.send('id=' + id + '&express_type=' + encodeURIComponent(type) + '&express_no=' + encodeURIComponent(no));
}
function cancel(id) {
    if (!confirm('确定取消该订单？已支付将退回库存与余额')) return;
    var token = document.getElementById('csrfToken').value;
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'index.php?r=manage/shop/orderCancel&_token=' + token, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            try { var r = JSON.parse(xhr.responseText);
                if (r.status === 'y') { showToast(r.info, 'success'); setTimeout(function(){ location.reload(); }, 800); }
                else showToast(r.info, 'danger');
            } catch(e) { showToast('响应异常', 'danger'); }
        }
    };
    xhr.send('id=' + id);
}
function showToast(message, type) {
    type = type || 'success';
    var toast = document.createElement('div');
    toast.className = 'toast align-items-center text-white bg-' + type + ' border-0 position-fixed show';
    toast.setAttribute('role', 'alert');
    toast.style.cssText = 'top:20px;right:20px;z-index:9999;min-width:280px;opacity:1;transition:opacity .3s ease;';
    toast.innerHTML = '<div class="d-flex"><div class="toast-body"><i class="fas fa-' + (type==='success'?'check-circle':'exclamation-circle') + ' mr-2"></i>' + message + '</div><button type="button" class="btn-close btn-close-white me-2 m-auto" onclick="this.parentElement.parentElement.remove()"></button></div>';
    document.body.appendChild(toast);
    setTimeout(function(){ toast.style.opacity='0'; setTimeout(function(){ if(toast.parentNode) toast.parentNode.removeChild(toast); }, 350); }, 3000);
}
document.getElementById('shipModal').addEventListener('click', function(e){ if(e.target===this) closeShip(); });
</script>
