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

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

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

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

// 定义变量
$id = $personnel_id = $airport_number = $pass_type = $expiry_date = $return_date = "";
$status = "有效";
$errors = [];
$message = "";
$isEdit = false;
$personnel = null;

// 如果是编辑模式，获取机场证信息
if (isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    $isEdit = true;
    
    $sql = "SELECT * FROM airport_passes WHERE id = $id LIMIT 1";
    $result = $conn->query($sql);
    
    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $personnel_id = $row['personnel_id'];
        $airport_number = $row['airport_number'];
        $pass_type = $row['pass_type'];
        $expiry_date = $row['expiry_date'];
        $return_date = $row['return_date'];
        $status = $row['status'];
        
        // 获取人员信息
        $personnel = getPersonnelById($conn, $personnel_id);
    } else {
        $message = showError("未找到该机场证");
        redirect("airport_passes.php");
    }
} elseif (isset($_GET['personnel_id'])) {
    // 如果是从人员详情页面添加，获取人员ID
    $personnel_id = (int)$_GET['personnel_id'];
    $personnel = getPersonnelById($conn, $personnel_id);
    
    if (!$personnel) {
        $message = showError("未找到该人员信息");
        redirect("airport_passes.php");
    }
}

// 处理表单提交
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // 获取表单数据
    $personnel_id = (int)$_POST['personnel_id'];
    $airport_number = trim($_POST['airport_number']);
    $pass_type = trim($_POST['pass_type']);
    $expiry_date = trim($_POST['expiry_date']);
    $return_date = trim($_POST['return_date']);
    $status = trim($_POST['status']);
    
    // 验证必填字段
    if (empty($personnel_id)) {
        $errors[] = "必须选择人员";
    }
    
    if (empty($airport_number)) {
        $errors[] = "机场号码不能为空";
    }
    
    if (empty($pass_type)) {
        $errors[] = "证件类别不能为空";
    }
    
    if (empty($expiry_date)) {
        $errors[] = "有效期不能为空";
    } elseif (!validateDate($expiry_date)) {
        $errors[] = "有效期格式不正确，应为YYYY-MM-DD";
    }
    
    if (!empty($return_date) && !validateDate($return_date)) {
        $errors[] = "归还日期格式不正确，应为YYYY-MM-DD";
    }
    
    // 如果没有错误，保存数据
    if (empty($errors)) {
        if ($isEdit) {
            // 更新现有记录
            $sql = "UPDATE airport_passes SET 
                    personnel_id = ?, 
                    airport_number = ?, 
                    pass_type = ?, 
                    expiry_date = ?, 
                    return_date = ?, 
                    status = ? 
                    WHERE id = ?";
            
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("isssssi", 
                $personnel_id, 
                $airport_number, 
                $pass_type, 
                $expiry_date, 
                $return_date, 
                $status, 
                $id
            );
            
            if ($stmt->execute()) {
                $message = showSuccess("机场证已成功更新");
                // 更新状态
                updateDocumentStatus($conn, 'airport_passes');
            } else {
                $message = showError("更新失败：" . $stmt->error);
            }
            
            $stmt->close();
        } else {
            // 插入新记录
            $sql = "INSERT INTO airport_passes (
                    personnel_id, 
                    airport_number, 
                    pass_type, 
                    expiry_date, 
                    return_date, 
                    status
                ) VALUES (?, ?, ?, ?, ?, ?)";
            
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("isssss", 
                $personnel_id, 
                $airport_number, 
                $pass_type, 
                $expiry_date, 
                $return_date, 
                $status
            );
            
            if ($stmt->execute()) {
                $id = $stmt->insert_id;
                $message = showSuccess("机场证已成功添加");
                // 更新状态
                updateDocumentStatus($conn, 'airport_passes');
                
                if (isset($_POST['continue']) && $_POST['continue'] == '1') {
                    // 继续添加，重置部分表单
                    $airport_number = $pass_type = $expiry_date = $return_date = "";
                    $status = "有效";
                } else {
                    // 返回列表或人员详情页
                    if (!empty($personnel_id)) {
                        redirect("personnel_view.php?id=$personnel_id");
                    } else {
                        redirect("airport_passes.php");
                    }
                }
            } else {
                $message = showError("添加失败：" . $stmt->error);
            }
            
            $stmt->close();
        }
    } else {
        $message = showError(implode("<br>", $errors));
    }
}

// 获取人员列表（用于选择）
$personnelList = [];
$sql = "SELECT id, chinese_name, english_name FROM personnel ORDER BY chinese_name, english_name";
$result = $conn->query($sql);

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

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $isEdit ? '编辑' : '添加'; ?>机场证 - 证件到期提醒系统</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"><?php echo $isEdit ? '编辑' : '添加'; ?>机场证</h1>
        
        <?php echo $message; ?>
        
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">机场证表单</h3>
            </div>
            <div class="card-body">
                <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"] . ($isEdit ? "?id=$id" : "")); ?>">
                    <div class="form-group">
                        <label class="form-label">选择人员 <span style="color: red;">*</span></label>
                        <select name="personnel_id" class="form-control" <?php echo $personnel_id ? 'disabled' : ''; ?>>
                            <option value="">请选择人员</option>
                            <?php foreach ($personnelList as $person): ?>
                            <option value="<?php echo $person['id']; ?>" <?php echo $personnel_id == $person['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars(($person['chinese_name'] ?: $person['english_name'])); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                        <?php if ($personnel_id): ?>
                        <input type="hidden" name="personnel_id" value="<?php echo $personnel_id; ?>">
                        <?php endif; ?>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-col">
                            <div class="form-group">
                                <label class="form-label">机场号码 <span style="color: red;">*</span></label>
                                <input type="text" name="airport_number" class="form-control" value="<?php echo htmlspecialchars($airport_number); ?>" required>
                            </div>
                        </div>
                        <div class="form-col">
                            <div class="form-group">
                                <label class="form-label">证件类别 <span style="color: red;">*</span></label>
                                <input type="text" name="pass_type" class="form-control" value="<?php echo htmlspecialchars($pass_type); ?>" required>
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-col">
                            <div class="form-group">
                                <label class="form-label">有效期 <span style="color: red;">*</span></label>
                                <input type="date" name="expiry_date" class="form-control" value="<?php echo htmlspecialchars($expiry_date); ?>" required>
                            </div>
                        </div>
                        <div class="form-col">
                            <div class="form-group">
                                <label class="form-label">归还日期</label>
                                <input type="date" name="return_date" class="form-control" value="<?php echo htmlspecialchars($return_date); ?>">
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">状态</label>
                        <select name="status" class="form-control">
                            <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>
                    </div>
                    
                    <div class="form-group">
                        <button type="submit" class="btn btn-primary"><?php echo $isEdit ? '更新' : '添加'; ?></button>
                        
                        <?php if (!$isEdit): ?>
                        <div class="checkbox-container" style="margin-top: 10px;">
                            <input type="checkbox" name="continue" id="continue" value="1">
                            <label for="continue">添加后继续</label>
                        </div>
                        <?php endif; ?>
                        
                        <?php if ($personnel_id): ?>
                        <a href="personnel_view.php?id=<?php echo $personnel_id; ?>" class="btn btn-secondary">返回人员详情</a>
                        <?php else: ?>
                        <a href="airport_passes.php" class="btn btn-secondary">返回列表</a>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
        </div>
    </main>
</body>
</html>
