<?php
// 开启会话
session_start();

// 引入必要的文件
require_once '../includes/config.php';
require_once '../includes/functions.php';

// 检查用户是否已登录，如果没有则重定向到登录页面
if (!isLoggedIn()) {
    redirect("../index.php");
}

// 获取即将到期的证件数量
$expiringCount = getExpiringDocumentsCount($conn);

// 定义变量
$search = "";
$message = "";
$currentPage = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 10;
$status = isset($_GET['status']) ? $_GET['status'] : '';

// 处理搜索请求
if ($_SERVER["REQUEST_METHOD"] == "GET" && isset($_GET['search'])) {
    $search = trim($_GET['search']);
}

// 处理删除请求
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['delete_id'])) {
    $id = (int)$_POST['delete_id'];
    
    $sql = "DELETE FROM airport_passes WHERE id = $id";
    if ($conn->query($sql) === TRUE) {
        $message = showSuccess("机场证已成功删除");
    } else {
        $message = showError("删除失败：" . $conn->error);
    }
}

// 构建查询条件
$whereClause = [];
if (!empty($search)) {
    $search = sanitize($conn, $search);
    $whereClause[] = "(p.chinese_name LIKE '%$search%' OR p.english_name LIKE '%$search%' OR ap.airport_number LIKE '%$search%' OR ap.pass_type LIKE '%$search%')";
}

if (!empty($status)) {
    $status = sanitize($conn, $status);
    $whereClause[] = "ap.status = '$status'";
}

$whereSQL = !empty($whereClause) ? "WHERE " . implode(" AND ", $whereClause) : "";

// 计算总记录数
$countSql = "SELECT COUNT(*) as total FROM airport_passes ap 
             JOIN personnel p ON ap.personnel_id = p.id 
             $whereSQL";
$countResult = $conn->query($countSql);
$totalRecords = 0;

if ($countResult && $row = $countResult->fetch_assoc()) {
    $totalRecords = (int)$row['total'];
}

// 获取分页数据
$offset = ($currentPage - 1) * $perPage;
$sql = "SELECT ap.*, p.chinese_name, p.english_name 
        FROM airport_passes ap 
        JOIN personnel p ON ap.personnel_id = p.id 
        $whereSQL 
        ORDER BY ap.expiry_date ASC 
        LIMIT $offset, $perPage";

$result = $conn->query($sql);
$passesList = [];

if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $passesList[] = $row;
    }
}

// 构建分页URL
$paginationUrl = "airport_passes.php?search=" . urlencode($search) . "&status=" . urlencode($status);
?>

