<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit;
}
require_once __DIR__ . '/db/config.php';

$pdo = db();

date_default_timezone_set("Asia/Shanghai");
// Handle Cancel Request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'cancel' && isset($_POST['order_id'])) {
    $order_id = $_POST['order_id'];
    
    // Check if order exists and belongs to user and is in pending/active state
    $stmt = $pdo->prepare("SELECT * FROM sms_orders WHERE id = ? AND user_id = ? AND status = 'pending'");
    $stmt->execute([$order_id, $_SESSION['user_id']]);
    $order = $stmt->fetch();
    
    if ($order) {
        $pdo->beginTransaction();
        try {
            // Update order status
            $stmt = $pdo->prepare("UPDATE sms_orders SET status = 'canceled' WHERE id = ?");
            $stmt->execute([$order_id]);
            
            // Refund balance
            $stmt = $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
            $stmt->execute([$order['cost'], $_SESSION['user_id']]);
            
            $pdo->commit();
            header('Location: orders.php?msg=canceled');
            exit;
        } catch (Exception $e) {
            $pdo->rollBack();
            // Handle error
        }
    }
}

$stmt = $pdo->prepare("SELECT username, balance FROM users WHERE id = ?");
$stmt->execute([$_SESSION['user_id']]);
$user = $stmt->fetch();

$stmt = $pdo->prepare("SELECT * FROM sms_orders WHERE user_id = ? ORDER BY created_at DESC");
$stmt->execute([$_SESSION['user_id']]);
$orders = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>接码记录 - 全球接码</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary: #3b82f6;
            --bg-body: #f1f5f9;
            --surface: #ffffff;
            --text-main: #1e293b;
            --text-muted: #64748b;
            --border-color: #e2e8f0;
            --sidebar-width: 280px;
            --radius-xl: 24px;
        }
        body {
            font-family: 'Plus Jakarta Sans', sans-serif;
            background-color: var(--bg-body);
            color: var(--text-main);
            letter-spacing: -0.01em;
        }
        
        .main-content {
            margin-left: var(--sidebar-width);
            padding: 2.5rem;
            min-height: 100vh;
        }
        
        .table-card {
            background: white;
            border: 1px solid var(--border-color);
            border-radius: var(--radius-xl);
            padding: 1.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
        }
        
        .table { vertical-align: middle; border-collapse: separate; border-spacing: 0 8px; }
        .table thead th {
            background: #f8fafc;
            border: none;
            color: var(--text-muted);
            font-weight: 700;
            font-size: 12px;
            padding: 1rem 1.5rem;
        }
        .table tbody tr {
            background: #fff;
            transition: transform 0.2s;
        }
        .table tbody tr:hover { background: #f8fafc; }
        .table tbody td {
            padding: 1.5rem;
            border-top: 1px solid #f1f5f9;
            border-bottom: 1px solid #f1f5f9;
            font-weight: 500;
        }
        .table tbody td:first-child { border-left: 1px solid #f1f5f9; border-top-left-radius: 12px; border-bottom-left-radius: 12px; }
        .table tbody td:last-child { border-right: 1px solid #f1f5f9; border-top-right-radius: 12px; border-bottom-right-radius: 12px; }
        
        .status-pill {
            padding: 6px 14px;
            border-radius: 100px;
            font-size: 12px;
            font-weight: 800;
        }
        .status-received { background: #dcfce7; color: #166534; }
        .status-canceled { background: #fee2e2; color: #991b1b; }
        .status-pending { background: #eff6ff; color: #1e40af; }

        .sms-box {
            background: #f1f5f9;
            color: #334155;
            padding: 8px 16px;
            border-radius: 10px;
            font-family: 'JetBrains Mono', 'Courier New', monospace;
            font-weight: 700;
            border: 1px solid #e2e8f0;
            display: inline-block;
        }

        @media (max-width: 992px) {
            .main-content { margin-left: 0; padding: 1.5rem; }
            .sidebar { display: none; }
        }
    </style>
</head>
<body>

<?php include 'includes/sidebar.php'; ?>

<div class="main-content">
    <div class="mb-5">
        <h1 class="fw-bold mb-1" style="font-size: 1.5rem;">接码记录</h1>
        <p class="text-muted small fw-medium mb-0">记录您账户下所有的号码获取详情与收码状态清单</p>
    </div>

    <div class="table-card">
        <div class="table-responsive">
            <table class="table">
                <thead>
                    <tr>
                        <th>时间</th>
                        <th>项目/国家</th>
                        <th>号码</th>
                        <th>短信内容</th>
                        <th class="text-center">状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($orders as $order): ?>
                        <tr>
                            <td class="small text-muted fw-bold">
                                <div><?= date('Y-m-d', strtotime($order['created_at'])) ?></div>
                                <div class="opacity-50"><?= date('H:i:s', strtotime($order['created_at'])) ?></div>
                            </td>
                            <td>
                                <div class="fw-bold"><?= htmlspecialchars($order['service_name']) ?></div>
                                <div class="small text-muted fw-medium"><?= htmlspecialchars($order['country_name']) ?></div>
                            </td>
                            <td>
                                <div class="fw-bold text-primary fs-5" style="letter-spacing: 0.5px;"><?= $order['number'] ?></div>
                            </td>
                            <td>
                                <?php if ($order['sms_content']): ?>
                                    <span class="sms-box"><?= htmlspecialchars($order['sms_content']) ?></span>
                                <?php else: ?>
                                    <span class="text-muted opacity-25">等待短信...</span>
                                <?php endif; ?>
                            </td>
                            <td class="text-center">
                                <?php if ($order['status'] === 'received'): ?>
                                    <span class="status-pill status-received">成功</span>
                                <?php elseif ($order['status'] === 'canceled' || $order['status'] === 'expired'): ?>
                                    <span class="status-pill status-canceled">已关闭</span>
                                <?php else: ?>
                                    <span class="status-pill status-pending">等待中</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($order['status'] === 'pending'): ?>
                                    <form method="POST">
                                        <input type="hidden" name="action" value="cancel">
                                        <input type="hidden" name="order_id" value="<?= $order['id'] ?>">
                                        <button type="submit" class="btn btn-outline-danger btn-sm rounded-pill fw-bold" style="font-size: 11px;">取消</button>
                                    </form>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    <?php if (empty($orders)): ?>
                        <tr>
                            <td colspan="6" class="text-center py-5">
                                <div class="opacity-10 mb-3"><i class="fas fa-history fa-4x"></i></div>
                                <div class="fw-bold text-muted">暂无任何历史接码记录</div>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>