<?php
$pageTitle = '我的物流订单';
require_once dirname(__DIR__) . '/config.php';
requireLogin();

$pdo = getDB();

// Fetch device orders with items
$stmt = $pdo->prepare("
    SELECT do.*, 
           GROUP_CONCAT(d.name ORDER BY d.id SEPARATOR ', ') AS items
    FROM device_orders do
    LEFT JOIN device_order_items doi ON do.id = doi.device_order_id
    LEFT JOIN devices d ON doi.device_id = d.id
    WHERE do.user_id = ?
    GROUP BY do.id
    ORDER BY do.created_at DESC
");
$stmt->execute([$_SESSION['user_id']]);
$orders = $stmt->fetchAll();

require_once dirname(__DIR__) . '/includes/header.php';

$status_map = [
    'pending'   => ['label' => '待支付',  'color' => 'secondary', 'icon' => 'clock'],
    'paid'      => ['label' => '已支付',  'color' => 'info',      'icon' => 'check-circle'],
    'shipped'   => ['label' => '已发货',  'color' => 'primary',   'icon' => 'truck'],
    'completed' => ['label' => '已完成',  'color' => 'success',   'icon' => 'check-double'],
    'cancelled' => ['label' => '已取消',  'color' => 'danger',    'icon' => 'times-circle'],
];
?>

<div class="container py-4">
    <div class="row">
        <div class="col-md-3"><?php include 'sidebar.php'; ?></div>
        <div class="col-md-9">
            <div class="card border-0 shadow-sm">
                <div class="card-body p-4">
                    <h5 class="fw-bold mb-4"><i class="fas fa-truck me-2 text-primary"></i>我的物流订单</h5>

                    <?php if (empty($orders)): ?>
                    <div class="text-center text-muted py-5">
                        <i class="fas fa-truck fa-3x mb-3 opacity-25"></i>
                        <p class="mb-3">暂无物流订单</p>
                        <a href="/devices.php" class="btn btn-primary">
                            <i class="fas fa-shopping-cart me-2"></i>购买实体设备
                        </a>
                    </div>
                    <?php else: ?>

                    <?php foreach ($orders as $order):
                        $s = $status_map[$order['status']] ?? ['label'=>$order['status'],'color'=>'secondary','icon'=>'question'];
                    ?>
                    <div class="card border mb-4">
                        <div class="card-header bg-light d-flex justify-content-between align-items-center py-2 px-3">
                            <div>
                                <span class="font-monospace small fw-semibold text-muted">订单号：</span>
                                <span class="font-monospace small fw-bold"><?php echo e($order['order_number']); ?></span>
                            </div>
                            <div class="d-flex align-items-center gap-2">
                                <span class="badge bg-<?php echo $s['color']; ?>">
                                    <i class="fas fa-<?php echo $s['icon']; ?> me-1"></i><?php echo $s['label']; ?>
                                </span>
                                <span class="text-muted small"><?php echo date('Y-m-d H:i', strtotime($order['created_at'])); ?></span>
                            </div>
                        </div>
                        <div class="card-body p-3">
                            <div class="row g-3">
                                <!-- Items & amount -->
                                <div class="col-md-6">
                                    <div class="small text-muted mb-1">购买商品</div>
                                    <div class="fw-semibold"><?php echo e($order['items'] ?? '—'); ?></div>
                                    <div class="small text-muted mt-1">
                                        金额：<strong class="text-primary">$<?php echo number_format($order['total_amount'],2); ?> USD</strong>
                                    </div>
                                    <?php if (!empty($order['ship_name'])): ?>
                                    <div class="small text-muted mt-1">
                                        <i class="fas fa-map-marker-alt text-danger me-1"></i>
                                        <?php echo e($order['ship_name']); ?> &nbsp;
                                        <?php echo e(($order['ship_province']??'').' '.($order['ship_city']??'').' '.($order['ship_address']??'')); ?>
                                    </div>
                                    <?php endif; ?>
                                </div>

                                <!-- Tracking info -->
                                <div class="col-md-6">
                                    <div class="small text-muted mb-1">物流信息</div>
                                    <?php if (!empty($order['tracking_number'])): ?>
                                    <div class="d-flex align-items-center gap-2 mb-1">
                                        <i class="fas fa-truck text-primary"></i>
                                        <span class="fw-semibold"><?php echo e($order['tracking_carrier'] ?? '快递'); ?></span>
                                    </div>
                                    <div class="font-monospace fw-bold text-primary mb-1">
                                        <?php echo e($order['tracking_number']); ?>
                                    </div>
                                    <?php if (!empty($order['tracking_url'])): ?>
                                    <a href="<?php echo e($order['tracking_url']); ?>" target="_blank" class="btn btn-sm btn-outline-primary">
                                        <i class="fas fa-external-link-alt me-1"></i>查询物流
                                    </a>
                                    <?php endif; ?>
                                    <?php if (!empty($order['shipped_at'])): ?>
                                    <div class="small text-muted mt-1">发货时间：<?php echo date('Y-m-d H:i', strtotime($order['shipped_at'])); ?></div>
                                    <?php endif; ?>
                                    <?php else: ?>
                                    <div class="text-muted small">
                                        <?php if ($order['status'] === 'paid'): ?>
                                        <i class="fas fa-hourglass-half me-1 text-warning"></i>正在备货，即将发货
                                        <?php elseif ($order['status'] === 'pending'): ?>
                                        <i class="fas fa-clock me-1 text-secondary"></i>等待支付
                                        <?php else: ?>
                                        <i class="fas fa-minus me-1"></i>暂无物流信息
                                        <?php endif; ?>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Status timeline -->
                            <div class="mt-3 pt-3 border-top">
                                <div class="d-flex justify-content-between align-items-center">
                                    <?php
                                    $steps = [
                                        'pending'   => ['待支付', 'clock', 'secondary'],
                                        'paid'      => ['已支付', 'check-circle', 'info'],
                                        'shipped'   => ['已发货', 'truck', 'primary'],
                                        'completed' => ['已完成', 'check-double', 'success'],
                                    ];
                                    $stepOrder = array_keys($steps);
                                    $currentIdx = array_search($order['status'], $stepOrder);
                                    if ($currentIdx === false) $currentIdx = -1;
                                    foreach ($steps as $key => $step):
                                        $idx = array_search($key, $stepOrder);
                                        $done = $idx <= $currentIdx;
                                        $active = $idx === $currentIdx;
                                    ?>
                                    <div class="text-center flex-fill">
                                        <div class="rounded-circle d-inline-flex align-items-center justify-content-center mb-1"
                                             style="width:32px;height:32px;background:<?php echo $done ? ($active?'#0d6efd':'#198754') : '#dee2e6'; ?>;">
                                            <i class="fas fa-<?php echo $step[1]; ?> text-white small"></i>
                                        </div>
                                        <div class="small <?php echo $done?'fw-semibold':'text-muted'; ?>"><?php echo $step[0]; ?></div>
                                    </div>
                                    <?php if ($key !== 'completed'): ?>
                                    <div class="flex-fill" style="height:2px;background:<?php echo ($idx < $currentIdx)?'#198754':'#dee2e6'; ?>;margin-bottom:20px;"></div>
                                    <?php endif; ?>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>

                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<?php require_once dirname(__DIR__) . '/includes/footer.php'; ?>
