<?php
declare(strict_types=1);

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

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

function clean_text(string $value): string {
    $value = trim($value);
    $value = strip_tags($value);
    return preg_replace('/\s+/u', ' ', $value) ?? '';
}

function json_error(int $status, string $message, array $context = []): void {
    http_response_code($status);
    if ($context) {
        error_log('[submit.php] ' . $message . ' | ' . json_encode($context, JSON_UNESCAPED_SLASHES));
    } else {
        error_log('[submit.php] ' . $message);
    }
    echo json_encode(['ok' => false, 'message' => $message], JSON_UNESCAPED_SLASHES);
    exit;
}

$recaptchaSecret = getenv('RECAPTCHA_SECRET_KEY') ?: '6LdwBXUtAAAAAI14MPqpLtvaWYuHbc8QU_yxMQQL';
$hubspotPortalId = getenv('HUBSPOT_PORTAL_ID') ?: '243368203';
$hubspotFormId = getenv('HUBSPOT_FORM_ID') ?: '7b7287c1-7135-44df-9574-4f6bab4a19cf';

if ($recaptchaSecret === '') {
    json_error(500, 'Server configuration error. Please try again later.');
}

$name = clean_text((string)($_POST['name'] ?? ''));
$email = filter_var((string)($_POST['email'] ?? ''), FILTER_VALIDATE_EMAIL);
$company = clean_text((string)($_POST['company'] ?? ''));
$volume = clean_text((string)($_POST['volume'] ?? ''));
$message = clean_text((string)($_POST['message'] ?? ''));
$captchaToken = trim((string)($_POST['g-recaptcha-response'] ?? ''));

if ($name === '' || !$email || $company === '' || $volume === '') {
    json_error(422, 'Please fill all required fields.');
}

if ($captchaToken === '') {
    json_error(422, 'Please complete the reCAPTCHA challenge.');
}

$verifyPayload = http_build_query([
    'secret' => $recaptchaSecret,
    'response' => $captchaToken,
    'remoteip' => $_SERVER['REMOTE_ADDR'] ?? '',
]);

$verifyCh = curl_init('https://www.google.com/recaptcha/api/siteverify');
curl_setopt_array($verifyCh, [
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $verifyPayload,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 15,
]);
$verifyRaw = curl_exec($verifyCh);
$verifyCode = (int)curl_getinfo($verifyCh, CURLINFO_HTTP_CODE);
$verifyErr = curl_error($verifyCh);
curl_close($verifyCh);

if ($verifyRaw === false || $verifyCode !== 200) {
    json_error(502, 'Could not verify reCAPTCHA. Please try again.', [
        'http_code' => $verifyCode,
        'curl_error' => $verifyErr,
    ]);
}

$verifyData = json_decode($verifyRaw, true);
if (!is_array($verifyData) || empty($verifyData['success'])) {
    json_error(422, 'reCAPTCHA verification failed. Please try again.', [
        'google_response' => $verifyData,
    ]);
}

$parts = preg_split('/\s+/u', $name, -1, PREG_SPLIT_NO_EMPTY) ?: [];
$firstName = $parts[0] ?? '';
$lastName = count($parts) > 1 ? implode(' ', array_slice($parts, 1)) : '';

$fields = [
    ['name' => 'firstname', 'value' => $firstName],
    ['name' => 'lastname', 'value' => $lastName],
    ['name' => 'email', 'value' => (string)$email],
    ['name' => 'company', 'value' => $company],
    ['name' => 'usecase', 'value' => $volume],
    ['name' => 'message', 'value' => $message],
];

$hubspotPayload = [
    'fields' => $fields,
    'context' => [
        'pageUri' => clean_text((string)($_POST['pageUri'] ?? '')),
        'pageName' => clean_text((string)($_POST['pageName'] ?? '')),
    ],
];

if (!empty($_COOKIE['hubspotutk'])) {
    $hubspotPayload['context']['hutk'] = clean_text((string)$_COOKIE['hubspotutk']);
}

$hubspotUrl = sprintf(
    'https://api.hsforms.com/submissions/v3/integration/submit/%s/%s',
    rawurlencode($hubspotPortalId),
    rawurlencode($hubspotFormId)
);

$hubspotCh = curl_init($hubspotUrl);
curl_setopt_array($hubspotCh, [
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
    CURLOPT_POSTFIELDS => json_encode($hubspotPayload, JSON_UNESCAPED_SLASHES),
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 20,
]);
$hubspotRaw = curl_exec($hubspotCh);
$hubspotCode = (int)curl_getinfo($hubspotCh, CURLINFO_HTTP_CODE);
$hubspotErr = curl_error($hubspotCh);
curl_close($hubspotCh);

if ($hubspotRaw === false || $hubspotCode < 200 || $hubspotCode >= 300) {
    json_error(502, 'Unable to submit form right now. Please try again shortly.', [
        'http_code' => $hubspotCode,
        'curl_error' => $hubspotErr,
        'response' => $hubspotRaw,
    ]);
}

echo json_encode([
    'ok' => true,
], JSON_UNESCAPED_SLASHES);
