<?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;
}

if (!isset($_POST['user_id'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing user_id']);
    exit;
}

$user_id = $_POST['user_id'];

try {
    $stmt = $pdo->prepare("SELECT * FROM profiles WHERE user_id = ? ORDER BY is_main DESC, created_at ASC");
    $stmt->execute([$user_id]);
    $profiles = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if (empty($profiles)) {
        echo json_encode([]);
    } else {
        echo json_encode($profiles);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error']);
}
?>