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

$page     = max(1, intval($_GET['page'] ?? 1));
$per_page = 10;
$offset   = ($page - 1) * $per_page;

$total_count = (int)$pdo->prepare("SELECT COUNT(*) FROM orders WHERE user_id=?")->execute([$_SESSION['user_id']]) ? $pdo->query("SELECT COUNT(*) FROM orders WHERE user_id=" . intval($_SESSION['user_id']))->fetchColumn() : 0;
$countStmt = $pdo->prepare("SELECT COUNT(*) FROM orders WHERE user_id=?");
$countStmt->execute([$_SESSION['user_id']]);
$total_count = (int)$countStmt->fetchColumn();
$total_pages = max(1, ceil($total_count / $per_page));

$stmt = $pdo->prepare("
    SELECT o.*,
           p.name AS pkg_name, p.data_mb, p.days, p.continent, p.countries,
           e.euicc_number, e.nickname AS euicc_nickname
    FROM orders o
    LEFT JOIN packages p ON o.package_id = p.id
    LEFT JOIN euniccs e ON o.euicc_id = e.id
    WHERE o.user_id = ?
    ORDER BY o.created_at DESC
    LIMIT $per_page OFFSET $offset
");
$stmt->execute([$_SESSION['user_id']]);
$orders = $stmt->fetchAll();

$site_url = rtrim(getSetting('site_url') ?? '', '/');

require_once dirname(__DIR__) . '/includes/header.php';
?>
<style>
.user-layout{display:flex;gap:28px;max-width:960px;margin:0 auto;padding:32px 16px}
.user-main{flex:1;min-width:0}
.order-card{background:#fff;border:1px solid #e8e0f5;border-radius:16px;margin-bottom:22px;overflow:hidden;box-shadow:0 2px 12px rgba(80,40,120,.07);transition:box-shadow .2s}
.order-card:hover{box-shadow:0 6px 28px rgba(80,40,120,.15)}
.order-header{background:linear-gradient(135deg,#1a0533 0%,#4a1080 100%);color:#fff;padding:14px 22px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px}
.order-header .order-num{font-family:monospace;font-size:.88rem;opacity:.8}
.order-header .order-date{font-size:.78rem;opacity:.65}
.order-body{padding:22px}
.status-badge{display:inline-flex;align-items:center;gap:6px;padding:4px 14px;border-radius:20px;font-size:.8rem;font-weight:600}
.status-pending{background:#fff3cd;color:#856404}
.status-paid{background:#cff4fc;color:#055160}
.status-completed{background:#d1e7dd;color:#0a3622}
.status-refunded{background:#f8d7da;color:#842029}
.status-failed{background:#f8d7da;color:#842029}
.pkg-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(130px,1fr));gap:10px;margin-bottom:16px}
.pkg-item{background:#f8f5ff;border-radius:8px;padding:10px 14px}
.pkg-item .pi-label{font-size:.7rem;color:#888;margin-bottom:2px}
.pkg-item .pi-value{font-weight:700;font-size:.92rem;color:#1a0533}
/* Timeline */
.timeline{display:flex;align-items:center;margin:16px 0 0}
.tl-step{flex:1;text-align:center;position:relative}
.tl-step:not(:last-child)::after{content:'';position:absolute;top:15px;left:50%;width:100%;height:2px;background:#dee2e6;z-index:0}
.tl-step.done:not(:last-child)::after{background:#198754}
.tl-dot{width:32px;height:32px;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;font-size:.75rem;position:relative;z-index:1;border:2px solid #dee2e6;background:#fff;color:#aaa}
.tl-step.done .tl-dot{background:#198754;border-color:#198754;color:#fff}
.tl-step.active .tl-dot{background:#0d6efd;border-color:#0d6efd;color:#fff}
.tl-label{font-size:.7rem;margin-top:4px;color:#999}
.tl-step.done .tl-label,.tl-step.active .tl-label{color:#333;font-weight:600}
/* QR section */
.qr-section{background:linear-gradient(135deg,#f0fdf4,#dcfce7);border:1px solid #86efac;border-radius:14px;padding:22px;text-align:center;margin-top:18px}
.qr-section img{max-width:200px;width:100%;border-radius:12px;border:4px solid #fff;box-shadow:0 4px 20px rgba(0,0,0,.15);margin:0 auto 16px;display:block}
.qr-title{font-weight:700;font-size:1rem;color:#14532d;margin-bottom:4px}
.qr-hint{font-size:.8rem;color:#16a34a;margin-bottom:16px}
.btn-dl{background:linear-gradient(135deg,#15803d,#16a34a);color:#fff;border:none;border-radius:8px;padding:8px 20px;font-weight:600;font-size:.85rem;text-decoration:none;display:inline-flex;align-items:center;gap:6px;transition:.2s;margin:4px}
.btn-dl:hover{background:linear-gradient(135deg,#14532d,#15803d);color:#fff;transform:translateY(-1px)}
.install-steps{background:#fff;border:1px solid #bbf7d0;border-radius:10px;padding:14px 18px;margin-top:14px;text-align:left}
.install-steps ol{margin:0;padding-left:20px;font-size:.82rem;color:#374151}
/* Logistics */
.logistics-box{background:#f0f4ff;border:1px solid #c7d2fe;border-radius:10px;padding:14px 18px;margin-top:14px;font-size:.87rem}
.logistics-box .lbl{color:#6c757d;min-width:80px;display:inline-block}
.empty-state{text-align:center;padding:60px 20px;color:#aaa}
.empty-state i{font-size:3rem;margin-bottom:16px;display:block;color:#e0d0ff}
</style>

<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="d-flex justify-content-between align-items-center mb-4">
            <h4 class="fw-bold mb-0"><i class="fas fa-mobile-alt me-2 text-primary"></i>我的 eSIM 订单</h4>
            <span class="badge bg-secondary">共 <?php echo $total_count; ?> 个订单</span>
        </div>

        <?php if (empty($orders)): ?>
        <div class="empty-state">
            <i class="fas fa-inbox"></i>
            <p class="mb-3">暂无 eSIM 订单</p>
            <a href="/esim-packages.php" class="btn btn-primary">浏览套餐</a>
        </div>
        <?php else: ?>

        <?php foreach ($orders as $order):
            $status = $order['status'];
            $slMap = [
                'pending'   => ['待支付',  'clock',        'status-pending'],
                'paid'      => ['已支付',  'check-circle', 'status-paid'],
                'completed' => ['已发货',  'paper-plane',  'status-completed'],
                'refunded'  => ['已退款',  'undo',         'status-refunded'],
                'failed'    => ['支付失败','times-circle', 'status-failed'],
            ];
            $sl = $slMap[$status] ?? ['未知','question','status-pending'];
            $steps = [
                ['key'=>'pending',   'label'=>'待支付', 'icon'=>'clock'],
                ['key'=>'paid',      'label'=>'已支付', 'icon'=>'check-circle'],
                ['key'=>'completed', 'label'=>'已发货', 'icon'=>'paper-plane'],
            ];
            $stepKeys = array_column($steps,'key');
            $curIdx   = array_search($status,$stepKeys);
            if ($curIdx===false) $curIdx = ($status==='failed'||$status==='refunded') ? -1 : 0;

            // Fetch associated device order for logistics
            $logStmt = $pdo->prepare("SELECT * FROM device_orders WHERE user_id=? AND order_number LIKE ? LIMIT 1");
            $logStmt->execute([$_SESSION['user_id'], '%'.$order['order_number'].'%']);
            $logOrder = $logStmt->fetch();
        ?>
        <div class="order-card">
            <div class="order-header">
                <div>
                    <div class="fw-bold"><?php echo htmlspecialchars($order['pkg_name'] ?? '套餐已下架'); ?></div>
                    <div class="order-num"># <?php echo htmlspecialchars($order['order_number']); ?></div>
                </div>
                <div class="text-end">
                    <div>
                        <span class="status-badge <?php echo $sl[2]; ?>">
                            <i class="fas fa-<?php echo $sl[1]; ?>"></i> <?php echo $sl[0]; ?>
                        </span>
                    </div>
                    <div class="order-date mt-1"><?php echo date('Y-m-d H:i', strtotime($order['created_at'])); ?></div>
                </div>
            </div>
            <div class="order-body">
                <!-- Package info grid -->
                <div class="pkg-grid">
                    <?php if (!empty($order['continent'])): ?>
                    <div class="pkg-item">
                        <div class="pi-label">适用地区</div>
                        <div class="pi-value"><?php echo htmlspecialchars($order['continent']); ?></div>
                    </div>
                    <?php endif; ?>
                    <?php if (!empty($order['countries'])): ?>
                    <div class="pkg-item">
                        <div class="pi-label">覆盖地区</div>
                        <div class="pi-value" style="font-size:.78rem;"><?php echo htmlspecialchars(mb_strimwidth($order['countries'], 0, 40, '...')); ?></div>
                    </div>
                    <?php endif; ?>
                    <?php if (!empty($order['data_mb'])): ?>
                    <div class="pkg-item">
                        <div class="pi-label">流量</div>
                        <div class="pi-value"><?php echo formatMB($order['data_mb']); ?></div>
                    </div>
                    <?php endif; ?>
                    <?php if (!empty($order['days'])): ?>
                    <div class="pkg-item">
                        <div class="pi-label">有效期</div>
                        <div class="pi-value"><?php echo getDays($order['days'], $order['pkg_name'] ?? ''); ?> 天</div>
                    </div>
                    <?php endif; ?>
                    <div class="pkg-item">
                        <div class="pi-label">支付金额</div>
                        <div class="pi-value" style="color:#d4621a;">$<?php echo number_format($order['amount'],2); ?></div>
                    </div>
                    <?php if (!empty($order['payment_method'])): ?>
                    <div class="pkg-item">
                        <div class="pi-label">支付方式</div>
                        <div class="pi-value"><?php echo htmlspecialchars($order['payment_method']); ?></div>
                    </div>
                    <?php endif; ?>
                    <?php if (!empty($order['euicc_number'])): ?>
                    <div class="pkg-item">
                        <div class="pi-label">关联eUICC</div>
                        <div class="pi-value" style="font-size:.75rem;">
                            <?php echo htmlspecialchars($order['euicc_nickname'] ?? ''); ?><br>
                            <span class="font-monospace text-muted" style="font-size:.7rem"><?php echo htmlspecialchars($order['euicc_number']); ?></span>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>

                <!-- Status timeline -->
                <?php if ($status !== 'failed' && $status !== 'refunded'): ?>
                <div class="timeline">
                    <?php foreach ($steps as $i => $step):
                        $done   = $i <= $curIdx;
                        $active = $i === $curIdx;
                    ?>
                    <div class="tl-step <?php echo $done?'done':''; ?> <?php echo $active?'active':''; ?>">
                        <div class="tl-dot"><i class="fas fa-<?php echo $step['icon']; ?>"></i></div>
                        <div class="tl-label"><?php echo $step['label']; ?></div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>

                <!-- Pending: pay button -->
                <?php if ($status === 'pending'): ?>
                <div class="mt-3">
                    <a href="/checkout.php?order=<?php echo urlencode($order['order_number']); ?>" class="btn btn-primary btn-sm">
                        <i class="fas fa-credit-card me-1"></i>立即支付
                    </a>
                </div>
                <?php endif; ?>

                <!-- Paid: waiting notice -->
                <?php if ($status === 'paid'): ?>
                <div class="alert alert-info mt-3 mb-0 py-2 px-3 small">
                    <i class="fas fa-hourglass-half me-1"></i>已支付成功，管理员正在处理您的 eSIM，发货后将通过邮件通知您。
                </div>
                <?php endif; ?>

                <!-- Completed: QR code inline display -->
                <?php if ($status === 'completed'): ?>
                    <?php if (!empty($order['qrcode_path'])): ?>
                    <div class="qr-section">
                        <div class="qr-title"><i class="fas fa-check-circle me-2"></i>您的 eSIM 二维码已就绪</div>
                        <div class="qr-hint">请用手机相机扫描下方二维码，按提示安装 eSIM</div>
                        <img src="<?php echo htmlspecialchars($order['qrcode_path']); ?>"
                             alt="eSIM 二维码"
                             id="qr-img-<?php echo $order['id']; ?>"
                             onerror="this.style.display='none';document.getElementById('qr-err-<?php echo $order['id']; ?>').style.display='block';">
                        <div id="qr-err-<?php echo $order['id']; ?>" style="display:none;" class="text-danger small mb-3">
                            <i class="fas fa-exclamation-triangle me-1"></i>二维码图片加载失败，请点击下方按钮下载
                        </div>
                        <div>
                            <a href="<?php echo htmlspecialchars($order['qrcode_path']); ?>"
                               download="eSIM_<?php echo htmlspecialchars($order['order_number']); ?>.png"
                               class="btn-dl">
                                <i class="fas fa-download"></i>下载二维码
                            </a>
                            <a href="<?php echo htmlspecialchars($order['qrcode_path']); ?>"
                               target="_blank"
                               class="btn btn-sm btn-outline-success" style="margin:4px;">
                                <i class="fas fa-external-link-alt me-1"></i>新窗口查看
                            </a>
                        </div>
                        <?php if (!empty($order['shipped_at'])): ?>
                        <div class="text-muted small mt-3">
                            <i class="fas fa-clock me-1"></i>发货时间：<?php echo date('Y-m-d H:i', strtotime($order['shipped_at'])); ?>
                        </div>
                        <?php endif; ?>
                        <div class="install-steps">
                            <div class="fw-bold small mb-2 text-success"><i class="fas fa-info-circle me-1"></i>安装说明</div>
                            <ol>
                                <li>确认您的设备支持 eSIM 功能（iPhone XS 及以上、部分 Android 旗舰机型）</li>
                                <li>进入手机"设置 → 蜂窝网络 / 移动网络 → 添加 eSIM / 添加移动套餐"</li>
                                <li>选择"扫描二维码"，对准上方二维码完成扫描</li>
                                <li>按照提示完成 eSIM 安装和激活，激活后即可使用</li>
                                <li>如遇问题请联系客服：<?php echo htmlspecialchars(getSetting('site_url') ?? ''); ?></li>
                            </ol>
                        </div>
                    </div>
                    <?php else: ?>
                    <div class="alert alert-warning mt-3 mb-0 py-2 px-3 small">
                        <i class="fas fa-exclamation-triangle me-1"></i>
                        订单已完成，但 eSIM 二维码尚未上传，请联系客服处理。
                    </div>
                    <?php endif; ?>
                <?php endif; ?>

                <!-- Logistics info for associated device order -->
                <?php if ($logOrder && !empty($logOrder['tracking_number'])): ?>
                <div class="logistics-box">
                    <div class="fw-bold mb-2"><i class="fas fa-shipping-fast me-2 text-primary"></i>附加设备物流信息</div>
                    <div class="mb-1">
                        <span class="lbl">快递公司</span>
                        <strong><?php echo htmlspecialchars($logOrder['tracking_carrier'] ?? '—'); ?></strong>
                    </div>
                    <div class="mb-1">
                        <span class="lbl">物流单号</span>
                        <strong class="font-monospace"><?php echo htmlspecialchars($logOrder['tracking_number']); ?></strong>
                        <button class="btn btn-sm btn-outline-secondary ms-2 py-0 px-2"
                                onclick="navigator.clipboard.writeText('<?php echo htmlspecialchars($logOrder['tracking_number']); ?>').then(()=>this.textContent='已复制').catch(()=>{})">
                            复制
                        </button>
                    </div>
                    <?php if (!empty($logOrder['tracking_url'])): ?>
                    <div class="mb-1">
                        <span class="lbl">查询链接</span>
                        <a href="<?php echo htmlspecialchars($logOrder['tracking_url']); ?>" target="_blank" class="text-primary">
                            <i class="fas fa-external-link-alt me-1"></i>点击查询物流
                        </a>
                    </div>
                    <?php endif; ?>
                    <?php if (!empty($logOrder['shipped_at'])): ?>
                    <div class="mb-1">
                        <span class="lbl">发货时间</span>
                        <?php echo date('Y-m-d H:i', strtotime($logOrder['shipped_at'])); ?>
                    </div>
                    <?php endif; ?>
                    <div>
                        <span class="lbl">物流状态</span>
                        <?php
                        $ls = $logOrder['status'] ?? 'pending';
                        $lsMap = ['pending'=>'待处理','paid'=>'已支付','shipped'=>'已发货','completed'=>'已签收','cancelled'=>'已取消'];
                        $lsColor = ($ls==='shipped'||$ls==='completed') ? 'success' : 'secondary';
                        echo '<span class="badge bg-'.$lsColor.'">' . ($lsMap[$ls]??$ls) . '</span>';
                        ?>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Refund/fail notice -->
                <?php if ($status === 'refunded'): ?>
                <div class="alert alert-warning mt-3 mb-0 py-2 px-3 small">
                    <i class="fas fa-undo me-1"></i>该订单已退款，如有疑问请联系客服。
                </div>
                <?php elseif ($status === 'failed'): ?>
                <div class="alert alert-danger mt-3 mb-0 py-2 px-3 small">
                    <i class="fas fa-times-circle me-1"></i>支付失败，请重新下单或联系客服。
                </div>
                <?php endif; ?>

            </div><!-- .order-body -->
        </div><!-- .order-card -->
        <?php endforeach; ?>

        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <nav class="mt-3">
            <ul class="pagination">
                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                <li class="page-item <?php echo $i===$page?'active':''; ?>">
                    <a class="page-link" href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                </li>
                <?php endfor; ?>
            </ul>
        </nav>
        <?php endif; ?>

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

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