<?php
// audit_proof.php - 墨家黑科技：審核判官 (V2.0)
// --------------------------------------------------
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
require_once 'db.php';

$input = file_get_contents("php://input");
$data = json_decode($input, true);

// 1. 驗收參數
if (!isset($data['proof_id']) || !isset($data['action']) || !isset($data['auditor_id'])) {
    echo json_encode(["status" => "error", "message" => "審核令無效 (缺參數)"]);
    exit;
}

$proof_id = $data['proof_id'];
$action = $data['action']; // 'approve' (通過) or 'reject' (駁回)
$auditor_id = $data['auditor_id']; // 誰審的 (例如 Rainzoowon)

try {
    $pdo->beginTransaction();

    // 2. 鎖定這筆證據
    $stmt = $pdo->prepare("SELECT tp.worker_id, t.reward, tp.status 
                           FROM task_proofs tp 
                           JOIN tasks t ON tp.task_id = t.id 
                           WHERE tp.id = :pid FOR UPDATE");
    $stmt->execute([':pid' => $proof_id]);
    $record = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$record) {
        throw new Exception("證據不存在");
    }
    if ($record['status'] !== 'pending') {
        throw new Exception("此案件已結案，無需再審。");
    }

    $worker_id = $record['worker_id'];
    $reward = $record['reward'];

    // 3. 執行判決
    if ($action === 'approve') {
        // ✅ 通過：發放獎勵 (Z幣) 給傭兵
        $pdo->prepare("UPDATE users SET coins = coins + :rew WHERE id = :wid")
            ->execute([':rew' => $reward, ':wid' => $worker_id]);
        
        // 更新狀態
        $pdo->prepare("UPDATE task_proofs SET status = 'approved' WHERE id = :pid")
            ->execute([':pid' => $proof_id]);
            
        $msg = "審核通過！已發放 $reward Z幣給傭兵。";

    } else {
        // ❌ 駁回：只更新狀態，不發錢
        $pdo->prepare("UPDATE task_proofs SET status = 'rejected' WHERE id = :pid")
            ->execute([':pid' => $proof_id]);
            
        $msg = "審核駁回。證據不足。";
    }

    $pdo->commit();
    echo json_encode(["status" => "success", "message" => $msg]);

} catch (Exception $e) {
    $pdo->rollBack();
    echo json_encode(["status" => "error", "message" => "判決失敗: " . $e->getMessage()]);
}
?>