<?php
session_name('user_session');
session_start();
require '../include/common.php';

// 检查用户是否已登录
if (!isset($_SESSION['role'])) {
    header("Location: login.php"); // 如果未登录，重定向到登录页面
    exit();
}

// 获取用户ID
$userId = $_SESSION['user_id']; // 假设用户ID存储在 Session 中

// 设定分页机制
$limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 25; // 每页显示的条数，默认为25
$page = isset($_GET['page']) ? (int) $_GET['page'] : 1; // 当前页，从 URL 中获取
$start = ($page - 1) * $limit; // 每页起始条

// 初始化搜索条件
$orderNumber = isset($_GET['order_number']) ? $_GET['order_number'] : '';
$startDate = isset($_GET['start_date']) ? $_GET['start_date'] : '';
$endDate = isset($_GET['end_date']) ? $_GET['end_date'] : '';
$status = isset($_GET['status']) ? $_GET['status'] : '';

// 基础查询语句
if ($_SESSION['role'] == 0) { // 如果是管理员
    $query = "SELECT * FROM " . table('orders') . " WHERE 1=1 "; // 1=1 是为了方便后续添加条件
} else {
    // 普通用户只能查看自己的订单
    $query = "SELECT * FROM " . table('orders') . " WHERE user_id = :user_id ";
}

// 添加搜索条件
$params = [];
if (!empty($orderNumber)) {
    $query .= " AND order_number LIKE :order_number ";
    $params[':order_number'] = '%' . $orderNumber . '%';
}

if (!empty($startDate)) {
    $query .= " AND created_at >= :start_date ";
    $params[':start_date'] = $startDate;
}

if (!empty($endDate)) {
    $query .= " AND created_at <= :end_date ";
    $params[':end_date'] = $endDate . ' 23:59:59'; // 确保包含结束日期的所有时间
}

if ($status !== '') {
    $query .= " AND status = :status ";
    $params[':status'] = $status;
}

// 降序排列订单
$query .= " ORDER BY created_at DESC LIMIT :start, :limit";

// 准备语句
$stmt = $pdo->prepare($query);

// 绑定参数
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->bindValue(':start', $start, PDO::PARAM_INT);
if ($_SESSION['role'] != 0) {
    $stmt->bindValue(':user_id', $userId, PDO::PARAM_INT); // 普通用户需要绑定自己的ID
}

// 绑定搜索参数
foreach ($params as $key => $value) {
    $stmt->bindValue($key, $value);
}

// 执行查询
$stmt->execute();
$orders = $stmt->fetchAll(); // 获取最新的订单数据 (最近的订单在前)

// 确保 $orders 被初始化，避免未定义错误
$orders = $orders ?: []; // 如果没有订单结果，则初始化为空数组

// 获取总订单数以计算页数
$totalQuery = "SELECT COUNT(*) FROM " . table('orders') . " WHERE 1=1 ";
if ($_SESSION['role'] != 0) {
    $totalQuery .= " AND user_id = :user_id ";
}
if (!empty($orderNumber)) {
    $totalQuery .= " AND order_number LIKE :order_number ";
}
if (!empty($startDate)) {
    $totalQuery .= " AND created_at >= :start_date ";
}
if (!empty($endDate)) {
    $totalQuery .= " AND created_at <= :end_date ";
}
if ($status !== '') {
    $totalQuery .= " AND status = :status ";
}

// 准备总数查询
$totalStmt = $pdo->prepare($totalQuery);

// 绑定参数
if ($_SESSION['role'] != 0) {
    $totalStmt->bindValue(':user_id', $userId, PDO::PARAM_INT); // 普通用户需要绑定自己的ID
}

// 绑定搜索参数
foreach ($params as $key => $value) {
    $totalStmt->bindValue($key, $value);
}

// 执行总数查询
$totalStmt->execute();
$totalOrders = $totalStmt->fetchColumn();
$totalPages = ceil($totalOrders / $limit); // 总页数

// 处理订单删除逻辑
if (isset($_GET['delete_id']) && $_SESSION['role'] == 0) { // 只有管理员能够删除
    $deleteId = $_GET['delete_id'];
    $deleteStmt = $pdo->prepare("DELETE FROM " . table('orders') . " WHERE id = :id");
    $deleteStmt->bindValue(':id', $deleteId, PDO::PARAM_INT);
    $deleteStmt->execute();
    header("Location: orders.php"); // 删除后重定向
    exit();
}
?>

