<?php
require_once '../config.php';

// 權限檢查
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'player') {
    header("Location: ../login.php");
    exit;
}

// ==========================================
// 1. 處理「完成任務」的資料送出 (POST)
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'complete_task') {
    $task_id = (int)$_POST['task_id'];
    $task_name = $_POST['task_name'];
    $estimated_time = (int)$_POST['estimated_time'];
    $actual_seconds = (int)$_POST['actual_seconds'];
    
    $actual_minutes = ceil($actual_seconds / 60);
    $local_time = date('Y-m-d H:i:s');

    try {
        $sqlite_db = getPlayerSQLiteConnection($_SESSION['sqlite_file']);
        
        // ★ 後端防護：檢查過去 10 秒內，是否已經有送出過一模一樣的任務
        $check_time = date('Y-m-d H:i:s', time() - 10);
        $stmt_check = $sqlite_db->prepare("SELECT id FROM task_history WHERE task_id = :task_id AND created_at >= :check_time");
        $stmt_check->execute([':task_id' => $task_id, ':check_time' => $check_time]);
        
        if ($stmt_check->fetch()) {
            // 如果 10 秒內已經有紀錄，代表是連點，直接導回首頁，不重複寫入
            header("Location: dashboard.php?msg=" . urlencode("任務已經送出囉，請勿重複點擊！"));
            exit;
        }

        $sql = "INSERT INTO task_history (task_id, task_name, estimated_time, actual_time, created_at) 
                VALUES (:task_id, :task_name, :estimated_time, :actual_time, :created_at)";
        $stmt = $sqlite_db->prepare($sql);
        $stmt->execute([
            ':task_id' => $task_id,
            ':task_name' => $task_name,
            ':estimated_time' => $estimated_time,
            ':actual_time' => $actual_minutes,
            ':created_at' => $local_time
        ]);

        header("Location: dashboard.php?msg=task_completed");
        exit;
    } catch (PDOException $e) {
        die("記錄任務失敗：" . $e->getMessage());
    }
}

// ==========================================
// 2. 顯示任務與計時器 (GET)
// ==========================================
if (!isset($_GET['task_id'])) {
    header("Location: dashboard.php");
    exit;
}

$task_id = (int)$_GET['task_id'];

try {
    $stmt = $mysql_db->prepare("SELECT * FROM tasks_template WHERE id = :id");
    $stmt->execute([':id' => $task_id]);
    $task = $stmt->fetch();
    if (!$task) die("找不到此任務！");
} catch (PDOException $e) {
    die("資料庫錯誤：" . $e->getMessage());
}
?>

