<?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;
$status = isset($_GET['status']) ? $_GET['status'] : '';

// 處理搜索請求
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 = "DELETE FROM access_cards WHERE id = $id";
    if ($conn->query($sql) === TRUE) {
        $message = showSuccess("門禁卡已成功刪除");
    } else {
        $message = showError("刪除失敗：" . $conn->error);
    }
}

// 構建查詢準則
$whereClause = [];
if (!empty($search)) {
    $search = sanitize($conn, $search);
    $whereClause[] = "(p.chinese_name LIKE '%$search%' OR p.english_name LIKE '%$search%' OR ac.card_number LIKE '%$search%' OR ac.chip_number LIKE '%$search%')";
}

if (!empty($status)) {
    $status = sanitize($conn, $status);
    $whereClause[] = "ac.status = '$status'";
}

$whereSQL = !empty($whereClause) ? "WHERE " . implode(" AND ", $whereClause) : "";

// 計算總記錄數
$countSql = "SELECT COUNT(*) as total FROM access_cards ac 
             JOIN personnel p ON ac.personnel_id = p.id 
             $whereSQL";
$countResult = $conn->query($countSql);
$totalRecords = 0;

if ($countResult && $row = $countResult->fetch_assoc()) {
    $totalRecords = (int)$row['total'];
}

// 獲取分頁資料
$offset = ($currentPage - 1) * $perPage;
$sql = "SELECT ac.*, p.chinese_name, p.english_name 
        FROM access_cards ac 
        JOIN personnel p ON ac.personnel_id = p.id 
        $whereSQL 
        ORDER BY ac.expiry_date ASC 
        LIMIT $offset, $perPage";

$result = $conn->query($sql);
$cardsList = [];

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

// 構建分頁URL
$paginationUrl = "access_cards.php?search=" . urlencode($search) . "&status=" . urlencode($status);
?>

<!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">人員資訊管理</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" class="active">門禁卡<?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="access_cards.php" style="flex: 1; margin-right: 20px;">
                    <div style="display: flex; flex-wrap: wrap;">
                        <input type="text" name="search" class="form-control" placeholder="搜索姓名、卡號..." value="<?php echo htmlspecialchars($search); ?>" style="margin-right: 10px; margin-bottom: 10px; width: 200px;">
                        
                        <select name="status" class="form-control" style="margin-right: 10px; margin-bottom: 10px; width: 150px;">
                            <option value="">所有狀態</option>
                            <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>
                        
                        <button type="submit" class="btn btn-primary" style="margin-bottom: 10px;">搜索</button>
                    </div>
                </form>
                <a href="access_cards_form.php" class="btn btn-success" style="margin-bottom: 10px;">添加門禁卡</a>
            </div>
        </div>
        
        <!-- 門禁卡列表 -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">門禁卡列表</h3>
            </div>
            <div class="card-body">
                <?php if (count($cardsList) > 0): ?>
                <table class="table">
                    <thead>
                        <tr>
                            <th>人員姓名</th>
                            <th>卡號碼</th>
                            <th>卡晶片號碼</th>
                            <th>發出日期</th>
                            <th>有效期</th>
                            <th>歸還日期</th>
                            <th>狀態</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($cardsList as $card): ?>
                        <tr>
                            <td>
                                <a href="personnel_view.php?id=<?php echo $card['personnel_id']; ?>" title="查看人員詳情">
                                    <?php echo htmlspecialchars($card['chinese_name'] ?: $card['english_name']); ?>
                                </a>
                            </td>
                            <td><?php echo htmlspecialchars($card['card_number']); ?></td>
                            <td><?php echo htmlspecialchars($card['chip_number'] ?: '-'); ?></td>
                            <td><?php echo formatDate($card['issue_date']); ?></td>
                            <td><?php echo formatDate($card['expiry_date']); ?></td>
                            <td><?php echo formatDate($card['return_date']); ?></td>
                            <td>
                                <span class="status-tag <?php echo getStatusClass($card['status']); ?>">
                                    <?php echo htmlspecialchars($card['status']); ?>
                                </span>
                            </td>
                            <td>
                                <a href="access_cards_form.php?id=<?php echo $card['id']; ?>" class="btn btn-primary action-btn">編輯</a>
                                <form method="POST" action="access_cards.php" style="display: inline;" onsubmit="return confirm('確定要刪除此門禁卡嗎？此操作不可恢復！');">
                                    <input type="hidden" name="delete_id" value="<?php echo $card['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) || !empty($status) ? '或沒有符合搜索條件的結果' : ''; ?></p>
                <?php endif; ?>
            </div>
        </div>
    </main>
</body>
</html>
