<?php

declare(strict_types=1);

$method = strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? 'GET'));
header('Content-Type: application/json; charset=utf-8');
header('X-Content-Type-Options: nosniff');

if ($method !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'method_not_allowed']);
    return;
}

$path = parse_url((string) ($_SERVER['REQUEST_URI'] ?? ''), PHP_URL_PATH) ?: '';
if (preg_match('#/api/v1/content/forms/([^/]+)/submissions$#', $path, $matches) !== 1) {
    http_response_code(404);
    echo json_encode(['success' => false, 'error' => 'not_found']);
    return;
}

$formId = (string) $matches[1];
$form = myronMicFormRepository()->findById($formId);
if ($form === null) {
    http_response_code(404);
    echo json_encode(['success' => false, 'error' => 'form_not_found']);
    return;
}

$raw = (string) file_get_contents('php://input');
$contentType = (string) ($_SERVER['CONTENT_TYPE'] ?? '');
$payload = str_contains($contentType, 'application/json')
    ? (json_decode($raw, true) ?: [])
    : $_POST;
if (!is_array($payload)) {
    $payload = [];
}

try {
    myronPublicInteractionTokenService()->requireValid(
        isset($payload['csrf_token']) ? (string) $payload['csrf_token'] : null,
        'form',
        $formId
    );
} catch (MyronCsrfFailureException $exception) {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => 'csrf_failed', 'message' => $exception->getMessage()], JSON_UNESCAPED_SLASHES);
    return;
}

if (myronFormHoneypotCheck($form, $payload)) {
    myronMicFormSpamCounter()->increment($formId);
    echo json_encode([
        'success' => true,
        'message' => (string) ($form['success_message'] ?? 'Thanks for submitting.'),
        'redirect_url' => null,
        'success_strategy' => (string) ($form['success_strategy'] ?? 'inline'),
    ], JSON_UNESCAPED_SLASHES);
    return;
}

$ipHash = myronFormIpHash((string) ($_SERVER['REMOTE_ADDR'] ?? ''));
myronEnsureSession();
$minuteKey = 'form_submit_minute_' . $ipHash . '_' . gmdate('YmdHi');
$hourKey = 'form_submit_hour_' . $ipHash . '_' . gmdate('YmdH');
$_SESSION[$minuteKey] = (int) ($_SESSION[$minuteKey] ?? 0) + 1;
$_SESSION[$hourKey] = (int) ($_SESSION[$hourKey] ?? 0) + 1;
if ($_SESSION[$minuteKey] > 5 || $_SESSION[$hourKey] > 30) {
    http_response_code(429);
    header('Retry-After: 60');
    echo json_encode(['success' => false, 'error' => 'rate_limited']);
    return;
}

$errors = myronFormValidateSubmission($form, $payload);
if ($errors !== []) {
    http_response_code(422);
    echo json_encode(['success' => false, 'errors' => $errors], JSON_UNESCAPED_SLASHES);
    return;
}

$fields = myronFormNormalizeSubmission($form, $payload);
$successStrategy = (string) ($form['success_strategy'] ?? 'inline');
$redirectUrl = $successStrategy === 'redirect' ? trim((string) ($form['success_redirect_url'] ?? '')) : '';
$completionRouting = is_array($form['completion_routing'] ?? null) ? $form['completion_routing'] : [];
if ($successStrategy === 'redirect' && array_is_list($completionRouting) && $completionRouting !== []) {
    foreach ($completionRouting as $rule) {
        if (!is_array($rule)) {
            continue;
        }
        $field = (string) ($rule['field'] ?? '');
        $value = (string) ($rule['value'] ?? '');
        if ($field !== '' && isset($fields[$field]) && (string) $fields[$field] === $value) {
            $redirectUrl = (string) ($rule['redirect_url'] ?? $rule['url'] ?? $redirectUrl);
            break;
        }
    }
}

$submission = myronMicFormSubmissionRepository()->create([
    'form_id' => $formId,
    'fields' => $fields,
    'source_url' => (string) ($_SERVER['HTTP_REFERER'] ?? ''),
    'ip_hash' => $ipHash,
    'user_agent' => (string) ($_SERVER['HTTP_USER_AGENT'] ?? ''),
]);
myronMicFormNotificationDispatcher()->dispatch((string) ($submission['id'] ?? ''));

echo json_encode([
    'success' => true,
    'message' => (string) ($form['success_message'] ?? 'Thanks for submitting.'),
    'redirect_url' => $redirectUrl !== '' ? $redirectUrl : null,
    'success_strategy' => $successStrategy,
], JSON_UNESCAPED_SLASHES);