<!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>執行任務 | 時間大富翁</title>
    <style>
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #2c3e50; color: white; margin: 0; padding: 0; display: flex; flex-direction: column; height: 100vh; text-align: center; }
        .header { padding: 20px; background-color: rgba(0,0,0,0.2); }
        .header h1 { margin: 0; font-size: 1.5rem; color: #f1c40f; }
        .header p { margin: 5px 0 0 0; color: #bdc3c7; font-size: 0.9rem; }
        .timer-container { flex: 1; display: flex; flex-direction: column; justify-content: center; align-items: center; padding: 20px; }
        .timer-circle { width: 250px; height: 250px; border-radius: 50%; border: 8px solid #3498db; display: flex; justify-content: center; align-items: center; font-size: 4rem; font-weight: bold; margin-bottom: 20px; font-variant-numeric: tabular-nums; box-shadow: 0 0 20px rgba(52, 152, 219, 0.5); transition: 0.3s; }
        .timer-circle.overtime { border-color: #e74c3c; color: #e74c3c; box-shadow: 0 0 30px rgba(231, 76, 60, 0.6); }
        .overtime-text { color: #e74c3c; font-weight: bold; font-size: 1.2rem; display: none; margin-bottom: 10px; }
        .timer-circle.overtime + .overtime-text { display: block; }
        .action-area { padding: 30px 20px; background-color: rgba(0,0,0,0.3); border-top-left-radius: 20px; border-top-right-radius: 20px; }
        .button-group { display: flex; gap: 15px; justify-content: center; margin-bottom: 20px; max-width: 400px; margin-left: auto; margin-right: auto; }
        .btn-pause { background-color: #f39c12; color: white; border: none; padding: 15px 10px; font-size: 1.2rem; font-weight: bold; border-radius: 50px; flex: 1; cursor: pointer; box-shadow: 0 6px 0 #e67e22; transition: 0.1s; }
        .btn-pause:active { transform: translateY(6px); box-shadow: 0 0 0 #e67e22; }
        .btn-pause.paused { background-color: #3498db; box-shadow: 0 6px 0 #2980b9; }
        .btn-complete { background-color: #2ecc71; color: white; border: none; padding: 15px 20px; font-size: 1.4rem; font-weight: bold; border-radius: 50px; flex: 2; cursor: pointer; box-shadow: 0 6px 0 #27ae60; transition: 0.1s; }
        .btn-complete:active { transform: translateY(6px); box-shadow: 0 0 0 #27ae60; }
        .btn-complete:disabled { background-color: #95a5a6; box-shadow: none; cursor: not-allowed; transform: none; } /* ★ 新增鎖死狀態樣式 */
        .btn-cancel { color: #95a5a6; text-decoration: none; display: inline-block; margin-top: 10px; font-size: 1rem; }
    </style>
</head>
<body>

<div class="header">
    <h1><?php echo htmlspecialchars($task['task_name']); ?></h1>
    <p>預計時間：<?php echo htmlspecialchars($task['estimated_time']); ?> 分鐘 (權重 x<?php echo htmlspecialchars($task['weight']); ?>)</p>
</div>

<div class="timer-container">
    <div class="timer-circle" id="clockDisplay">00:00</div>
    <div class="overtime-text">⚠️ 已經超時囉！請盡快完成！</div>
</div>

<div class="action-area">
    <form id="taskForm" method="POST" action="execute_task.php">
        <input type="hidden" name="action" value="complete_task">
        <input type="hidden" name="task_id" value="<?php echo $task['id']; ?>">
        <input type="hidden" name="task_name" value="<?php echo htmlspecialchars($task['task_name']); ?>">
        <input type="hidden" name="estimated_time" value="<?php echo $task['estimated_time']; ?>">
        <input type="hidden" name="actual_seconds" id="actual_seconds" value="0">
        
        <div class="button-group">
            <button type="button" class="btn-pause" id="pauseBtn" onclick="togglePause()">⏸️ 暫停</button>
            <button type="button" class="btn-complete" id="completeBtn" onclick="finishTask()">🏁 我完成了！</button>
        </div>
    </form>
    <a href="dashboard.php" class="btn-cancel" onclick="return confirm('確定要放棄這次任務嗎？時間不會被記錄喔！');">取消任務</a>
</div>

<script>
    const estimatedSeconds = <?php echo $task['estimated_time'] * 60; ?>;
    let isPaused = false; 
    let totalElapsedMs = 0;         
    let lastStartTime = Date.now(); 
    let timerInterval;

    const clockDisplay = document.getElementById('clockDisplay');
    const actualSecondsInput = document.getElementById('actual_seconds');
    const form = document.getElementById('taskForm');
    const pauseBtn = document.getElementById('pauseBtn');
    const completeBtn = document.getElementById('completeBtn'); // ★ 取得完成按鈕

    function formatTime(seconds) {
        const absSeconds = Math.abs(seconds);
        const m = Math.floor(absSeconds / 60).toString().padStart(2, '0');
        const s = (absSeconds % 60).toString().padStart(2, '0');
        return (seconds < 0 ? "-" : "") + m + ":" + s;
    }

    function updateDisplay() {
        let currentElapsedMs = totalElapsedMs;
        if (!isPaused) currentElapsedMs += (Date.now() - lastStartTime);
        let elapsedSeconds = Math.floor(currentElapsedMs / 1000);
        let remainingSeconds = estimatedSeconds - elapsedSeconds;

        if (remainingSeconds >= 0) {
            clockDisplay.innerText = formatTime(remainingSeconds);
            clockDisplay.classList.remove('overtime');
        } else {
            clockDisplay.innerText = formatTime(Math.abs(remainingSeconds));
            clockDisplay.classList.add('overtime');
        }
        return elapsedSeconds; 
    }

    timerInterval = setInterval(updateDisplay, 500);
    updateDisplay(); 

    function togglePause() {
        if (!isPaused) {
            totalElapsedMs += (Date.now() - lastStartTime);
            isPaused = true;
            pauseBtn.innerHTML = "▶️ 繼續";
            pauseBtn.classList.add('paused');
            clockDisplay.style.opacity = "0.5"; 
        } else {
            lastStartTime = Date.now();
            isPaused = false;
            pauseBtn.innerHTML = "⏸️ 暫停";
            pauseBtn.classList.remove('paused');
            clockDisplay.style.opacity = "1";
        }
    }

    function finishTask() {
        if (isPaused) {
            alert('請先點擊「繼續」再完成任務喔！');
            return;
        }
        
        // ★ 前端防護：按鈕按下去的瞬間立刻鎖死並更改文字
        completeBtn.disabled = true;
        completeBtn.innerText = "送出中...";
        pauseBtn.disabled = true;

        clearInterval(timerInterval);
        let finalElapsedSeconds = updateDisplay();
        actualSecondsInput.value = finalElapsedSeconds; 
        form.submit();
    }
</script>

</body>
</html>