<?php
session_start();
require 'config.php';

$page = $_GET['page'] ?? 'login';
$message = '';
$status = $_GET['status'] ?? '';

// --- 邏輯處理 ---

// 1. 處理登入
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $page === 'login') {
    $id_card = cleanInput($_POST['id_card']);
    
    // 驗證學生
    $stmt = $pdo->prepare("SELECT * FROM students WHERE id_card = ?");
    $stmt->execute([$id_card]);
    $student = $stmt->fetch();

    if ($student) {
        $_SESSION['student_id'] = $student['id'];
        $_SESSION['student_name'] = $student['name'];
        $_SESSION['class_code'] = $student['class_code'];
        $_SESSION['id_card_mask'] = $student['id_card']; // Log 用
        
        // Log: 登入成功
        writeLog($pdo, $student['id_card'], "使用者登入成功: " . $student['name']);
        
        header("Location: index.php?page=list");
        exit;
    } else {
        // Log: 登入失敗
        writeLog($pdo, $id_card, "登入失敗: 查無此身分證號");
        $message = "找不到此身分證號，請確認輸入是否正確。";
    }
}

// 登出
if ($page === 'logout') {
    if (isset($_SESSION['id_card_mask'])) {
        writeLog($pdo, $_SESSION['id_card_mask'], "使用者登出");
    }
    session_destroy();
    header("Location: index.php");
    exit;
}

// 驗證 Session
$student_user = null;
if (isset($_SESSION['student_id'])) {
    $stmt = $pdo->prepare("SELECT * FROM students WHERE id = ?");
    $stmt->execute([$_SESSION['student_id']]);
    $student_user = $stmt->fetch();
}

if (!$student_user && $page !== 'login') {
    header("Location: index.php?page=login");
    exit;
}

// 2. 處理表單提交
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $page === 'submit_form') {
    $activity_id = $_POST['activity_id'];
    $will_attend = $_POST['will_attend'] ?? '';
    $lunch_type = $_POST['lunch_type'] ?? null;
    $note = cleanInput($_POST['note']);
    $signature = $_POST['signature_data']; 

    // 檢查活動是否存在及過期
    $stmt = $pdo->prepare("SELECT * FROM activities WHERE id = ?");
    $stmt->execute([$activity_id]);
    $act = $stmt->fetch();

    if (!$act) die("活動不存在");
    
    // 檢查是否已填寫過 (防止重複送出或惡意修改)
    $chkStmt = $pdo->prepare("SELECT id FROM responses WHERE activity_id = ? AND student_id = ?");
    $chkStmt->execute([$activity_id, $student_user['id']]);
    if ($chkStmt->fetch()) {
        writeLog($pdo, $student_user['id_card'], "試圖重複提交活動ID: $activity_id");
        die("您已填寫過此表單，不可重複修改。");
    }

    if (strtotime($act['survey_end']) < time()) {
        writeLog($pdo, $student_user['id_card'], "試圖提交已過期活動ID: $activity_id");
        die("調查已截止，無法填寫。");
    }

    // 後端強制驗證
    if (empty($will_attend) || empty($signature)) {
        die("錯誤：參加意願與簽名為必填欄位。");
    }
    if ($will_attend === 'Y' && empty($lunch_type)) {
        die("錯誤：參加者必須選擇午餐葷素。");
    }

    // 儲存回覆
    $sql = "INSERT INTO responses 
            (activity_id, student_id, class_code, seat_no, student_name, will_attend, lunch_type, note, parent_signature, ip_address, signed_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        $activity_id, $student_user['id'], $student_user['class_code'], 
        $student_user['seat_no'], $student_user['name'], $will_attend, 
        $lunch_type, $note, $signature, $_SERVER['REMOTE_ADDR']
    ]);

    // Log: 提交表單
    writeLog($pdo, $student_user['id_card'], "提交活動回覆 (ID:$activity_id): 意願=$will_attend");

    header("Location: index.php?page=list&status=success");
    exit;
}

