<?php
// api/audit_action.php - 裁決引擎 (專注電腦版邏輯修復)
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
require_once 'db.php';

$method = $_SERVER['REQUEST_METHOD'];

// 🟢 GET: 撈取名單
if ($method === 'GET') {
    $admin_id = $_GET['admin_id'] ?? null;
    $creator_id = $_GET['creator_id'] ?? null;

    try {
        if ($admin_id) {
            // 👑 天啟者視角：看 appealed 與 pending/0
            $stmt = $pdo->prepare("SELECT level FROM users WHERE id = ?");
            $stmt->execute([$admin_id]);
            if ($stmt->fetchColumn() < 99) throw new Exception("權限不足");

            $sql = "SELECT s.id as submission_id, s.task_id, s.user_id as miner_id, s.proof_img, s.created_at, s.status,
                           u.username as miner_name, t.platform, t.action_type, t.reward, t.title
                    FROM task_submissions s
                    JOIN users u ON s.user_id = u.id
                    JOIN tasks t ON s.task_id = t.id
                    WHERE s.status IN ('appealed', 'pending', '0', '3')
                    ORDER BY 
                        CASE WHEN s.status IN ('appealed', '3') THEN 1 ELSE 2 END, 
                        s.created_at ASC";
            $stmt = $pdo->query($sql);

        } else if ($creator_id) {
            // 👨‍💼 發案人視角：看自己發的任務中，狀態為 pending 或 0 的案子
            $sql = "SELECT s.id as submission_id, s.task_id, s.user_id as miner_id, s.proof_img, s.created_at, s.status,
                           u.username as miner_name, t.platform, t.action_type, t.reward, t.title
                    FROM task_submissions s
                    JOIN users u ON s.user_id = u.id
                    JOIN tasks t ON s.task_id = t.id
                    WHERE t.creator_id = ? AND s.status IN ('pending', '0')
                    ORDER BY s.created_at ASC";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$creator_id]);
        } else {
            throw new Exception("缺少身分識別參數 (admin_id 或 creator_id)");
        }

        $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode(["status" => "success", "data" => $data]);
    } catch (Exception $e) {
        echo json_encode(["status" => "error", "message" => $e->getMessage()]);
    }
    exit;
}

// 🔴 POST: 執行裁決
if ($method === 'POST') {
    $input = json_decode(file_get_contents("php://input"), true);
    $user_id = $input['user_id'] ?? 0;
    $submission_id = $input['submission_id'];
    $action = $input['action'];

    try {
        $pdo->beginTransaction();

        $stmt = $pdo->prepare("SELECT s.user_id as miner_id, s.status, t.reward, t.id as task_id, t.platform, t.title, t.creator_id
                               FROM task_submissions s JOIN tasks t ON s.task_id = t.id WHERE s.id = ? FOR UPDATE");
        $stmt->execute([$submission_id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$row) throw new Exception("戰報已失效或不存在");

        $reward = $row['reward'];
        $miner_id = $row['miner_id'];
        $creator_id = $row['creator_id'];
        $current_status = strval($row['status']);
        $memo = "完成任務 #{$row['task_id']} ({$row['title']}) 賞金";

        // 1️⃣ 發案人初審 (approve / reject)
        if ($action === 'approve' || $action === 'reject') {
            if ($user_id != $creator_id) throw new Exception("只有發案人可以進行初審");
            if ($current_status !== 'pending' && $current_status !== '0') throw new Exception("此截圖已被審核過");

            if ($action === 'approve') {
                $stmt = $pdo->prepare("UPDATE users SET coins = coins + ? WHERE id = ?");
                $stmt->execute([$reward, $miner_id]);
                $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description) VALUES (?, 'TASK_REWARD', ?, ?)");
                $stmt->execute([$miner_id, $reward, $memo]);
                $stmt = $pdo->prepare("UPDATE task_submissions SET status = 'approved' WHERE id = ?");
                $stmt->execute([$submission_id]);
                $msg = "已批准！獎金已發放給接案人。";
            } else {
                $stmt = $pdo->prepare("UPDATE task_submissions SET status = 'rejected' WHERE id = ?");
                $stmt->execute([$submission_id]);
                $msg = "已退回該截圖！";
            }
        } 
        // 2️⃣ 接案人申訴 (appeal)
        else if ($action === 'appeal') {
            if ($user_id != $miner_id) throw new Exception("只有提交者可以申訴");
            if ($current_status !== 'rejected' && $current_status !== '2') throw new Exception("只有被退回的任務才能申訴");
            
            $stmt = $pdo->prepare("UPDATE task_submissions SET status = 'appealed' WHERE id = ?");
            $stmt->execute([$submission_id]);
            $msg = "已提交申訴！交由天啟者裁決。";
        }
        // 3️⃣ 天啟者介入 (force_approve / force_reject)
        else if ($action === 'force_approve' || $action === 'force_reject') {
            $stmt = $pdo->prepare("SELECT level FROM users WHERE id = ?");
            $stmt->execute([$user_id]);
            if ($stmt->fetchColumn() < 99) throw new Exception("越權操作！");
            
            if ($action === 'force_approve') {
                $stmt = $pdo->prepare("UPDATE users SET coins = coins + ? WHERE id = ?");
                $stmt->execute([$reward, $miner_id]);
                $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description) VALUES (?, 'TASK_REWARD', ?, ?)");
                $stmt->execute([$miner_id, $reward, "(天啟者強制通過) " . $memo]);
                $stmt = $pdo->prepare("UPDATE task_submissions SET status = 'approved' WHERE id = ?");
                $stmt->execute([$submission_id]);
                $msg = "天啟裁決：強制發放獎金！";
            } else {
                $stmt = $pdo->prepare("UPDATE task_submissions SET status = 'rejected' WHERE id = ?");
                $stmt->execute([$submission_id]);
                $msg = "天啟裁決：已無情駁回！";
            }
        }

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

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