<?php
// api/upload_proof.php - 終極圖片上傳引擎 (雙宇宙絕對網址定位版)
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
require_once 'db.php';

// 🛡️ 確保資料庫有儲存圖片路徑的欄位
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) {
    $errCode = $_FILES['proof']['error'] ?? '未知';
    $errMsg = "圖片接收失敗！";
    if ($errCode == UPLOAD_ERR_INI_SIZE || $errCode == UPLOAD_ERR_FORM_SIZE) $errMsg = "圖片檔案太大！";
    elseif ($errCode == UPLOAD_ERR_PARTIAL) $errMsg = "圖片只有部分上傳。";
    elseif ($errCode == UPLOAD_ERR_NO_FILE) $errMsg = "沒有選擇圖片。";
    echo json_encode(["status" => "error", "message" => "{$errMsg} (錯誤碼: {$errCode})"]);
    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)) {
    if (!mkdir($uploadDir, 0777, true)) {
         echo json_encode(["status" => "error", "message" => "無法建立資料夾，請檢查伺服器權限！"]);
         exit;
    }
}

$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("您已經提交過此任務，請等待審核！");
        }

        // ✨ 天啟跨宇宙修復核心：動態產生「完整的絕對網址 (https://...)」
        $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https')) ? "https://" : "http://";
        $domain = $_SERVER['HTTP_HOST'];
        $basePath = dirname(dirname($_SERVER['PHP_SELF'])); 
        if ($basePath == DIRECTORY_SEPARATOR || $basePath == '\\' || $basePath == '/') $basePath = '';
        $basePath = str_replace('\\', '/', $basePath);
        
        // 將完整的網址存入資料庫，徹底解決破圖問題！
        $dbFilePath = $protocol . $domain . $basePath . '/uploads/proofs/' . $newFileName; 
        
        $stmt = $pdo->prepare("INSERT INTO task_submissions (task_id, user_id, status, proof_image, created_at) VALUES (?, ?, 'pending', ?, NOW())");
        $stmt->execute([$task_id, $user_id, $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)。"]);
}
?>