<?php include 'header.php'; ?>
<div class="main-content">
    <div class="page-content">
        <div class="container-fluid">
    <h1>充值订单</h1>

    <!-- 搜索表单 -->
    <form method="GET" class="mb-4">
        <div class="input-group">
            <input type="text" class="form-control" name="order_number" placeholder="订单号"
                value="<?php echo htmlspecialchars($orderNumber); ?>">
            <input type="date" class="form-control" name="start_date"
                value="<?php echo htmlspecialchars($startDate); ?>">
            <input type="date" class="form-control" name="end_date" value="<?php echo htmlspecialchars($endDate); ?>">
            <select class="form-select" name="status">
                <option value="" <?php if ($status === '')
                    echo 'selected'; ?>>所有状态</option>
                <option value="1" <?php if ($status == 1)
                    echo 'selected'; ?>>已支付</option>
                <option value="0" <?php if ($status == 0)
                    echo 'selected'; ?>>未支付</option>
            </select>
            <button class="btn btn-primary" type="submit">搜索</button>
        </div>

        <!-- 每页显示条数的选择 -->
        <div class="mt-3 d-inline-block">
            <label for="limit" class="form-label">每页显示条数:</label>
            <select class="form-select d-inline" name="limit" style="width: auto;" onchange="this.form.submit()">
                <option value="25" <?php if ($limit == 25)
                    echo 'selected'; ?>>25</option>
                <option value="50" <?php if ($limit == 50)
                    echo 'selected'; ?>>50</option>
                <option value="75" <?php if ($limit == 75)
                    echo 'selected'; ?>>75</option>
                <option value="100" <?php if ($limit == 100)
                    echo 'selected'; ?>>100</option>
                <option value="150" <?php if ($limit == 150)
                    echo 'selected'; ?>>150</option>
                <option value="200" <?php if ($limit == 200)
                    echo 'selected'; ?>>200</option>
            </select>
        </div>
    </form>

    <?php if (count($orders) > 0): ?>
        <div style="overflow-x: auto;">
        <table class="table table-bordered table-striped mt-3">
            <thead>
                <tr>
                    <th>订单ID</th>
                    <?php if ($_SESSION['role'] == 0): ?>
                        <th>用户ID</th> <!-- 管理员看到的用户 ID -->
                    <?php endif; ?>
                    <th>订单号</th>
                    <th>充值金额</th>
                    <th>状态</th>
                    <th>创建时间</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $displayId = ($totalOrders - ($page - 1) * $limit); // 计算显示的ID
                foreach ($orders as $order): ?>
                    <tr>
                        <td><?php echo $displayId--; ?></td> <!-- 显示的 ID -->
                        <?php if ($_SESSION['role'] == 0): ?>
                            <td><?php echo $order['user_id']; ?></td> <!-- 管理员看到的用户 ID -->
                        <?php endif; ?>
                        <td><?php echo $order['order_number']; ?></td>
                        <td><?php echo number_format($order['amount'], 2); ?></td>
                        <td style="color: <?php echo $order['status'] == 1 ? 'green' : 'red'; ?>;">
                            <?php echo $order['status'] == 1 ? '已支付' : '未支付'; ?>
                        </td>
                        <td><?php echo $order['created_at']; ?></td>
                    </tr>

                <?php endforeach; ?>
            </tbody>
        </table>
            </div>
        <!-- 分页导航 -->
        <nav aria-label="Page navigation">
            <ul class="pagination">
                <?php if ($page > 1): ?>
                    <li class="page-item"><a class="page-link" href="?page=1&limit=<?php echo $limit; ?>">第一页</a></li>
                    <li class="page-item"><a class="page-link"
                            href="?page=<?php echo $page - 1; ?>&limit=<?php echo $limit; ?>">上一页</a></li>
                <?php endif; ?>

                <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                    <li class="page-item <?php if ($i == $page)
                        echo 'active'; ?>">
                        <a class="page-link" href="?page=<?php echo $i; ?>&limit=<?php echo $limit; ?>"><?php echo $i; ?></a>
                    </li>
                <?php endfor; ?>

                <?php if ($page < $totalPages): ?>
                    <li class="page-item"><a class="page-link"
                            href="?page=<?php echo $page + 1; ?>&limit=<?php echo $limit; ?>">下一页</a></li>
                    <li class="page-item"><a class="page-link"
                            href="?page=<?php echo $totalPages; ?>&limit=<?php echo $limit; ?>">最后一页</a></li>
                <?php endif; ?>
            </ul>
        </nav>
    <?php else: ?>
        <p>没有找到充值订单记录。</p>
    <?php endif; ?>
</div>
</div>
    </div>
<script src="../assets/js/popper.min.js"></script>
<script src="../assets/js/bootstrap.min.js"></script>
</body>

</html>
