<?php
// 開啟會話
session_start();

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

// 檢查用戶是否已登錄，如果沒有則重定向到登錄頁面
if (!isLoggedIn()) {
    redirect("../index.php");
}

// 獲取即將到期的證件數量
$expiringCount = getExpiringDocumentsCount($conn);

// 定義變數
$id = $personnel_id = $pass_number = $restricted_area = $expiry_date = $return_date = "";
$status = "有效";
$errors = [];
$message = "";
$isEdit = false;
$personnel = null;

// 如果是編輯模式，獲取禁區證資訊
if (isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    $isEdit = true;
    
    $sql = "SELECT * FROM restricted_area_passes WHERE id = $id LIMIT 1";
    $result = $conn->query($sql);
    
    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $personnel_id = $row['personnel_id'];
        $pass_number = $row['pass_number'];
        $restricted_area = $row['restricted_area'];
        $expiry_date = $row['expiry_date'];
        $return_date = $row['return_date'];
        $status = $row['status'];
        
        // 獲取人員資訊
        $personnel = getPersonnelById($conn, $personnel_id);
    } else {
        $message = showError("未找到該禁區證");
        redirect("restricted_passes.php");
    }
} elseif (isset($_GET['personnel_id'])) {
    // 如果是從人員詳情頁面添加，獲取人員ID
    $personnel_id = (int)$_GET['personnel_id'];
    $personnel = getPersonnelById($conn, $personnel_id);
    
    if (!$personnel) {
        $message = showError("未找到該人員資訊");
        redirect("restricted_passes.php");
    }
}

// 處理表單提交
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // 獲取表單數據
    $personnel_id = (int)$_POST['personnel_id'];
    $pass_number = trim($_POST['pass_number']);
    $restricted_area = trim($_POST['restricted_area']);
    $expiry_date = trim($_POST['expiry_date']);
    $return_date = trim($_POST['return_date']);
    $status = trim($_POST['status']);
    
    // 驗證必填欄位
    if (empty($personnel_id)) {
        $errors[] = "必須選擇人員";
    }
    
    if (empty($pass_number)) {
        $errors[] = "禁區證號碼不能為空";
    }
    
    if (empty($restricted_area)) {
        $errors[] = "禁區區域不能為空";
    }
    
    if (empty($expiry_date)) {
        $errors[] = "有效期不能為空";
    } elseif (!validateDate($expiry_date)) {
        $errors[] = "有效期格式不正確，應為YYYY-MM-DD";
    }
    
    if (!empty($return_date) && !validateDate($return_date)) {
        $errors[] = "歸還日期格式不正確，應為YYYY-MM-DD";
    }
    
    // 如果沒有錯誤，保存資料
    if (empty($errors)) {
        if ($isEdit) {
            // 更新現有記錄
            $sql = "UPDATE restricted_area_passes SET 
                    personnel_id = ?, 
                    pass_number = ?, 
                    restricted_area = ?, 
                    expiry_date = ?, 
                    return_date = ?, 
                    status = ? 
                    WHERE id = ?";
            
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("isssssi", 
                $personnel_id, 
                $pass_number, 
                $restricted_area, 
                $expiry_date, 
                $return_date, 
                $status, 
                $id
            );
            
            if ($stmt->execute()) {
                $message = showSuccess("禁區證已成功更新");
                // 更新狀態
                updateDocumentStatus($conn, 'restricted_area_passes');
            } else {
                $message = showError("更新失敗：" . $stmt->error);
            }
            
            $stmt->close();
        } else {
            // 插入新記錄
            $sql = "INSERT INTO restricted_area_passes (
                    personnel_id, 
                    pass_number, 
                    restricted_area, 
                    expiry_date, 
                    return_date, 
                    status
                ) VALUES (?, ?, ?, ?, ?, ?)";
            
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("isssss", 
                $personnel_id, 
                $pass_number, 
                $restricted_area, 
                $expiry_date, 
                $return_date, 
                $status
            );
            
            if ($stmt->execute()) {
                $id = $stmt->insert_id;
                $message = showSuccess("禁區證已成功添加");
                // 更新狀態
                updateDocumentStatus($conn, 'restricted_area_passes');
                
                if (isset($_POST['continue']) && $_POST['continue'] == '1') {
                    // 繼續添加，重置部分表單
                    $pass_number = $restricted_area = $expiry_date = $return_date = "";
                    $status = "有效";
                } else {
                    // 返回列表或人員詳情頁
                    if (!empty($personnel_id)) {
                        redirect("personnel_view.php?id=$personnel_id");
                    } else {
                        redirect("restricted_passes.php");
                    }
                }
            } else {
                $message = showError("添加失敗：" . $stmt->error);
            }
            
            $stmt->close();
        }
    } else {
        $message = showError(implode("<br>", $errors));
    }
}

// 獲取人員列表（用於選擇）
$personnelList = [];
$sql = "SELECT id, chinese_name, english_name FROM personnel ORDER BY chinese_name, english_name";
$result = $conn->query($sql);

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

<!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">人員資訊管理</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" class="active">禁區證<?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" : "")); ?>">
                    <div class="form-group">
                        <label class="form-label">選擇人員 <span style="color: red;">*</span></label>
                        <select name="personnel_id" class="form-control" <?php echo $personnel_id ? 'disabled' : ''; ?>>
                            <option value="">請選擇人員</option>
                            <?php foreach ($personnelList as $person): ?>
                            <option value="<?php echo $person['id']; ?>" <?php echo $personnel_id == $person['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars(($person['chinese_name'] ?: $person['english_name'])); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                        <?php if ($personnel_id): ?>
                        <input type="hidden" name="personnel_id" value="<?php echo $personnel_id; ?>">
                        <?php endif; ?>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-col">
                            <div class="form-group">
                                <label class="form-label">禁區證號碼 <span style="color: red;">*</span></label>
                                <input type="text" name="pass_number" class="form-control" value="<?php echo htmlspecialchars($pass_number); ?>" required>
                            </div>
                        </div>
                        <div class="form-col">
                            <div class="form-group">
                                <label class="form-label">禁區區域 <span style="color: red;">*</span></label>
                                <input type="text" name="restricted_area" class="form-control" value="<?php echo htmlspecialchars($restricted_area); ?>" required>
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-col">
                            <div class="form-group">
                                <label class="form-label">有效期 <span style="color: red;">*</span></label>
                                <input type="date" name="expiry_date" class="form-control" value="<?php echo htmlspecialchars($expiry_date); ?>" required>
                            </div>
                        </div>
                        <div class="form-col">
                            <div class="form-group">
                                <label class="form-label">歸還日期</label>
                                <input type="date" name="return_date" class="form-control" value="<?php echo htmlspecialchars($return_date); ?>">
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">狀態</label>
                        <select name="status" class="form-control">
                            <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>
                    </div>
                    
                    <div class="form-group">
                        <button type="submit" class="btn btn-primary"><?php echo $isEdit ? '更新' : '添加'; ?></button>
                        
                        <?php if (!$isEdit): ?>
                        <div class="checkbox-container" style="margin-top: 10px;">
                            <input type="checkbox" name="continue" id="continue" value="1">
                            <label for="continue">添加後繼續</label>
                        </div>
                        <?php endif; ?>
                        
                        <?php if ($personnel_id): ?>
                        <a href="personnel_view.php?id=<?php echo $personnel_id; ?>" class="btn btn-secondary">返回人員詳情</a>
                        <?php else: ?>
                        <a href="restricted_passes.php" class="btn btn-secondary">返回列表</a>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
        </div>
    </main>
</body>
</html>
