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

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

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

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

// 定义变量
$id = $photo = $english_name = $chinese_code = $chinese_name = $nickname = $position = $phone = $email = $id_passport = "";
$data_center_access = $execution_team = $maintenance_team = $work_commitment = $criminal_check = 0;
$gender = $employment_type = $company_home = "";
$errors = [];
$message = "";
$isEdit = false;

// 如果是编辑模式，获取人员信息
if (isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    $isEdit = true;
    
    $sql = "SELECT * FROM personnel WHERE id = $id LIMIT 1";
    $result = $conn->query($sql);
    
    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $photo = $row['photo'];
        $english_name = $row['english_name'];
        $chinese_code = $row['chinese_code'];
        $chinese_name = $row['chinese_name'];
        $nickname = $row['nickname'];
        $position = $row['position'];
        $phone = $row['phone'];
        $email = $row['email'];
        $id_passport = $row['id_passport'];
        $data_center_access = $row['data_center_access'];
        $execution_team = $row['execution_team'];
        $maintenance_team = $row['maintenance_team'];
        $gender = $row['gender'];
        $employment_type = $row['employment_type'];
        $company_home = $row['company_home'];
        $work_commitment = $row['work_commitment'];
        $criminal_check = $row['criminal_check'];
    } else {
        $message = showError("未找到该人员信息");
        redirect("personnel.php");
    }
}

// 处理表单提交
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // 获取表单数据
    $english_name = trim($_POST['english_name']);
    $chinese_code = trim($_POST['chinese_code']);
    $chinese_name = trim($_POST['chinese_name']);
    $nickname = trim($_POST['nickname']);
    $position = trim($_POST['position']);
    $phone = trim($_POST['phone']);
    $email = trim($_POST['email']);
    $id_passport = trim($_POST['id_passport']);
    $data_center_access = isset($_POST['data_center_access']) ? 1 : 0;
    $execution_team = isset($_POST['execution_team']) ? 1 : 0;
    $maintenance_team = isset($_POST['maintenance_team']) ? 1 : 0;
    $gender = trim($_POST['gender']);
    $employment_type = trim($_POST['employment_type']);
    $company_home = trim($_POST['company_home']);
    $work_commitment = isset($_POST['work_commitment']) ? 1 : 0;
    $criminal_check = isset($_POST['criminal_check']) ? 1 : 0;
    
    // 验证必填字段
    if (empty($chinese_name) && empty($english_name)) {
        $errors[] = "中文姓名和英文姓名至少填写一项";
    }
    
    // 处理照片上传
    $photoPath = $photo; // 保留原有照片路径
    
    if (isset($_FILES['photo']) && $_FILES['photo']['error'] !== UPLOAD_ERR_NO_FILE) {
        $uploadResult = uploadImage($_FILES['photo']);
        
        if ($uploadResult['success']) {
            // 如果是编辑模式且已有照片，删除旧照片
            if ($isEdit && !empty($photo) && file_exists("../" . $photo)) {
                unlink("../" . $photo);
            }
            $photoPath = $uploadResult['file_path'];
        } else {
            $errors[] = $uploadResult['message'];
        }
    }
    
    // 如果没有错误，保存数据
    if (empty($errors)) {
        if ($isEdit) {
            // 更新现有记录
            $sql = "UPDATE personnel SET 
                    photo = ?, 
                    english_name = ?, 
                    chinese_code = ?, 
                    chinese_name = ?, 
                    nickname = ?, 
                    position = ?, 
                    phone = ?, 
                    email = ?, 
                    id_passport = ?, 
                    data_center_access = ?, 
                    execution_team = ?, 
                    maintenance_team = ?, 
                    gender = ?, 
                    employment_type = ?, 
                    company_home = ?, 
                    work_commitment = ?, 
                    criminal_check = ? 
                    WHERE id = ?";
            
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("sssssssssiisssiiii", 
                $photoPath, 
                $english_name, 
                $chinese_code, 
                $chinese_name, 
                $nickname, 
                $position, 
                $phone, 
                $email, 
                $id_passport, 
                $data_center_access, 
                $execution_team, 
                $maintenance_team, 
                $gender, 
                $employment_type, 
                $company_home, 
                $work_commitment, 
                $criminal_check, 
                $id
            );
            
            if ($stmt->execute()) {
                $message = showSuccess("人员信息已成功更新");
            } else {
                $message = showError("更新失败：" . $stmt->error);
            }
            
            $stmt->close();
        } else {
            // 插入新记录
            $sql = "INSERT INTO personnel (
                    photo, 
                    english_name, 
                    chinese_code, 
                    chinese_name, 
                    nickname, 
                    position, 
                    phone, 
                    email, 
                    id_passport, 
                    data_center_access, 
                    execution_team, 
                    maintenance_team, 
                    gender, 
                    employment_type, 
                    company_home, 
                    work_commitment, 
                    criminal_check
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("sssssssssiiissiii", 
                $photoPath, 
                $english_name, 
                $chinese_code, 
                $chinese_name, 
                $nickname, 
                $position, 
                $phone, 
                $email, 
                $id_passport, 
                $data_center_access, 
                $execution_team, 
                $maintenance_team, 
                $gender, 
                $employment_type, 
                $company_home, 
                $work_commitment, 
                $criminal_check
            );
            
            if ($stmt->execute()) {
                $id = $stmt->insert_id;
                $message = showSuccess("人员信息已成功添加");
                // 重置表单
                $photo = $english_name = $chinese_code = $chinese_name = $nickname = $position = $phone = $email = $id_passport = "";
                $data_center_access = $execution_team = $maintenance_team = $work_commitment = $criminal_check = 0;
                $gender = $employment_type = $company_home = "";
            } else {
                $message = showError("添加失败：" . $stmt->error);
            }
            
            $stmt->close();
        }
    } else {
        $message = showError(implode("<br>", $errors));
    }
}
?>

