<?php
// api/upload_proof.php - 退璞歸真引擎 (純淨相對路徑 + 雙欄位寫入版)
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
require_once 'db.php';

// 🛡️ 確保雙欄位都存在，避免 SQL 報錯
try { $pdo->exec("ALTER TABLE task_submissions ADD COLUMN proof_img VARCHAR(255) NULL"); } catch (Exception $e) {}
try { $pdo->exec("ALTER TABLE task_submissions ADD COLUMN proof_image VARCHAR(255) NULL"); } catch (Exception $e) {}

$user_id = $_POST['user_id'] ?? 0;
$task_id = $_POST['task_id'] ?? 0;

if (!$user_id || !$task_id) {
    echo json_encode(["status" => "error", "message" => "參數錯誤，請重新登入！"]);
    exit;
}

if (!isset($_FILES['proof']) || $_FILES['proof']['error'] !== UPLOAD_ERR_OK) {
    echo json_encode(["status" => "error", "message" => "圖片上傳失敗，請檢查網路或檔案大小。"]);
    exit;
}

$file = $_FILES['proof'];
$allowedTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
if (!in_array($file['type'], $allowedTypes)) {
    echo json_encode(["status" => "error", "message" => "不支援的圖片格式！"]);
    exit;
}

$uploadDir = '../uploads/proofs/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
if (!$extension) $extension = 'jpg';
// 生成乾淨的檔名
$newFileName = 'task_' . $task_id . '_user_' . $user_id . '_' . time() . '.' . $extension;
$destination = $uploadDir . $newFileName;

if (move_uploaded_file($file['tmp_name'], $destination)) {
    try {
        $pdo->beginTransaction();
        
        $stmt = $pdo->prepare("SELECT id FROM task_submissions WHERE task_id = ? AND user_id = ? AND status = 'pending' FOR UPDATE");
        $stmt->execute([$task_id, $user_id]);
        if ($stmt->fetch()) {
            throw new Exception("您已經提交過此任務，請等待審核！");
        }

        // ✨ 核心修復：只存最純粹的相對路徑，絕不用 PHP 去亂組裝網址！
        $dbFilePath = 'uploads/proofs/' . $newFileName; 
        
        // 🛡️ 雙重保險：同時寫入舊版 proof_img 與新版 proof_image 兩個欄位！
        $stmt = $pdo->prepare("INSERT INTO task_submissions (task_id, user_id, status, proof_img, proof_image, created_at) VALUES (?, ?, 'pending', ?, ?, NOW())");
        $stmt->execute([$task_id, $user_id, $dbFilePath, $dbFilePath]);

        $pdo->commit();
        echo json_encode(["status" => "success", "message" => "✅ 截圖上傳成功！已送出人工審核。"]);
        
    } catch (Exception $e) {
        $pdo->rollBack();
        if (file_exists($destination)) unlink($destination);
        echo json_encode(["status" => "error", "message" => $e->getMessage()]);
    }
} else {
    echo json_encode(["status" => "error", "message" => "檔案儲存失敗！缺乏寫入權限 (777)。"]);
}
?>