<?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, ['approved', 'rejected'])) {
    echo json_encode(['success' => false, 'message' => '参数错误']);
    exit;
}

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

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

// 如果审核通过，添加到应用表
if ($status == 'approved') {
    $name = $db->escape($product['name']);
    $description = $db->escape($product['description']);
    $price = $product['price'];
    $duration_days = $product['duration_days'];
     
    
    // 检查是否已存在同名应用
    $exist = $db->fetchOne("SELECT id FROM apps WHERE name = '$name'");
    if (!$exist) {
        $db->query("INSERT INTO apps (name, description, price, duration_days, status) 
                    VALUES ('$name', '$description', $price, $duration_days, 1)");
        
        // 同时给代理商分配这个应用
        $new_app_id = $db->insertId();
        $db->query("INSERT INTO agent_apps (agent_id, app_id, agent_price, commission_rate, status) 
                    VALUES ({$product['agent_id']}, $new_app_id, $price, {$product['commission_rate']}, 1)");
    }
}

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