<?php
require_once dirname(__DIR__) . '/config.php';

header('Content-Type: application/json');

// 检查登录和权限
if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => '请先登录']);
    exit;
}

$user = currentUser();
if ($user['role'] !== 'admin') {
    echo json_encode(['success' => false, 'message' => '权限不足']);
    exit;
}

$id = intval($_POST['id'] ?? 0);
$status = $_POST['status'] ?? '';
$remark = trim($_POST['remark'] ?? '');

if ($id <= 0 || !in_array($status, ['pending', 'processing', 'completed', 'rejected'])) {
    echo json_encode(['success' => false, 'message' => '参数错误']);
    exit;
}

// 获取提现记录
$withdrawal = $db->fetchOne("SELECT * FROM agent_withdrawals WHERE id = $id");
if (!$withdrawal) {
    echo json_encode(['success' => false, 'message' => '提现记录不存在']);
    exit;
}

// 更新状态
$db->query("UPDATE agent_withdrawals SET status = '$status', admin_remark = '$remark', processed_at = NOW() WHERE id = $id");

// 如果是确认到账，更新代理商已提现佣金
if ($status == 'completed') {
    $db->query("UPDATE users SET agent_withdrawn = agent_withdrawn + {$withdrawal['amount']} WHERE id = {$withdrawal['agent_id']}");
}

echo json_encode(['success' => true]);
exit;
?>