<?php
// api_agent_product_review.php - 独立的代理商产品审核API接口

header('Content-Type: application/json; charset=utf-8');

// 引入数据库配置和验证函数
require_once '../config/db.php'; // 假设数据库配置文件路径
require_once '../includes/auth.php'; // 假设认证函数文件

// 验证管理员权限
if (!requireAdmin()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => '未授权访问']);
    exit;
}

// 验证请求方法
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => '仅支持POST请求']);
    exit;
}

// 获取POST数据
$input = json_decode(file_get_contents('php://input'), true);

// 验证必要参数
if (!$input || !isset($input['id']) || !isset($input['status'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => '缺少必要参数']);
    exit;
}

$id = intval($input['id']);
$status = trim($input['status']);
$remark = isset($input['remark']) ? trim($input['remark']) : '';

// 验证状态值
if (!in_array($status, ['approved', 'rejected'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => '无效的状态值']);
    exit;
}

// 验证备注（拒绝时必填）
if ($status === 'rejected' && empty($remark)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => '拒绝时必须填写备注']);
    exit;
}

try {
    // 开启事务
    $db->beginTransaction();
    
    // 查询产品记录
    $stmt = $db->prepare("SELECT * FROM agent_products WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $product = $stmt->get_result()->fetch_assoc();
    
    if (!$product) {
        $db->rollback();
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => '产品不存在']);
        exit;
    }
    
    if ($product['status'] !== 'pending') {
        $db->rollback();
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => '产品状态不是待审核']);
        exit;
    }
    
    // 更新产品状态
    $updateStmt = $db->prepare("UPDATE agent_products SET status = ?, admin_remark = ?, updated_at = NOW() WHERE id = ?");
    $updateStmt->bind_param("ssi", $status, $remark, $id);
    
    if (!$updateStmt->execute()) {
        $db->rollback();
        throw new Exception("更新产品状态失败");
    }
    
    // 如果审核通过，将产品添加到应用表
    if ($status === 'approved') {
        $insertStmt = $db->prepare("INSERT INTO apps (name, description, price, duration_days, status, created_at) 
                                   VALUES (?, ?, ?, ?, 1, NOW())");
        $insertStmt->bind_param("ssdi", $product['name'], $product['description'], 
                               $product['price'], $product['duration_days']);
        
        if (!$insertStmt->execute()) {
            $db->rollback();
            throw new Exception("添加应用失败");
        }
        
        // 记录操作日志
        $adminId = $_SESSION['user_id'] ?? 0;
        $logStmt = $db->prepare("INSERT INTO admin_logs (admin_id, action, target_type, target_id, details, created_at) 
                                VALUES (?, 'approve_agent_product', 'agent_product', ?, ?, NOW())");
        $logDetails = json_encode([
            'product_name' => $product['name'],
            'price' => $product['price'],
            'duration_days' => $product['duration_days']
        ]);
        $logStmt->bind_param("iss", $adminId, $id, $logDetails);
        $logStmt->execute();
    }
    
    // 提交事务
    $db->commit();
    
    // 返回成功响应
    echo json_encode([
        'success' => true,
        'message' => $status === 'approved' ? '产品审核通过' : '产品已拒绝',
        'data' => [
            'id' => $id,
            'status' => $status,
            'remark' => $remark
        ]
    ]);
    
} catch (Exception $e) {
    // 回滚事务
    $db->rollback();
    
    error_log("代理商产品审核失败: " . $e->getMessage());
    
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => '系统错误，请稍后再试']);
}

?>