<!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 rel="stylesheet" href="../assets/css/style.css">
</head>
<body>
    <!-- 头部 -->
    <header class="header">
        <div class="container header-content">
            <div class="logo">证件到期提醒系统</div>
            <div class="user-info">
                <span>欢迎, <?php echo htmlspecialchars($_SESSION["admin_username"]); ?></span>
                <a href="logout.php" class="logout-btn">退出</a>
            </div>
        </div>
    </header>
    
    <!-- 侧边栏 -->
    <aside class="sidebar">
        <ul class="sidebar-menu">
            <li><a href="dashboard.php">仪表盘</a></li>
            <li><a href="personnel.php">人员信息管理</a></li>
            <li><a href="visitor_permits.php">访客许可证<?php if($expiringCount['visitor_permits'] > 0): ?><span class="badge"><?php echo $expiringCount['visitor_permits']; ?></span><?php endif; ?></a></li>
            <li><a href="entry_permits.php">进入许可证<?php if($expiringCount['entry_permits'] > 0): ?><span class="badge"><?php echo $expiringCount['entry_permits']; ?></span><?php endif; ?></a></li>
            <li><a href="access_cards.php">门禁卡<?php if($expiringCount['access_cards'] > 0): ?><span class="badge"><?php echo $expiringCount['access_cards']; ?></span><?php endif; ?></a></li>
            <li><a href="airport_passes.php" class="active">机场证<?php if($expiringCount['airport_passes'] > 0): ?><span class="badge"><?php echo $expiringCount['airport_passes']; ?></span><?php endif; ?></a></li>
            <li><a href="restricted_passes.php">禁区证<?php if($expiringCount['restricted_area_passes'] > 0): ?><span class="badge"><?php echo $expiringCount['restricted_area_passes']; ?></span><?php endif; ?></a></li>
            <li><a href="vehicle_passes.php">车辆禁区证<?php if($expiringCount['vehicle_restricted_passes'] > 0): ?><span class="badge"><?php echo $expiringCount['vehicle_restricted_passes']; ?></span><?php endif; ?></a></li>
            <li><a href="settings.php">管理员设置</a></li>
        </ul>
    </aside>
    
    <!-- 主要内容区域 -->
    <main class="main-content">
        <h1 class="page-title">机场证管理</h1>
        
        <?php echo $message; ?>
        
        <!-- 搜索和添加区域 -->
        <div class="search-area">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <form method="GET" action="airport_passes.php" style="flex: 1; margin-right: 20px;">
                    <div style="display: flex; flex-wrap: wrap;">
                        <input type="text" name="search" class="form-control" placeholder="搜索姓名、机场号码..." value="<?php echo htmlspecialchars($search); ?>" style="margin-right: 10px; margin-bottom: 10px; width: 200px;">
                        
                        <select name="status" class="form-control" style="margin-right: 10px; margin-bottom: 10px; width: 150px;">
                            <option value="">所有状态</option>
                            <option value="有效" <?php echo $status === '有效' ? 'selected' : ''; ?>>有效</option>
                            <option value="即将到期" <?php echo $status === '即将到期' ? 'selected' : ''; ?>>即将到期</option>
                            <option value="已过期" <?php echo $status === '已过期' ? 'selected' : ''; ?>>已过期</option>
                            <option value="已归还" <?php echo $status === '已归还' ? 'selected' : ''; ?>>已归还</option>
                        </select>
                        
                        <button type="submit" class="btn btn-primary" style="margin-bottom: 10px;">搜索</button>
                    </div>
                </form>
                <a href="airport_passes_form.php" class="btn btn-success" style="margin-bottom: 10px;">添加机场证</a>
            </div>
        </div>
        
        <!-- 机场证列表 -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">机场证列表</h3>
            </div>
            <div class="card-body">
                <?php if (count($passesList) > 0): ?>
                <table class="table">
                    <thead>
                        <tr>
                            <th>人员姓名</th>
                            <th>机场号码</th>
                            <th>证件类别</th>
                            <th>有效期</th>
                            <th>归还日期</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($passesList as $pass): ?>
                        <tr>
                            <td>
                                <a href="personnel_view.php?id=<?php echo $pass['personnel_id']; ?>" title="查看人员详情">
                                    <?php echo htmlspecialchars($pass['chinese_name'] ?: $pass['english_name']); ?>
                                </a>
                            </td>
                            <td><?php echo htmlspecialchars($pass['airport_number']); ?></td>
                            <td><?php echo htmlspecialchars($pass['pass_type']); ?></td>
                            <td><?php echo formatDate($pass['expiry_date']); ?></td>
                            <td><?php echo formatDate($pass['return_date']); ?></td>
                            <td>
                                <span class="status-tag <?php echo getStatusClass($pass['status']); ?>">
                                    <?php echo htmlspecialchars($pass['status']); ?>
                                </span>
                            </td>
                            <td>
                                <a href="airport_passes_form.php?id=<?php echo $pass['id']; ?>" class="btn btn-primary action-btn">编辑</a>
                                <form method="POST" action="airport_passes.php" style="display: inline;" onsubmit="return confirm('确定要删除此机场证吗？此操作不可恢复！');">
                                    <input type="hidden" name="delete_id" value="<?php echo $pass['id']; ?>">
                                    <button type="submit" class="btn btn-danger action-btn">删除</button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                
                <!-- 分页 -->
                <?php echo getPagination($totalRecords, $perPage, $currentPage, $paginationUrl); ?>
                
                <?php else: ?>
                <p>暂无机场证记录<?php echo !empty($search) || !empty($status) ? '或没有符合搜索条件的结果' : ''; ?></p>
                <?php endif; ?>
            </div>
        </div>
    </main>
</body>
</html>
