<?php
require_once '../config.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

$required_fields = ['user_id', 'name', 'avatar', 'age_limit', 'is_main'];
foreach ($required_fields as $field) {
    if (!isset($_POST[$field])) {
        http_response_code(400);
        echo json_encode(['error' => "Missing $field"]);
        exit;
    }
}

$user_id = $_POST['user_id'];
$name = $_POST['name'];
$avatar = $_POST['avatar'];
$age_limit = (int)$_POST['age_limit'];
$is_main = $_POST['is_main'] === '1' ? 1 : 0;

try {
    $stmt = $pdo->prepare("INSERT INTO profiles (user_id, name, avatar, age_limit, is_main) VALUES (?, ?, ?, ?, ?)");
    $stmt->execute([$user_id, $name, $avatar, $age_limit, $is_main]);
    
    $profile_id = $pdo->lastInsertId();
    
    $stmt = $pdo->prepare("SELECT * FROM profiles WHERE id = ?");
    $stmt->execute([$profile_id]);
    $profile = $stmt->fetch(PDO::FETCH_ASSOC);
    
    echo json_encode($profile);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error']);
}
?>