<?php
ini_set('display_errors', '0');
ini_set('log_errors', '1');
error_reporting(E_ALL);

// If a fatal error occurs, show a friendly page instead of a blank 500.
register_shutdown_function(function () {
    $err = error_get_last();
    if (!$err) return;
    $fatal = [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR];
    if (!in_array($err['type'], $fatal, true)) return;

    $id = 'contact_' . date('Ymd_His') . '_' . bin2hex(random_bytes(4));
    error_log("[{$id}] Contact page fatal: {$err['message']} in {$err['file']}:{$err['line']}");

    http_response_code(500);
    header('Content-Type: text/html; charset=UTF-8');
    echo "<!doctype html><html><head><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1'>";
    echo "<title>Contact — error</title></head><body style='font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif; padding:24px; color:#111;'>";
    echo "<h1 style='margin:0 0 10px'>Something went wrong</h1>";
    echo "<p style='margin:0 0 14px'>The contact page hit an internal error on the server.</p>";
    echo "<p style='margin:0 0 14px'><strong>Error id:</strong> <code>{$id}</code></p>";
    echo "<p style='margin:0'>Check your server logs (Apache/PHP error log) for this id to see the exact cause.</p>";
    echo "</body></html>";
    exit;
});

require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/includes/email.php';
require_once __DIR__ . '/includes/contact-fallback-store.php';

// CSRF token
if (empty($_SESSION['contact_csrf'])) {
    $_SESSION['contact_csrf'] = bin2hex(random_bytes(32));
}

$successMessage = '';
$errorMessage = '';
$values = ['name' => '', 'email' => '', 'phone' => '', 'notes' => ''];

