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

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'error' => 'Invalid request method.']);
    exit;
}

try {
    $pdo = db();

    $sql = "INSERT INTO gtm_profiles (business_name, sells_what, icp, market_size, sales_motions, org_size, roles, goals) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
    $stmt = $pdo->prepare($sql);

    $stmt->execute([
        $_POST['business_name'] ?? '',
        $_POST['sells_what'] ?? '',
        $_POST['icp'] ?? '',
        $_POST['market_size'] ?? '',
        implode(', ', $_POST['sales_motions'] ?? []),
        $_POST['org_size'] ?? '',
        $_POST['roles'] ?? '',
        $_POST['goals'] ?? ''
    ]);

    $last_id = $pdo->lastInsertId();

    echo json_encode(['success' => true, 'profile_id' => $last_id]);
} catch (PDOException $e) {
    // In a real app, you would log this error, not expose it to the user.
    echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
}