<?php
// submit_proof.php - 任務證物提交櫃台 (截圖上傳)
// --------------------------------------------------
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
require_once 'db.php';

// 1. 檢查是否為 POST 請求且有檔案
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(["status" => "error", "message" => "請使用 POST 方法"]);
    exit;
}

$worker_id = $_POST['user_id'] ?? 0;
$task_id   = $_POST['task_id'] ?? 0;
$comment   = $_POST['comment'] ?? ''; // 暖心留言

if (!$worker_id || !$task_id || !isset($_FILES['proof_file'])) {
    echo json_encode(["status" => "error", "message" => "資料不完整 (缺 ID 或 檔案)"]);
    exit;
}

try {
    // 2. 檔案處理 (Owl 的安檢站)
    $target_dir = "../uploads/";
    $file_ext = strtolower(pathinfo($_FILES["proof_file"]["name"], PATHINFO_EXTENSION));
    
    // 檔名：proof_任務ID_執行者ID_時間戳.jpg (確保不重複)
    $new_filename = "proof_{$task_id}_{$worker_id}_" . time() . "." . $file_ext;
    $target_file = $target_dir . $new_filename;

    // 檢查格式
    $allowed = ['jpg', 'jpeg', 'png', 'gif'];
    if (!in_array($file_ext, $allowed)) {
        throw new Exception("只允許上傳圖片 (JPG, PNG, GIF)");
    }

    // 執行搬移
    if (!move_uploaded_file($_FILES["proof_file"]["tmp_name"], $target_file)) {
        throw new Exception("圖片上傳失敗，請檢查資料夾權限");
    }

    // 3. 寫入證物倉 (資料庫)
    // 注意：狀態設為 'pending' (待審核)，錢還沒發
    $sql = "INSERT INTO task_proofs (task_id, worker_id, proof_data, comment, status) 
            VALUES (:tid, :wid, :proof, :cmt, 'pending')";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':tid' => $task_id,
        ':wid' => $worker_id,
        ':proof' => $new_filename,
        ':cmt' => $comment
    ]);

    echo json_encode([
        "status" => "success",
        "message" => "截圖已上傳！等待發布者審核 (或24小時自動通過)。"
    ]);

} catch (Exception $e) {
    echo json_encode(["status" => "error", "message" => $e->getMessage()]);
}
?>