<?php
declare(strict_types=1);

/* ============================================================
   HARAMBEE  contact form handler
   Standalone script, unrelated to any other backend in this repo.
   Validates the submission, drops obvious bots silently, and emails
   the association. Works with or without JS (see js/contact.js).
   ============================================================ */

const TO_EMAIL   = 'info@romanian-business-club.org';
const FROM_EMAIL = 'no-reply@romanian-business-club.org';

const REASON_LABELS = [
    'membru'      => 'Devino membru',
    'parteneriat' => 'Parteneriat / Colaborare',
    'presa'       => 'Presă / Media',
    'general'     => 'Întrebare generală',
    'altele'      => 'Altele',
];

function wants_json(): bool
{
    return isset($_SERVER['HTTP_ACCEPT']) && str_contains($_SERVER['HTTP_ACCEPT'], 'application/json');
}

function respond_json(bool $ok, ?string $reason = null, int $code = 200): never
{
    http_response_code($code);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['ok' => $ok, 'reason' => $reason]);
    exit;
}

function respond_page(bool $ok, string $message): never
{
    http_response_code($ok ? 200 : 400);
    header('Content-Type: text/html; charset=utf-8');
    $title = $ok ? 'Mesaj trimis' : 'A apărut o eroare';
    echo '<!DOCTYPE html><html lang="ro"><head><meta charset="UTF-8">'
        . '<meta name="viewport" content="width=device-width, initial-scale=1.0">'
        . '<title>' . htmlspecialchars($title) . '</title><style>'
        . 'body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;'
        . 'background:#0b1110;color:#fdf1e1;font-family:system-ui,sans-serif;text-align:center;padding:24px;}'
        . '.box{max-width:520px}h1{font-size:2.2rem;margin:0 0 16px;font-weight:600}'
        . 'a{color:#fdf1e1;border-bottom:1px solid rgba(174,138,80,.5);text-decoration:none}'
        . '</style></head><body><div class="box">'
        . '<h1>' . htmlspecialchars($title) . '</h1>'
        . '<p>' . htmlspecialchars($message) . '</p>'
        . '<p><a href="contact.html">&larr; Înapoi la pagina de contact</a></p>'
        . '</div></body></html>';
    exit;
}

function clean_header_value(string $v): string
{
    return trim(preg_replace('/[\r\n]+/', ' ', $v) ?? '');
}

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
    header('Location: contact.html');
    exit;
}

$name     = trim((string)($_POST['name'] ?? ''));
$email    = trim((string)($_POST['email'] ?? ''));
$reason   = trim((string)($_POST['reason'] ?? ''));
$message  = trim((string)($_POST['message'] ?? ''));
$honeypot = trim((string)($_POST['company_website'] ?? ''));
$ts       = (float)($_POST['ts'] ?? 0);

$ajax = wants_json();
$successMessage = 'Mesajul tău a fost trimis. Îți vom răspunde cât mai curând.';

/* Silently "succeed" for bots  filled honeypot, or submitted less than
   1.5s after the page rendered its timestamp (no real person is that fast). */
$submittedTooFast = $ts > 0 && (microtime(true) * 1000 - $ts) < 1500;
if ($honeypot !== '' || $submittedTooFast) {
    if ($ajax) respond_json(true);
    respond_page(true, $successMessage);
}

$valid = $name !== '' && mb_strlen($name) <= 200
    && filter_var($email, FILTER_VALIDATE_EMAIL) && strlen($email) <= 200
    && isset(REASON_LABELS[$reason])
    && $message !== '' && mb_strlen($message) <= 5000;

if (!$valid) {
    if ($ajax) respond_json(false, 'invalid', 422);
    respond_page(false, 'Te rugăm completează corect toate câmpurile și încearcă din nou.');
}

$subject = '=?UTF-8?B?' . base64_encode('[Contact site] ' . REASON_LABELS[$reason]) . '?=';
$body = "Nume: {$name}\nEmail: {$email}\nMotiv: " . REASON_LABELS[$reason] . "\n\nMesaj:\n{$message}\n";
$headers = implode("\r\n", [
    'From: Formular contact <' . FROM_EMAIL . '>',
    'Reply-To: ' . clean_header_value($name) . ' <' . clean_header_value($email) . '>',
    'MIME-Version: 1.0',
    'Content-Type: text/plain; charset=UTF-8',
]);

$sent = @mail(TO_EMAIL, $subject, $body, $headers);

if ($ajax) respond_json($sent, $sent ? null : 'send_failed', $sent ? 200 : 502);
respond_page(
    $sent,
    $sent ? $successMessage : ('Nu am putut trimite mesajul. Te rugăm încearcă din nou sau scrie-ne la ' . TO_EMAIL . '.')
);