function h($v) { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $values['name']  = trim($_POST['name'] ?? '');
    $values['email'] = trim($_POST['email'] ?? '');
    $values['phone'] = trim($_POST['phone'] ?? '');
    $values['notes'] = trim($_POST['notes'] ?? '');

    $csrf = $_POST['csrf'] ?? '';
    $honeypot = trim($_POST['company'] ?? ''); // should stay empty

    // lightweight rate limit (per session)
    $now = time();
    $last = $_SESSION['contact_last_submit'] ?? 0;

    if (!hash_equals($_SESSION['contact_csrf'], $csrf)) {
        $errorMessage = 'Please refresh the page and try again.';
    } elseif ($honeypot !== '') {
        $errorMessage = 'Submission failed. Please try again.';
    } elseif ($last && ($now - $last) < 15) {
        $errorMessage = 'Please wait a moment and try again.';
    } elseif ($values['name'] === '') {
        $errorMessage = 'Name is required.';
    } elseif (!filter_var($values['email'], FILTER_VALIDATE_EMAIL)) {
        $errorMessage = 'Please enter a valid email address.';
    } elseif ($values['notes'] === '') {
        $errorMessage = 'Notes are required.';
    } else {
        $_SESSION['contact_last_submit'] = $now;

        try {
            $emailService = new EmailService();
            $result = $emailService->sendContactUs(CONTACT_FORM_TO, $values);
        } catch (Throwable $e) {
            error_log("Contact email init/send failed: " . $e->getMessage());
            $result = ['success' => false];
        }

        if (!empty($result['success'])) {
            $successMessage = 'Thanks — we received your message and will get back to you shortly.';
            $values = ['name' => '', 'email' => '', 'phone' => '', 'notes' => ''];
            // rotate token so refresh doesn't resubmit
            $_SESSION['contact_csrf'] = bin2hex(random_bytes(32));
        } elseif (contact_fallback_store_record($values)) {
            error_log('Contact form: submission stored in site/storage/contact_submissions.jsonl (SMTP and mail() both failed)');
            $successMessage = 'Thanks — we received your message and will get back to you shortly.';
            $values = ['name' => '', 'email' => '', 'phone' => '', 'notes' => ''];
            $_SESSION['contact_csrf'] = bin2hex(random_bytes(32));
        } else {
            $errorMessage = 'Sorry — we could not send your message right now. Please try again later.';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Contact us — answered-ai.com</title>
  <link rel="preconnect" href="https://fonts.googleapis.com" />
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
  <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:ital,wght@0,200..800;1,200..800&family=Sora:wght@400;500;600;700;800&display=swap" rel="stylesheet" />
  <style>
    :root{
      --bg:#0a0c10;
      --surface:#121722;
      --text:#e8ecf4;
      --muted:#9aa6bb;
      --line:rgba(255,255,255,.10);
      --glow:#2dd4bf;
      --violet:#7c3aed;
      --radius:20px;
      --max:960px;
      --font:"Plus Jakarta Sans",system-ui,sans-serif;
      --display:"Sora",var(--font);
    }
    *{box-sizing:border-box}
    body{
      margin:0;
      font-family:var(--font);
      background:
        radial-gradient(1000px 600px at 20% 0%, rgba(45,212,191,.20), transparent 55%),
        radial-gradient(900px 600px at 95% 20%, rgba(124,58,237,.22), transparent 55%),
        var(--bg);
      color:var(--text);
      line-height:1.6;
    }
    a{color:inherit;text-decoration:none}
    .wrap{max-width:var(--max);margin:0 auto;padding:0 clamp(1rem,4vw,2rem)}
    header{
      position:sticky;top:0;z-index:10;
      backdrop-filter: blur(16px);
      background: rgba(10,12,16,.72);
      border-bottom:1px solid var(--line);
    }
    .topbar{display:flex;align-items:center;justify-content:space-between;gap:1rem;padding:1rem 0}
    .brand{display:flex;align-items:center;gap:.85rem;min-width:0}
    .brand img{height:40px;width:auto;display:block;object-fit:contain}
    .brand .title{font-family:var(--display);font-weight:800;letter-spacing:-.03em;font-size:1.05rem}
    .btn{
      display:inline-flex;align-items:center;justify-content:center;gap:.5rem;
      padding:.65rem 1.05rem;border-radius:999px;
      border:1px solid var(--line);
      background: rgba(255,255,255,.04);
      color:var(--text);
      font-weight:650;
      font-size:.92rem;
      cursor:pointer;
      transition:transform .2s, background .2s, border-color .2s;
    }
    .btn:hover{background: rgba(255,255,255,.07); border-color: rgba(45,212,191,.25); transform: translateY(-1px)}
    .btn-primary{
      border:none;
      background: linear-gradient(135deg, #2dd4bf, #0d9488);
      color:#04120f;
      box-shadow: 0 12px 40px rgba(13,148,136,.35);
    }
    .btn-primary:hover{box-shadow: 0 16px 50px rgba(45,212,191,.45)}
    main{padding: 2.25rem 0 4rem}
    h1{
      font-family:var(--display);
      font-size: clamp(2.0rem, 4.8vw, 3.0rem);
      line-height:1.05;
      letter-spacing:-.04em;
      margin:0 0 .65rem;
    }
    .lead{color:var(--muted);max-width:52rem;margin:0}
    .card{
      margin-top: 1.5rem;
      background: rgba(18,23,34,.72);
      border:1px solid var(--line);
      border-radius: var(--radius);
      box-shadow: 0 20px 70px rgba(0,0,0,.45);
      overflow:hidden;
    }
    form{padding: 1.25rem}
    .grid{display:grid;grid-template-columns:1fr 1fr;gap:1rem}
    @media (max-width: 820px){ .grid{grid-template-columns:1fr} }
    label{display:block;font-weight:650;margin:.1rem 0 .35rem}
    input, textarea{
      width:100%;
      padding:.85rem .9rem;
      border-radius: 14px;
      border:1px solid rgba(255,255,255,.14);
      background: rgba(10,12,16,.55);
      color: var(--text);
      outline:none;
      font: inherit;
    }
    input:focus, textarea:focus{
      border-color: rgba(45,212,191,.45);
      box-shadow: 0 0 0 3px rgba(45,212,191,.12);
    }
    textarea{min-height: 140px; resize: vertical}
    .actions{display:flex;align-items:center;justify-content:space-between;gap:1rem;flex-wrap:wrap;margin-top:1rem}
    .note{color:var(--muted);font-size:.92rem}
    .alert{
      margin: 1rem 1.25rem 0;
      padding: .9rem 1rem;
      border-radius: 14px;
      border: 1px solid rgba(255,255,255,.14);
      background: rgba(255,255,255,.05);
    }
    .alert.success{border-color: rgba(45,212,191,.35); background: rgba(45,212,191,.10)}
    .alert.error{border-color: rgba(248,113,113,.35); background: rgba(248,113,113,.10)}
    footer{margin-top: 1.25rem; padding: 1rem 1.25rem; border-top:1px solid var(--line); color:var(--muted); font-size:.9rem}
    code{background: rgba(45,212,191,.12); padding: .12rem .35rem; border-radius: 8px}
    .sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}
  </style>
</head>
<body>
  <header>
    <div class="wrap topbar">
      <div class="brand">
        <img src="assets/logo-answered-ai.png" alt="answered-ai.com" />
        <div class="title">Contact</div>
      </div>
      <a class="btn" href="index.html">← Back to website</a>
    </div>
  </header>

  <main>
    <div class="wrap">
      <h1>Contact us</h1>
      <p class="lead">Send a message; we notify <code><?php echo h(CONTACT_FORM_TO); ?></code> and send you a brief confirmation at your email. Replies use your address via Reply-To.</p>

      <div class="card">
        <?php if ($successMessage): ?>
          <div class="alert success"><?php echo h($successMessage); ?></div>
        <?php elseif ($errorMessage): ?>
          <div class="alert error"><?php echo h($errorMessage); ?></div>
        <?php endif; ?>

        <form method="post" action="contact.php" novalidate>
          <input type="hidden" name="csrf" value="<?php echo h($_SESSION['contact_csrf']); ?>" />
          <div class="sr-only">
            <label for="company">Company</label>
            <input id="company" name="company" type="text" value="" autocomplete="off" tabindex="-1" />
          </div>

          <div class="grid">
            <div>
              <label for="name">Name</label>
              <input id="name" name="name" type="text" required value="<?php echo h($values['name']); ?>" placeholder="Your name" />
            </div>
            <div>
              <label for="email">Email address</label>
              <input id="email" name="email" type="email" required value="<?php echo h($values['email']); ?>" placeholder="you@company.com" />
            </div>
            <div>
              <label for="phone">Phone number</label>
              <input id="phone" name="phone" type="tel" value="<?php echo h($values['phone']); ?>" placeholder="(optional)" />
            </div>
            <div style="grid-column: 1 / -1;">
              <label for="notes">Notes</label>
              <textarea id="notes" name="notes" required placeholder="How can we help?"><?php echo h($values['notes']); ?></textarea>
            </div>
          </div>

          <div class="actions">
            <span class="note">We’ll reply to the email you provide (set as Reply-To).</span>
            <button class="btn btn-primary" type="submit">Submit</button>
          </div>
        </form>

        <footer>
          SMTP: set <code>SMTP_HOST</code>, <code>SMTP_USER</code>, <code>SMTP_PASS</code>, <code>SMTP_PORT</code> on the server. Optional: <code>SMTP_TIMEOUT</code> (seconds, default 15) to cap how long a failed SMTP attempt blocks the request; <code>CONTACT_SKIP_SMTP=1</code> sends the contact form only via PHP <code>mail()</code>. Trace delivery in <code>site/storage/email-send.log</code> (JSON lines). For SMTP wire debug, set env <code>EMAIL_SMTP_DEBUG=1</code>; disable file logging with <code>EMAIL_LOG=0</code>. If mail still fails, submissions may be queued in <code>site/storage/contact_submissions.jsonl</code> (ensure that directory is writable by the web user).
        </footer>
      </div>
    </div>
  </main>
</body>
</html>

