<?php

declare(strict_types=1);

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

$method = strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? 'GET'));
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) ?: '';
$pageId = '';
if (preg_match('#/api/v1/content/pages/([^/]+)/comments$#', $path, $matches) === 1) {
    $pageId = (string) $matches[1];
} elseif ($path !== '/api/v1/content/blog-comments') {
    http_response_code(404);
    echo json_encode(['success' => false, 'error' => '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 = [];
}

if ($pageId === '') {
    $pageId = trim((string) ($payload['page_id'] ?? ''));
}

$service = myronBlogCommentService();
$page = $pageId !== '' ? myronContentRepository()->getPublishedPageById($pageId) : null;
if (!is_array($page) || !$service->canAcceptPublicSubmissionForPage($page)) {
    http_response_code(404);
    echo json_encode(['success' => false, 'error' => 'comments_unavailable']);
    return;
}

$name = trim((string) ($payload['author_name'] ?? $payload['name'] ?? ''));
$email = trim((string) ($payload['author_email'] ?? $payload['email'] ?? ''));
$body = trim((string) ($payload['body'] ?? $payload['comment'] ?? ''));
$errors = [];
if ($name === '') {
    $errors['author_name'] = 'This field is required.';
}
if ($email === '' || filter_var(myronNormalizeEmail($email), FILTER_VALIDATE_EMAIL) === false) {
    $errors['author_email'] = 'Enter a valid email address.';
}
if ($body === '') {
    $errors['body'] = 'This field is required.';
}
if (strlen($body) > 5000) {
    $errors['body'] = 'This comment is too long.';
}
if ($errors !== []) {
    http_response_code(422);
    echo json_encode(['success' => false, 'errors' => $errors], JSON_UNESCAPED_SLASHES);
    return;
}

$formKey = $service->publicSubmissionFormKey($pageId);
$verification = myronVerificationVerify($formKey, $payload);
if (!$verification->allowed) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'verification_failed']);
    return;
}

try {
    $comment = $service->createPending([
        'page_id' => $pageId,
        'page_version_id' => (string) ($page['version_id'] ?? $page['current_published_version_id'] ?? ''),
        'author_name' => $name,
        'author_email' => $email,
        'body' => $body,
        'source_url' => (string) ($_SERVER['HTTP_REFERER'] ?? $page['path'] ?? ''),
        'ip_hash' => myronFormIpHash(myronVerificationClientIp()),
        'user_agent' => (string) ($_SERVER['HTTP_USER_AGENT'] ?? ''),
    ]);
} catch (InvalidArgumentException) {
    http_response_code(422);
    echo json_encode(['success' => false, 'error' => 'invalid_comment']);
    return;
} catch (Throwable) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'server_error']);
    return;
}

http_response_code(201);
echo json_encode([
    'success' => true,
    'status' => (string) ($comment['status'] ?? BlogCommentRepository::STATUS_PENDING),
    'message' => 'Thanks. Your comment is awaiting review.',
], JSON_UNESCAPED_SLASHES);
