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