// --- 視圖呈現 ---
?>
<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>戶外教育行前通知暨意願調查 - <?php echo SCHOOL_NAME; ?></title>
    <link rel="stylesheet" href="style.css">
    <style>
        .rich-text-content ul, .rich-text-content ol { padding-left: 20px; margin: 5px 0; }
        .rich-text-content p { margin: 5px 0; }
        .rich-text-content img { max-width: 100%; height: auto; }
    </style>
</head>
<body>

<div class="container">
    <div class="no-print">
        <header style="border-bottom: 2px solid #eee; margin-bottom: 20px; padding-bottom: 10px;">
            <h2 style="margin-bottom: 5px;"><?php echo SCHOOL_NAME; ?></h2>
            <?php if ($student_user): ?>
                <div style="display:flex; justify-content:space-between; align-items:center;">
                    <span style="font-size:0.9rem; color:#666;">
                        學生：<?php echo htmlspecialchars($student_user['class_code'] . ' ' . $student_user['name']); ?>
                    </span>
                    <a href="index.php?page=logout" class="btn btn-secondary" style="padding:5px 10px; font-size:0.8rem;">登出</a>
                </div>
            <?php endif; ?>
        </header>

        <?php if ($message): ?>
            <div style="background:#fce4e4; padding:15px; margin-bottom:20px; border-radius:6px; color:#c0392b; text-align:center; font-weight:bold;">
                <?php echo $message; ?>
            </div>
        <?php endif; ?>

        <?php if ($status == 'success'): ?>
            <div style="background:#d4edda; padding:15px; margin-bottom:20px; border-radius:6px; color:#155724; text-align:center; font-weight:bold;">
                填寫成功！感謝您的回覆。
            </div>
        <?php endif; ?>
    </div>
    <!-- 頁面 1: 登入 -->
    <?php if ($page === 'login'): ?>
        <div style="max-width: 400px; margin: 30px auto; text-align: center;">
            <h2>戶外教育行前通知暨意願調查</h2>
            <h3>家長登入</h3>
            <form method="POST">
                <p>請輸入學生的身分證字號</p>
                <input type="text" name="id_card" placeholder="例如: A123456789" required style="text-transform: uppercase; font-size:1.2rem; text-align:center;">
                <button type="submit" class="btn btn-block" style="font-size:1.2rem;">登入系統</button>
            </form>
        </div>

    <!-- 頁面 2: 活動列表 -->
    <?php elseif ($page === 'list'): ?>
        <h3>活動列表</h3>
        <?php
        $class_code = $student_user['class_code'];
        // 撈取活動與該學生的回覆狀況
        $sql = "SELECT a.*, r.will_attend, r.signed_at, r.id as response_id
                FROM activities a 
                LEFT JOIN responses r ON a.id = r.activity_id AND r.student_id = ?
                WHERE a.target_classes LIKE ? 
                ORDER BY a.date DESC";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$student_user['id'], "%$class_code%"]);
        $activities = $stmt->fetchAll();

        if (count($activities) == 0): ?>
            <p>目前沒有給貴班的戶外教學活動。</p>
        <?php else: ?>
            <table>
                <thead>
                    <tr>
                        <th>活動名稱</th>
                        <th>日期</th>
                        <th>截止日期</th>
                        <th>狀態</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($activities as $act): 
                    $is_expired = strtotime($act['survey_end']) < time();
                    $has_response = !empty($act['response_id']);
                    
                    if ($has_response) {
                        $status_text = $act['will_attend'] == 'Y' ? '已填:參加' : '已填:不參加';
                        $status_class = $act['will_attend'] == 'Y' ? 'badge-yes' : 'badge-no';
                        $btn_text = "查看/列印";
                        $btn_class = "btn-secondary";
                    } else {
                        $status_text = '未填寫';
                        $status_class = '';
                        $btn_text = "填寫意願";
                        $btn_class = "btn";
                    }
                ?>
                    <tr>
                        <td data-label="活動名稱"><?php echo htmlspecialchars($act['name']); ?></td>
                        <td data-label="日期"><?php echo $act['date']; ?></td>
                        <td data-label="截止" style="<?php echo ($is_expired && !$has_response) ? 'color:red;' : ''; ?>">
                            <?php echo date('m/d H:i', strtotime($act['survey_end'])); ?>
                        </td>
                        <td data-label="狀態"><span class="badge <?php echo $status_class; ?>"><?php echo $status_text; ?></span></td>
                        <td data-label="操作">
                            <?php if ($has_response): ?>
                                <!-- 已填寫：進入唯讀/列印模式 -->
                                <a href="index.php?page=form&id=<?php echo $act['id']; ?>" class="btn <?php echo $btn_class; ?>"><?php echo $btn_text; ?></a>
                            <?php elseif (!$is_expired): ?>
                                <!-- 未填寫且未過期 -->
                                <a href="index.php?page=form&id=<?php echo $act['id']; ?>" class="btn <?php echo $btn_class; ?>"><?php echo $btn_text; ?></a>
                            <?php else: ?>
                                <span style="color:#999; font-size:0.9rem;">(已截止，請洽導師)</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>

    <!-- 頁面 3: 表單 / 檢視頁面 -->
    <?php elseif ($page === 'form' && isset($_GET['id'])): ?>
        <?php
        $act_id = $_GET['id'];
        // 取得活動資料
        $stmt = $pdo->prepare("SELECT * FROM activities WHERE id = ?");
        $stmt->execute([$act_id]);
        $activity = $stmt->fetch();
        if(!$activity) die("活動不存在");

        // 取得回覆資料
        $stmt = $pdo->prepare("SELECT * FROM responses WHERE activity_id = ? AND student_id = ?");
        $stmt->execute([$act_id, $student_user['id']]);
        $response = $stmt->fetch();
        
        $is_readonly = !empty($response); // 是否為唯讀模式
        ?>
        
        <div class="print-area">
            <h2 style="text-align:center; margin-bottom:10px;">
                <?php echo htmlspecialchars($activity['name']); ?><br>
                <small style="font-size:0.7em;">行前通知單暨家長同意書</small>
            </h2>
            
            <div style="border:1px solid #ddd; padding:15px; margin-bottom:10px; border-radius:4px; background-color:#fff;">
                <p><strong>親愛的家長您好：</strong></p>
                <p>本校辦理戶外教學，誠摯邀請貴子弟參加。</p>
                <ul style="list-style: none; padding-left: 0;">
                    <li>📅 <strong>時間：</strong><?php echo $activity['date']; ?></li>
                    <li>📍 <strong>地點：</strong><?php echo htmlspecialchars($activity['location1']); ?></li>
                    <?php echo $activity['location2'] ? '<li>　 　 　　'.htmlspecialchars($activity['location2']).'</li>' : ''; ?></li>
                    <li>🏫 <strong>單位：</strong><?php echo htmlspecialchars($activity['unit_name']); ?></li>
                </ul>
                <hr style="border:0; border-top:1px dashed #eee;">
                <div><strong>📃 活動說明：</strong><div class="rich-text-content"><?php echo $activity['description']; ?></div></div>
                <div><strong>⚠️ 注意事項：</strong><div class="rich-text-content"><?php echo $activity['notice']; ?></div></div>
            </div>

            <!-- 模式切換：唯讀 vs 填寫 -->
            <?php if ($is_readonly): ?>
                
                <!-- === 唯讀與列印介面 === -->
                <div class="readonly-box">
                    <h3 style="text-align:center; border-bottom:2px solid #ccc; padding-bottom:5px;">回條填寫確認單</h3>
                    
                    <div class="readonly-field">
                        <span class="readonly-label">1. 參加意願：</span>
                        <span class="readonly-value">
                            <?php echo $response['will_attend'] == 'Y' ? '✅ 參加' : '❌ 不參加'; ?>
                        </span>
                    </div>

                    <?php if ($response['will_attend'] == 'Y'): ?>
                    <div class="readonly-field">
                        <span class="readonly-label">2. 午餐選擇：</span>
                        <span class="readonly-value">
                            <?php echo $response['lunch_type'] == 'meat' ? '🍖 葷食' : '🥦 素食'; ?>
                        </span>
                    </div>
                    <?php endif; ?>

                    <div class="readonly-field">
                        <span class="readonly-label">3. 備註事項：</span>
                        <span class="readonly-value">
                            <?php echo $response['note'] ? nl2br(htmlspecialchars($response['note'])) : '無'; ?>
                        </span>
                    </div>

                    <div class="readonly-field" style="border-bottom:none;">
                        <span class="readonly-label" style="vertical-align: top;">4. 家長簽名：</span>

                        <?php 
                        $sig = $response['parent_signature'];
                        if ($sig):
                            if (strpos($sig, 'data:image') === 0): ?>
                                <img src="<?php echo $sig; ?>" class="signature-img" alt="家長簽名">
                            <?php else: ?>
                                <span style="color: #d35400; font-weight: bold; font-size: 0.9em;">
                                    <?php echo htmlspecialchars(str_replace('text:', '', $sig)); ?>
                                </span>
                            <?php endif; 
                        endif; ?>

                        <p style="font-size:0.8rem; color:#888;">簽署時間：<?php echo $response['signed_at']; ?></p>
                    </div>
                </div>

                <div class="no-print" style="margin-top:20px; text-align:center;">
                    <button onclick="window.print()" class="btn" style="width:100%; max-width:300px; font-size:1.2rem;">🖨️ 列印通知單</button>
                    <br><br>
                    <a href="index.php?page=list" class="btn btn-secondary">返回列表</a>
                </div>

            <?php else: ?>

                <!-- === 填寫表單介面 === -->
                <form id="surveyForm" method="POST" action="index.php?page=submit_form" class="no-print">
                    <input type="hidden" name="activity_id" value="<?php echo $activity['id']; ?>">
                    
                    <h3 style="background:#eee; padding:10px;">回條填寫</h3>
                    
                    <div style="margin-bottom: 20px;">
                        <label style="color:red;">* 1. 請問貴子弟是否參加？</label><br>
                        <div style="padding:10px 0;">
                            <label><input type="radio" name="will_attend" value="Y" onclick="toggleLunch(true)" required> 參加</label>
                            <label><input type="radio" name="will_attend" value="N" onclick="toggleLunch(false)"> 不參加</label>
                        </div>
                    </div>

                    <div id="lunch_section" style="margin-bottom: 20px; display:none;">
                        <label style="color:red;">* 2. 若參加，午餐選擇？</label><br>
                        <div style="padding:10px 0;">
                            <label><input type="radio" name="lunch_type" value="meat"> 葷食</label>
                            <label><input type="radio" name="lunch_type" value="veg"> 素食</label>
                        </div>
                    </div>

                    <div style="margin-bottom: 20px;">
                        <label>3. 孩子近期需特別注意事項 (選填)：</label>
                        <textarea name="note" rows="3" placeholder="例如：身體不適、過敏..."></textarea>
                    </div>

                    <div style="margin-bottom: 20px;">
                        <label style="color:red;">* 4. 家長簽名 (請直接在下方框框內書寫)：</label>
                        <div id="signature-pad">
                            <canvas id="the_canvas"></canvas>
                        </div>
                        <button type="button" class="btn btn-secondary" onclick="clearCanvas()" style="margin-top:5px; font-size:0.8rem;">清除重簽</button>
                        <input type="hidden" name="signature_data" id="signature_data">
                    </div>
                    
                    <button type="submit" class="btn btn-block" style="font-size:1.2rem; padding:15px;" onclick="return validateForm()">送出確認 (不可修改)</button>
                    <button type="button" class="btn btn-secondary btn-block" style="font-size:1.2rem; padding:15px;" onclick="location.href='index.php?page=list'">取消返回</button>
                </form>

                <script>
                    // Canvas 簽名板邏輯
                    var canvas = document.getElementById('the_canvas');
                    var ctx = canvas.getContext('2d');
                    var isDrawing = false;
                    var hasSigned = false; // 追蹤是否已簽名

                    function resizeCanvas() {
                        var parent = document.getElementById('signature-pad');
                        if(parent) {
                            // 保存當前影像內容 (避免 resize 清空)
                            // 這裡為簡化，resize 會清空，建議提示使用者
                            canvas.width = parent.offsetWidth;
                            canvas.height = parent.offsetHeight;
                            ctx.lineWidth = 3;
                            ctx.lineCap = 'round';
                            ctx.strokeStyle = '#000';
                            hasSigned = false;
                        }
                    }
                    window.addEventListener('resize', resizeCanvas);
                    setTimeout(resizeCanvas, 100); // 確保 DOM 載入後執行

                    function getPos(e) {
                        var rect = canvas.getBoundingClientRect();
                        var x, y;
                        if (e.touches) {
                            x = e.touches[0].clientX - rect.left;
                            y = e.touches[0].clientY - rect.top;
                        } else {
                            x = e.clientX - rect.left;
                            y = e.clientY - rect.top;
                        }
                        return {x: x, y: y};
                    }

                    function startDraw(e) {
                        isDrawing = true;
                        var pos = getPos(e);
                        ctx.beginPath();
                        ctx.moveTo(pos.x, pos.y);
                        // 避免觸控時同時滾動頁面
                        if(e.type === 'touchstart' || e.type === 'touchmove') {
                           // e.preventDefault(); // 視需求開啟，開啟後簽名時頁面無法捲動
                        }
                    }

                    function draw(e) {
                        if (!isDrawing) return;
                        var pos = getPos(e);
                        ctx.lineTo(pos.x, pos.y);
                        ctx.stroke();
                        hasSigned = true;
                        if(e.type === 'touchmove') e.preventDefault(); // 防止拖曳時頁面亂跑
                    }

                    function endDraw() {
                        isDrawing = false;
                    }

                    if(canvas) {
                        canvas.addEventListener('mousedown', startDraw);
                        canvas.addEventListener('mousemove', draw);
                        canvas.addEventListener('mouseup', endDraw);
                        canvas.addEventListener('touchstart', startDraw, {passive: false});
                        canvas.addEventListener('touchmove', draw, {passive: false});
                        canvas.addEventListener('touchend', endDraw);
                    }

                    function clearCanvas() {
                        ctx.clearRect(0, 0, canvas.width, canvas.height);
                        hasSigned = false;
                    }

                    function toggleLunch(isYes) {
                        var section = document.getElementById('lunch_section');
                        var radios = document.getElementsByName('lunch_type');
                        if (isYes) {
                            section.style.display = 'block';
                            // 設為必填
                            for(var i=0; i<radios.length; i++) radios[i].required = true;
                        } else {
                            section.style.display = 'none';
                            // 取消必填
                            for(var i=0; i<radios.length; i++) {
                                radios[i].required = false;
                                radios[i].checked = false;
                            }
                        }
                    }

                    function validateForm() {
                        // 1. 檢查意願
                        var attend = document.querySelector('input[name="will_attend"]:checked');
                        if (!attend) {
                            alert('請選擇「參加」或「不參加」');
                            return false;
                        }

                        // 1.5 檢查午餐 (若參加則必填)
                        if (attend.value === 'Y') {
                            var lunch = document.querySelector('input[name="lunch_type"]:checked');
                            if (!lunch) {
                                alert('請選擇午餐（葷食或素食）');
                                return false;
                            }
                        }

                        // 2. 檢查簽名 (利用空白畫布的 DataURL 長度或是 hasSigned 變數)
                        if (!hasSigned) {
                            alert('請在簽名框內簽名');
                            return false;
                        }

                        // 寫入 hidden input
                        var dataUrl = canvas.toDataURL();
                        document.getElementById('signature_data').value = dataUrl;

                        return confirm('確認送出？送出後將無法修改資料。');
                    }
                </script>
            <?php endif; ?>
        </div>
    <?php endif; ?>

</div>
</body>
</html>