<?php
// flowzoo/api/audit_action.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) {}

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $admin_id = $_GET['admin_id'] ?? null;
    $creator_id = $_GET['creator_id'] ?? null;

    try {
        if ($admin_id) {
            $stmt = $pdo->prepare("SELECT level FROM users WHERE id = ?");
            $stmt->execute([$admin_id]);
            if ($stmt->fetchColumn() < 99) throw new Exception("權限不足");
            
            // ✨ 天啟核心：COALESCE(s.proof_img, s.proof_image) 確保無論舊版新版上傳，都能把圖片路徑抓出來！
            $sql = "SELECT s.id as submission_id, s.task_id, s.user_id as miner_id, 
                           COALESCE(s.proof_img, s.proof_image) as 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) {
            // ✨ 金主後台也同步套用融合魔法
            $sql = "SELECT s.id as submission_id, s.task_id, s.user_id as miner_id, 
                           COALESCE(s.proof_img, s.proof_image) as 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("缺少身分識別參數"); }

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

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']}) 賞金";

        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') {
                $pdo->prepare("UPDATE users SET coins = coins + ? WHERE id = ?")->execute([$reward, $miner_id]);
                $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description) VALUES (?, 'TASK_REWARD', ?, ?)")->execute([$miner_id, $reward, $memo]);
                $pdo->prepare("UPDATE task_submissions SET status = 'approved' WHERE id = ?")->execute([$submission_id]);
                $msg = "已批准並發薪！";
            } else {
                $pdo->prepare("UPDATE task_submissions SET status = 'rejected' WHERE id = ?")->execute([$submission_id]);
                $msg = "已無情退回！";
            }
        } else if ($action === 'appeal') {
            if ($user_id != $miner_id) throw new Exception("非礦工");
            if ($current_status !== 'rejected' && $current_status !== '2') throw new Exception("無法申訴");
            $pdo->prepare("UPDATE task_submissions SET status = 'appealed' WHERE id = ?")->execute([$submission_id]);
            $msg = "已提交申訴！";
        } 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') {
                $pdo->prepare("UPDATE users SET coins = coins + ? WHERE id = ?")->execute([$reward, $miner_id]);
                $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description) VALUES (?, 'TASK_REWARD', ?, ?)")->execute([$miner_id, $reward, "(天啟裁決) " . $memo]);
                $pdo->prepare("UPDATE task_submissions SET status = 'approved' WHERE id = ?")->execute([$submission_id]);
                $msg = "天啟強制發薪！";
            } else {
                $pdo->prepare("UPDATE task_submissions SET status = 'rejected' WHERE id = ?")->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()]); }
}
?>