<?php
/**
 * Contact page + enquiry form handler.
 *
 * Posts back to itself. Validates server-side, rejects bots via a honeypot and
 * a minimum fill time, then mails the enquiry to config['form_to'].
 */
session_start();

$cfg_early = require __DIR__ . '/inc/config.php';

$errors = [];
$sent   = false;
$old    = ['name' => '', 'company' => '', 'email' => '', 'phone' => '', 'interest' => '', 'message' => ''];

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    foreach ($old as $k => $_) {
        $old[$k] = trim((string) ($_POST[$k] ?? ''));
    }

    // Honeypot: a real browser leaves this empty.
    $trap = trim((string) ($_POST['website'] ?? ''));

    // Minimum fill time: forms submitted in under 3 seconds are bots.
    $started  = (int) ($_SESSION['form_started'] ?? 0);
    $too_fast = $started > 0 && (time() - $started) < 3;

    if ($old['name'] === '') {
        $errors[] = 'Please tell us your name.';
    }
    if ($old['email'] === '' || !filter_var($old['email'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Please enter a valid email address so we can reply.';
    }
    if (mb_strlen($old['message']) < 20) {
        $errors[] = 'Please give us a little more detail - at least 20 characters.';
    }
    // Header-injection guard on anything that reaches a mail header.
    if (preg_match('/[\r\n]/', $old['name'] . $old['email'])) {
        $errors[] = 'Your name or email contained characters we cannot accept.';
    }

    if (!$errors && !$trap && !$too_fast) {
        $to      = $cfg_early['form_to'];
        $subject = $cfg_early['form_subject'];

        $interest_label = [
            'software'  => 'Software Solutions',
            'commerce'  => 'Goods purchasing / selling',
            'wholesale' => 'Wholesale supply',
            'both'      => 'Both divisions',
            'other'     => 'Something else',
        ][$old['interest']] ?? 'Not specified';

        $lines = [
            'New enquiry from the Mirha Global website',
            str_repeat('-', 46),
            'Name:      ' . $old['name'],
            'Company:   ' . ($old['company'] !== '' ? $old['company'] : '-'),
            'Email:     ' . $old['email'],
            'Phone:     ' . ($old['phone'] !== '' ? $old['phone'] : '-'),
            'Interest:  ' . $interest_label,
            '',
            'Message:',
            $old['message'],
            '',
            str_repeat('-', 46),
            'Sent: ' . date('D, d M Y H:i:s') . ' (server time)',
            'IP:   ' . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'),
        ];

        $headers = implode("\r\n", [
            'From: ' . $cfg_early['company'] . ' Website <' . $cfg_early['form_from'] . '>',
            'Reply-To: ' . $old['name'] . ' <' . $old['email'] . '>',
            'Content-Type: text/plain; charset=UTF-8',
            'X-Mailer: PHP/' . phpversion(),
        ]);

        $ok = @mail($to, $subject, implode("\n", $lines), $headers, '-f' . $cfg_early['form_from']);

        if ($ok) {
            $sent = true;
            $old  = array_fill_keys(array_keys($old), '');
        } else {
            $errors[] = 'We could not send your message just now. Please email us directly at ' . $cfg_early['email'] . '.';
        }
    } elseif (!$errors) {
        // Silently accept bot submissions so they get no feedback to tune against.
        $sent = true;
        $old  = array_fill_keys(array_keys($old), '');
    }
}

$_SESSION['form_started'] = time();

$page_key   = 'contact';
$page_title = 'Contact Mirha Global | Software & Trading Enquiries';
$page_desc  = 'Get in touch with Mirha Global about software development, marketplace integration, wholesale supply or selling your product range in the UK.';
require __DIR__ . '/partials/head.php';
?>

<section class="page-hero">
  <div class="wrap">
    <p class="crumbs"><a href="/">Home</a><span>/</span>Contact</p>
    <h1>Get in touch</h1>
    <p>Tell us what you are working on. Enquiries get a reply from a real person
       within one working day.</p>
  </div>
</section>

<section class="section">
  <div class="wrap">
    <div class="two-col">
      <div>
        <?php if ($sent): ?>
          <div class="alert alert-ok" role="status">
            <strong>Thank you - your message is on its way.</strong>
            <p>We have received your enquiry and will reply within one working
               day. If it is urgent, call us on <?= e($cfg['phone']) ?>.</p>
          </div>
        <?php endif; ?>

        <?php if ($errors): ?>
          <div class="alert alert-err" role="alert">
            <strong>Please check the form</strong>
            <ul style="margin:6px 0 0; padding-left:1.1em">
              <?php foreach ($errors as $err): ?>
                <li><?= e($err) ?></li>
              <?php endforeach; ?>
            </ul>
          </div>
        <?php endif; ?>

        <h2>Send an enquiry</h2>
        <p class="muted" style="margin-bottom:26px">Fields marked <span style="color:#dc2626">*</span> are required.</p>

        <form method="post" action="/contact" novalidate>
          <div class="form-grid">
            <div class="field">
              <label for="name">Your name <span class="req">*</span></label>
              <input type="text" id="name" name="name" value="<?= e($old['name']) ?>" autocomplete="name" required>
            </div>

            <div class="field">
              <label for="company">Company</label>
              <input type="text" id="company" name="company" value="<?= e($old['company']) ?>" autocomplete="organization">
            </div>

            <div class="field">
              <label for="email">Email address <span class="req">*</span></label>
              <input type="email" id="email" name="email" value="<?= e($old['email']) ?>" autocomplete="email" required>
            </div>

            <div class="field">
              <label for="phone">Phone</label>
              <input type="tel" id="phone" name="phone" value="<?= e($old['phone']) ?>" autocomplete="tel">
            </div>

            <div class="field field--full">
              <label for="interest">What is this about?</label>
              <select id="interest" name="interest">
                <?php
                $opts = [
                    ''          => 'Please choose...',
                    'software'  => 'Software Solutions - a build, integration or system',
                    'commerce'  => 'Goods - selling my product range',
                    'wholesale' => 'Goods - buying stock / wholesale supply',
                    'both'      => 'Both divisions',
                    'other'     => 'Something else',
                ];
                foreach ($opts as $val => $label):
                    $sel = $old['interest'] === $val ? ' selected' : '';
                ?>
                  <option value="<?= e($val) ?>"<?= $sel ?>><?= e($label) ?></option>
                <?php endforeach; ?>
              </select>
            </div>

            <div class="field field--full">
              <label for="message">How can we help? <span class="req">*</span></label>
              <textarea id="message" name="message" required><?= e($old['message']) ?></textarea>
              <span class="hint">The more specific you are about the product, the
                platform or the deadline, the more useful our reply will be.</span>
            </div>

            <div class="hp" aria-hidden="true">
              <label for="website">Leave this field empty</label>
              <input type="text" id="website" name="website" tabindex="-1" autocomplete="off">
            </div>

            <div class="field field--full">
              <button class="btn btn-primary btn-lg" type="submit">
                Send enquiry
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12h14M12 5l7 7-7 7"/></svg>
              </button>
              <span class="hint" style="margin-top:10px">We use your details only to
                answer your enquiry. See our <a href="/privacy">privacy notice</a>.</span>
            </div>
          </div>
        </form>
      </div>

      <div>
        <div class="contact-card">
          <h3>Email</h3>
          <p>
            General: <a href="mailto:<?= e($cfg['email']) ?>"><?= e($cfg['email']) ?></a><br>
            Trade desk: <a href="mailto:<?= e($cfg['email_sales']) ?>"><?= e($cfg['email_sales']) ?></a>
          </p>
        </div>

        <div class="contact-card">
          <h3>Phone</h3>
          <p><a href="tel:<?= e($cfg['phone_href']) ?>"><?= e($cfg['phone']) ?></a></p>
        </div>

        <div class="contact-card">
          <h3>Office hours</h3>
          <p><?= e($cfg['hours']) ?></p>
        </div>

        <div class="contact-card">
          <h3>Address</h3>
          <p>
            <?= implode('<br>', array_map('e', $cfg['address'])) ?>
          </p>
        </div>

        <div class="contact-card" style="background:var(--bg-soft)">
          <h3>Not sure which division?</h3>
          <p>Send the enquiry anyway. If it turns out to be the other side of the
             business, we will pass it across internally &mdash; you will not have to
             explain it twice.</p>
        </div>
      </div>
    </div>
  </div>
</section>

<?php require __DIR__ . '/partials/foot.php'; ?>