<!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" 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"><?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" : "")); ?>" enctype="multipart/form-data">
                    <div class="form-row">
                        <div class="form-col">
                            <div class="form-group">
                                <label class="form-label">照片</label>
                                <?php if (!empty($photo) && file_exists("../" . $photo)): ?>
                                <div class="photo-preview">
                                    <img src="<?php echo "../" . htmlspecialchars($photo); ?>" alt="照片">
                                </div>
                                <?php endif; ?>
                                <input type="file" name="photo" class="form-control" accept="image/*">
                                <small>支持JPG, PNG, GIF格式，最大5MB</small>
                            </div>
                        </div>
                        <div class="form-col">
                            <div class="form-group">
                                <label class="form-label">英文姓名</label>
                                <input type="text" name="english_name" class="form-control" value="<?php echo htmlspecialchars($english_name); ?>">
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-col">
                            <div class="form-group">
                                <label class="form-label">中文电码</label>
                                <input type="text" name="chinese_code" class="form-control" value="<?php echo htmlspecialchars($chinese_code); ?>">
                            </div>
                        </div>
                        <div class="form-col">
                            <div class="form-group">
                                <label class="form-label">中文姓名</label>
                                <input type="text" name="chinese_name" class="form-control" value="<?php echo htmlspecialchars($chinese_name); ?>">
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-col">
                            <div class="form-group">
                                <label class="form-label">乳名</label>
                                <input type="text" name="nickname" class="form-control" value="<?php echo htmlspecialchars($nickname); ?>">
                            </div>
                        </div>
                        <div class="form-col">
                            <div class="form-group">
                                <label class="form-label">职位</label>
                                <input type="text" name="position" class="form-control" value="<?php echo htmlspecialchars($position); ?>">
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-col">
                            <div class="form-group">
                                <label class="form-label">电话</label>
                                <input type="text" name="phone" class="form-control" value="<?php echo htmlspecialchars($phone); ?>">
                            </div>
                        </div>
                        <div class="form-col">
                            <div class="form-group">
                                <label class="form-label">邮箱</label>
                                <input type="email" name="email" class="form-control" value="<?php echo htmlspecialchars($email); ?>">
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-col">
                            <div class="form-group">
                                <label class="form-label">身份证或护照</label>
                                <input type="text" name="id_passport" class="form-control" value="<?php echo htmlspecialchars($id_passport); ?>">
                            </div>
                        </div>
                        <div class="form-col">
                            <div class="form-group">
                                <label class="form-label">公司/家</label>
                                <input type="text" name="company_home" class="form-control" value="<?php echo htmlspecialchars($company_home); ?>">
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-col">
                            <div class="form-group">
                                <label class="form-label">性别</label>
                                <select name="gender" class="form-control">
                                    <option value="">请选择</option>
                                    <option value="男" <?php echo $gender === '男' ? 'selected' : ''; ?>>男</option>
                                    <option value="女" <?php echo $gender === '女' ? 'selected' : ''; ?>>女</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-col">
                            <div class="form-group">
                                <label class="form-label">雇佣类型</label>
                                <select name="employment_type" class="form-control">
                                    <option value="">请选择</option>
                                    <option value="全职" <?php echo $employment_type === '全职' ? 'selected' : ''; ?>>全职</option>
                                    <option value="兼职" <?php echo $employment_type === '兼职' ? 'selected' : ''; ?>>兼职</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">其他信息</label>
                        <div class="checkbox-container">
                            <input type="checkbox" name="data_center_access" id="data_center_access" value="1" <?php echo $data_center_access ? 'checked' : ''; ?>>
                            <label for="data_center_access">是否可以进入数据中心</label>
                        </div>
                        <div class="checkbox-container">
                            <input type="checkbox" name="execution_team" id="execution_team" value="1" <?php echo $execution_team ? 'checked' : ''; ?>>
                            <label for="execution_team">执行组</label>
                        </div>
                        <div class="checkbox-container">
                            <input type="checkbox" name="maintenance_team" id="maintenance_team" value="1" <?php echo $maintenance_team ? 'checked' : ''; ?>>
                            <label for="maintenance_team">保养组</label>
                        </div>
                        <div class="checkbox-container">
                            <input type="checkbox" name="work_commitment" id="work_commitment" value="1" <?php echo $work_commitment ? 'checked' : ''; ?>>
                            <label for="work_commitment">工作承诺书</label>
                        </div>
                        <div class="checkbox-container">
                            <input type="checkbox" name="criminal_check" id="criminal_check" value="1" <?php echo $criminal_check ? 'checked' : ''; ?>>
                            <label for="criminal_check">罪行核查</label>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <button type="submit" class="btn btn-primary"><?php echo $isEdit ? '更新' : '添加'; ?></button>
                        <a href="personnel.php" class="btn btn-secondary">返回</a>
                    </div>
                </form>
            </div>
        </div>
    </main>
</body>
</html>
