<?php
// api/admin_kyc_action.php - 天啟者 KYC 審核動作
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
require_once 'db.php';

$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents("php://input"), true);

// 🦁 驗證天啟者權限 (共用函數概念)
function checkAdmin($pdo, $admin_id) {
    $stmt = $pdo->prepare("SELECT level FROM users WHERE id = ?");
    $stmt->execute([$admin_id]);
    if ($stmt->fetchColumn() < 99) {
        echo json_encode(["status" => "error", "message" => "權限不足"]); exit;
    }
}

// 🟢 GET: 列出待審核名單
if ($method === 'GET') {
    // 找出有上傳照片(id_photo not null) 且 尚未認證(is_verified=0) 的人
    $sql = "SELECT id, username, email, id_photo, created_at FROM users WHERE id_photo IS NOT NULL AND is_verified = 0 ORDER BY created_at DESC";
    $stmt = $pdo->query($sql);
    echo json_encode(["status" => "success", "data" => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
    exit;
}

// 🔴 POST: 執行審核 (Approve / Reject)
if ($method === 'POST') {
    $admin_id = $input['admin_id'] ?? 0;
    $user_id = $input['user_id'] ?? 0;
    $action = $input['action'] ?? ''; // 'approve' or 'reject'

    checkAdmin($pdo, $admin_id);

    try {
        if ($action === 'approve') {
            // 通過：標記為已認證
            $stmt = $pdo->prepare("UPDATE users SET is_verified = 1 WHERE id = ?");
            $stmt->execute([$user_id]);
            $msg = "✅ 已通過認證，飼育員解鎖！";
        } else {
            // 拒絕：清空照片路徑 (讓使用者可以重傳)，但不刪檔案(留底或手動清)
            $stmt = $pdo->prepare("UPDATE users SET id_photo = NULL WHERE id = ?");
            $stmt->execute([$user_id]);
            $msg = "❌ 已退回申請，請使用者重新上傳。";
        }
        echo json_encode(["status" => "success", "message" => $msg]);
    } catch (Exception $e) {
        echo json_encode(["status" => "error", "message" => "操作失敗"]);
    }
    exit;
}
?>