<?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;

// 处理搜索请求
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 = "SELECT 
            (SELECT COUNT(*) FROM visitor_permits WHERE personnel_id = $id) +
            (SELECT COUNT(*) FROM entry_permits WHERE personnel_id = $id) +
            (SELECT COUNT(*) FROM access_cards WHERE personnel_id = $id) +
            (SELECT COUNT(*) FROM airport_passes WHERE personnel_id = $id) +
            (SELECT COUNT(*) FROM restricted_area_passes WHERE personnel_id = $id) +
            (SELECT COUNT(*) FROM vehicle_restricted_passes WHERE personnel_id = $id) AS total";
    
    $result = $conn->query($sql);
    $row = $result->fetch_assoc();
    
    if ($row['total'] > 0) {
        $message = showError("删除失败：该人员有关联的证件记录，请先删除相关证件");
    } else {
        // 获取照片路径
        $sql = "SELECT photo FROM personnel WHERE id = $id";
        $result = $conn->query($sql);
        if ($result && $result->num_rows > 0) {
            $row = $result->fetch_assoc();
            $photoPath = $row['photo'];
            
            // 如果有照片，删除照片文件
            if ($photoPath && file_exists("../" . $photoPath)) {
                unlink("../" . $photoPath);
            }
        }
        
        // 删除人员记录
        $sql = "DELETE FROM personnel WHERE id = $id";
        if ($conn->query($sql) === TRUE) {
            $message = showSuccess("人员信息已成功删除");
        } else {
            $message = showError("删除失败：" . $conn->error);
        }
    }
}

// 获取人员列表
$searchResult = searchPersonnel($conn, $search, $currentPage, $perPage);
$personnelList = $searchResult['data'];
$totalRecords = $searchResult['total'];

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

<!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" class="active">人员信息管理</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">机场证<?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="personnel.php" style="flex: 1; margin-right: 20px;">
                    <div style="display: flex;">
                        <input type="text" name="search" class="form-control" placeholder="搜索姓名、电话、身份证..." value="<?php echo htmlspecialchars($search); ?>" style="margin-right: 10px;">
                        <button type="submit" class="btn btn-primary">搜索</button>
                    </div>
                </form>
                <a href="personnel_form.php" class="btn btn-success">添加人员</a>
            </div>
        </div>
        
        <!-- 人员列表 -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">人员列表</h3>
            </div>
            <div class="card-body">
                <?php if (count($personnelList) > 0): ?>
                <table class="table">
                    <thead>
                        <tr>
                            <th>照片</th>
                            <th>中文姓名</th>
                            <th>英文姓名</th>
                            <th>职位</th>
                            <th>电话</th>
                            <th>邮箱</th>
                            <th>性别</th>
                            <th>雇佣类型</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($personnelList as $person): ?>
                        <tr>
                            <td>
                                <?php if (!empty($person['photo']) && file_exists("../" . $person['photo'])): ?>
                                <img src="<?php echo "../" . htmlspecialchars($person['photo']); ?>" alt="照片" style="width: 50px; height: 50px; object-fit: cover; border-radius: 2px;">
                                <?php else: ?>
                                <div style="width: 50px; height: 50px; background-color: #f0f0f0; display: flex; align-items: center; justify-content: center; border-radius: 2px;">无</div>
                                <?php endif; ?>
                            </td>
                            <td><?php echo htmlspecialchars($person['chinese_name'] ?: '-'); ?></td>
                            <td><?php echo htmlspecialchars($person['english_name'] ?: '-'); ?></td>
                            <td><?php echo htmlspecialchars($person['position'] ?: '-'); ?></td>
                            <td><?php echo htmlspecialchars($person['phone'] ?: '-'); ?></td>
                            <td><?php echo htmlspecialchars($person['email'] ?: '-'); ?></td>
                            <td><?php echo htmlspecialchars($person['gender'] ?: '-'); ?></td>
                            <td><?php echo htmlspecialchars($person['employment_type'] ?: '-'); ?></td>
                            <td>
                                <a href="personnel_view.php?id=<?php echo $person['id']; ?>" class="btn btn-primary action-btn">查看</a>
                                <a href="personnel_form.php?id=<?php echo $person['id']; ?>" class="btn btn-secondary action-btn">编辑</a>
                                <form method="POST" action="personnel.php" style="display: inline;" onsubmit="return confirm('确定要删除此人员信息吗？此操作不可恢复！');">
                                    <input type="hidden" name="delete_id" value="<?php echo $person['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) ? '或没有符合搜索条件的结果' : ''; ?></p>
                <?php endif; ?>
            </div>
        </div>
    </main>
</body>
</html>
