<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/layout.php';
require_once __DIR__ . '/../includes/captcha.php';

session_start_once();

$errors = [];
$old    = [];
$done   = false;

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {

    if (!csrf_check($_POST['csrf'] ?? null)) {
        $errors[] = t('err_csrf');
    }
    // ловушка для роботов
    if (trim((string)($_POST['website'] ?? '')) !== '') {
        audit('spam.honeypot', 'contact', null, []);
        header('Location: /contact?ok=1'); exit;   // молча
    }
    // слишком быстрое заполнение
    $rendered = (int)($_SESSION['contact_rendered_at'] ?? 0);
    if ($rendered > 0 && (time() - $rendered) < 3) {
        audit('spam.too_fast', 'contact', null, ['seconds' => time() - $rendered]);
        header('Location: /contact?ok=1'); exit;
    }

    $old = [
        'name'  => trim((string)($_POST['name'] ?? '')),
        'email' => trim((string)($_POST['email'] ?? '')),
        'body'  => trim((string)($_POST['body'] ?? '')),
    ];

    if ($old['name'] === '' || $old['body'] === '') {
        $errors[] = t('err_required');
    }
    if (!filter_var($old['email'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = t('err_email');
    }
    // капча спрашивается только у подозрительных
    if (!empty($_POST['captcha_shown']) && !captcha_check((string)($_POST['captcha'] ?? ''))) {
        $errors[] = t('err_captcha');
    }
    // жёсткий предел на канал
    $ip = client_ip_binary();
    if ($ip !== null) {
        $st = db()->prepare('SELECT COUNT(*) FROM contact_messages WHERE ip = ? AND created_at > NOW() - INTERVAL 1 HOUR');
        $st->execute([$ip]);
        if ((int)$st->fetchColumn() >= 5) {
            $errors[] = t('err_rate');
        }
    }

    if (!$errors) {
        $ins = db()->prepare('INSERT INTO contact_messages (name, email, body, lang, ip, user_agent)
                              VALUES (?,?,?,?,?,?)');
        $ins->execute([$old['name'], $old['email'], $old['body'], current_lang(),
                       $ip, mb_substr((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 255)]);
        $mid = (int)db()->lastInsertId();

        $to = trim((string)setting('fallback_email', ''));
        if ($to !== '') {
            $subject = 'Повідомлення з сайту служби підтримки ПВУ III';
            $body = "Надійшло повідомлення через форму зв'язку на сайті.\n\n"
                  . "Ім'я: {$old['name']}\n"
                  . "Пошта для відповіді: {$old['email']}\n"
                  . "Мова сторінки: " . current_lang() . "\n"
                  . "Час: " . date('d.m.Y H:i') . "\n\n"
                  . "Повідомлення:\n{$old['body']}\n";
            queue_mail($to, $subject, $body, null);
            db()->prepare('UPDATE contact_messages SET status = "queued" WHERE id = ?')->execute([$mid]);
        }
        audit('contact.create', 'contact', $mid, ['email' => $old['email']]);
        header('Location: /contact?ok=1'); exit;
    }
}

$done      = isset($_GET['ok']);
$needCap   = captcha_required();
$_SESSION['contact_rendered_at'] = time();

page_header(t('contact_title'), 'contact');
?>
<section class="hero">
  <h1><?= e(t('contact_title')) ?></h1>
  <p class="lead"><?= e(t('contact_intro')) ?></p>
</section>

<?php if ($done): ?>
  <div class="alert ok-box"><?= e(t('contact_done')) ?></div>
  <p><a class="btn primary" href="/"><?= e(t('contact_back')) ?></a></p>
<?php else: ?>
  <?php if ($errors): ?>
    <div class="alert error"><ul><?php foreach (array_unique($errors) as $er): ?><li><?= e($er) ?></li><?php endforeach; ?></ul></div>
  <?php endif; ?>
  <form class="card form" method="post" action="/contact">
    <?= contact_form_fields($needCap, $old) ?>
    <div class="form-actions">
      <a class="btn ghost" href="/"><?= e(t('contact_cancel')) ?></a>
      <button type="submit" class="btn primary"><?= e(t('contact_send')) ?></button>
    </div>
  </form>
<?php endif;
page_footer();
