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