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

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

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

$user_id = $_SESSION['user_id'];
$user = currentUser();

// 检查是否为代理商
if ($user['is_agent'] != 1) {
    echo json_encode(['success' => false, 'message' => '只有代理商才能上传产品']);
    exit;
}

$action = $_POST['action'] ?? $_GET['action'] ?? '';

if ($action === 'upload') {
    $name = trim($_POST['name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $price = floatval($_POST['price'] ?? 0);
    $duration_days = intval($_POST['duration_days'] ?? 0);
    $commission_rate = floatval($_POST['commission_rate'] ?? 0);
    
    // 获取折扣设置
    $discount_enabled = isset($_POST['discount_enabled']) ? 1 : 0;
    $discount_type = $_POST['discount_type'] ?? 'percent';
    $discount_value = floatval($_POST['discount_value'] ?? 0);
    $stack_discount = isset($_POST['stack_discount']) ? 1 : 0;
    
    if (empty($name)) {
        echo json_encode(['success' => false, 'message' => '产品名称不能为空']);
        exit;
    }
    
    if ($price <= 0) {
        echo json_encode(['success' => false, 'message' => '价格必须大于0']);
        exit;
    }
    
    if ($commission_rate < 0 || $commission_rate > 100) {
        echo json_encode(['success' => false, 'message' => '佣金比例应在0-100之间']);
        exit;
    }
    
    // 验证折扣值
    if ($discount_enabled) {
        if ($discount_type == 'percent' && ($discount_value <= 0 || $discount_value >= 100)) {
            echo json_encode(['success' => false, 'message' => '百分比折扣应在1-99之间']);
            exit;
        }
        if ($discount_type == 'fixed' && $discount_value <= 0) {
            echo json_encode(['success' => false, 'message' => '固定折扣金额必须大于0']);
            exit;
        }
    }
    
    // 处理图片上传
    $images = [];
    if (isset($_FILES['images']) && !empty($_FILES['images']['name'][0])) {
        $upload_dir = UPLOAD_DIR . 'agent_products/';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }
        
        $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
        $max_files = 5;
        $count = 0;
        
        foreach ($_FILES['images']['tmp_name'] as $key => $tmp_name) {
            if ($count >= $max_files) break;
            if ($_FILES['images']['error'][$key] == 0) {
                $file_type = $_FILES['images']['type'][$key];
                if (!in_array($file_type, $allowed_types)) {
                    continue;
                }
                $ext = pathinfo($_FILES['images']['name'][$key], PATHINFO_EXTENSION);
                $filename = 'product_' . time() . '_' . uniqid() . '.' . $ext;
                $target = $upload_dir . $filename;
                if (move_uploaded_file($tmp_name, $target)) {
                    $images[] = UPLOAD_URL . 'agent_products/' . $filename;
                    $count++;
                }
            }
        }
    }
    
    $name = $db->escape($name);
    $description = $db->escape($description);
    $images_json = json_encode($images);
    
    $db->query("INSERT INTO agent_products (agent_id, name, description, price, duration_days, commission_rate, 
                discount_enabled, discount_type, discount_value, stack_discount, images, status) 
                VALUES ($user_id, '$name', '$description', $price, $duration_days, $commission_rate, 
                $discount_enabled, '$discount_type', $discount_value, $stack_discount, '$images_json', 'pending')");
    
    echo json_encode(['success' => true, 'message' => '产品已提交，等待审核']);
    exit;
}

echo json_encode(['success' => false, 'message' => '无效的操作']);
?>