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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['task_id'])) {
    
    $task_id = (int)$_POST['task_id'];
    $task_name = $_POST['task_name'];
    $est_time = (int)$_POST['estimated_time']; 
    $target_time_str = trim($_POST['target_time']); 

    $now = new DateTime();
    $local_time_db = $now->format('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()) {
            header("Location: dashboard.php?msg=" . urlencode("任務已經打卡囉，請勿重複點擊！"));
            exit;
        }

        $target_dt = new DateTime($now->format('Y-m-d') . ' ' . $target_time_str);
        $diff_seconds = $target_dt->getTimestamp() - $now->getTimestamp();
        $diff_minutes = (int)floor($diff_seconds / 60);

        // ★ 核心修復：把提早與遲到的邏輯徹底分開！
        if ($diff_minutes > 0) {
            // 提早打卡：限制最高不能賺超過設定的 $est_time
            if ($diff_minutes > $est_time) {
                $diff_minutes = $est_time;
            }
            // 系統在 verify 的算法是 (est - act) = reward
            // 所以我們設定 act = est - diff_minutes
            $actual_time = $est_time - $diff_minutes;
        } else {
            // 遲到打卡 (diff_minutes 是負數)：
            // 遲到就是要被原汁原味地扣分！
            // 為了讓 (est - act) 算出來等於負的 diff_minutes，
            // 數學公式：act = est - diff_minutes
            // 舉例：est=10, 遲到20分(diff=-20)。act = 10 - (-20) = 30
            // verify 結算時：10 - 30 = -20 (成功完美倒扣！)
            $actual_time = $est_time - $diff_minutes; 
        }

        $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);
        
        $display_name = $task_name . " (目標: $target_time_str)";
        
        $stmt->execute([
            ':task_id' => $task_id,
            ':task_name' => $display_name,
            ':estimated_time' => $est_time,
            ':actual_time' => $actual_time,
            ':created_at' => $local_time_db
        ]);

        $msg = "✅ 打卡成功！";
        if ($diff_minutes > 0) {
            $msg .= " 提早了 {$diff_minutes} 分鐘，太棒了！";
        } elseif ($diff_minutes < 0) {
            $late = abs($diff_minutes);
            $msg .= " 遲到了 {$late} 分鐘，準備面對懲罰！";
        } else {
            $msg .= " 準時壓線完成！";
        }

        header("Location: dashboard.php?msg=" . urlencode($msg));
        exit;

    } catch (Exception $e) {
        die("打卡寫入失敗：" . $e->getMessage());
    }

} else {
    header("Location: dashboard.php");
    exit;
}
?>