<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/functions.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_val = $_POST['status'] ?? '';
$remark = trim($_POST['remark'] ?? '');

if ($id <= 0) {
    echo json_encode(['success' => false, 'message' => '参数错误']);
    exit;
}

$application = $db->fetchOne("SELECT * FROM agent_applications WHERE id = $id");
if (!$application) {
    echo json_encode(['success' => false, 'message' => '申请不存在']);
    exit;
}

if (!in_array($status_val, ['approved', 'rejected'])) {
    echo json_encode(['success' => false, 'message' => '状态无效']);
    exit;
}

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

if ($status_val == 'approved') {
    // 更新用户为代理商
    $db->query("UPDATE users SET is_agent = 1, agent_level = 1 WHERE id = {$application['user_id']}");
}

echo json_encode(['success' => true, 'message' => '审核成功']);
exit;