<?php
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/data.php';

$ok = false; $err = '';
$old = ['name'=>'','phone'=>'','email'=>'','home_type'=>'','area'=>'','need_type'=>'','message'=>''];

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
    // Anti-spam: honeypot + minimum fill time
    $hp = trim($_POST['company'] ?? '');           // honeypot, must stay empty
    $ts = (int)($_POST['ts'] ?? 0);
    $name  = trim($_POST['name'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $old = [
      'name'=>$name,'phone'=>$phone,'email'=>$email,
      'home_type'=>trim($_POST['home_type'] ?? ''),
      'area'=>trim($_POST['area'] ?? ''),
      'need_type'=>trim($_POST['need_type'] ?? ''),
      'message'=>trim($_POST['message'] ?? ''),
    ];

    if ($hp !== '' || ($ts > 0 && (time() - $ts) < 3)) {
        // Silent drop for bots — pretend success
        $ok = true;
    } elseif ($name === '' || $phone === '') {
        $err = 'Please fill in your name and a contact number so we can reply.';
    } else {
        try {
            $opening = isset($_POST['openings']) && is_array($_POST['openings'])
                ? implode(', ', array_map('strval', $_POST['openings'])) : '';
            $stmt = db()->prepare("INSERT INTO quotes
              (name,phone,email,home_type,area,opening_types,need_type,num_openings,preferred_option,message,source_page,ip,user_agent)
              VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)");
            $stmt->execute([
              $name, $phone, $email ?: null,
              $old['home_type'] ?: null, $old['area'] ?: null,
              $opening ?: null, $old['need_type'] ?: null,
              trim($_POST['num_openings'] ?? '') ?: null,
              trim($_POST['preferred_option'] ?? '') ?: null,
              $old['message'] ?: null,
              'contact', $_SERVER['REMOTE_ADDR'] ?? '', substr($_SERVER['HTTP_USER_AGENT'] ?? '',0,250),
            ]);
            $ok = true;
            // Best-effort email notification (never blocks the lead)
            @notify_lead($name,$phone,$email,$old,$opening);
            $old = ['name'=>'','phone'=>'','email'=>'','home_type'=>'','area'=>'','need_type'=>'','message'=>''];
        } catch (Throwable $ex) {
            $err = 'Something went wrong saving your request. Please WhatsApp us instead.';
        }
    }
}

function notify_lead($name,$phone,$email,$old,$opening){
    $sgKey = getenv('FRESHMESH_SG_KEY');
    if (!$sgKey) return;
    $to = 'charles@digitalperpetual.com';
    $body = "New FreshMesh quote request\n\n".
            "Name: $name\nPhone: $phone\nEmail: ".($email?:'-')."\n".
            "Home type: ".($old['home_type']?:'-')."\nArea: ".($old['area']?:'-')."\n".
            "Openings: ".($opening?:'-')."\nNeed: ".($old['need_type']?:'-')."\n".
            "Message: ".($old['message']?:'-')."\n";
    $payload = json_encode([
      'personalizations'=>[['to'=>[['email'=>$to]]]],
      'from'=>['email'=>'noreply@digitalperpetual.com','name'=>'FreshMesh Leads'],
      'subject'=>"New FreshMesh quote: $name ($phone)",
      'content'=>[['type'=>'text/plain','value'=>$body]],
    ]);
    $ch = curl_init('https://api.sendgrid.com/v3/mail/send');
    curl_setopt_array($ch,[CURLOPT_POST=>1,CURLOPT_HTTPHEADER=>['Authorization: Bearer '.$sgKey,'Content-Type: application/json'],
      CURLOPT_POSTFIELDS=>$payload,CURLOPT_RETURNTRANSFER=>1,CURLOPT_TIMEOUT=>8]);
    curl_exec($ch); curl_close($ch);
}

$PAGE_TITLE = 'Contact FreshMesh | Get a Window & Door Mesh Quote';
$PAGE_DESC  = 'Get a quote for window, door, balcony or cat-safe mesh in Singapore. WhatsApp us photos or fill in the quote form and we will reply with package options.';
require __DIR__ . '/includes/header.php';
?>
<section class="page-hero">
  <div class="wrap">
    <div class="crumb"><a href="/">Home</a> &nbsp;/&nbsp; Contact</div>
    <h1>Get your mesh quote</h1>
    <p class="lead">The fastest way is WhatsApp with photos. Prefer a form? Fill it in below and we will reply with package options and a price guide.</p>
  </div>
</section>
<section class="section">
  <div class="wrap quote-wrap">
    <div>
      <?php if ($ok): ?>
        <div class="alert ok">Thanks! Your request has been received. We will reply shortly. For a faster response, send photos on WhatsApp.</div>
      <?php elseif ($err): ?>
        <div class="alert err"><?= e($err) ?></div>
      <?php endif; ?>
      <form class="quote-form" method="post" action="/contact">
        <input type="text" name="company" class="hp" tabindex="-1" autocomplete="off" aria-hidden="true">
        <input type="hidden" name="ts" value="<?= time() ?>">
        <div class="row">
          <div class="field"><label>Name *</label><input type="text" name="name" required value="<?= e($old['name']) ?>"></div>
          <div class="field"><label>Phone / WhatsApp *</label><input type="text" name="phone" required value="<?= e($old['phone']) ?>"></div>
        </div>
        <div class="field"><label>Email</label><input type="email" name="email" value="<?= e($old['email']) ?>"></div>
        <div class="row">
          <div class="field"><label>Home type</label>
            <select name="home_type">
              <option value="">Select…</option>
              <?php foreach (['HDB','Condo','Landed','Office','Shop','Other'] as $h): ?>
                <option<?= $old['home_type']===$h?' selected':'' ?>><?= $h ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="field"><label>Area in Singapore</label><input type="text" name="area" placeholder="e.g. Tampines" value="<?= e($old['area']) ?>"></div>
        </div>
        <div class="row">
          <div class="field"><label>What do you need?</label>
            <select name="need_type">
              <option value="">Select…</option>
              <?php foreach (['Insect-only','Cat-safe','Child-safety support','Security mesh','Not sure'] as $n): ?>
                <option<?= $old['need_type']===$n?' selected':'' ?>><?= $n ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="field"><label>Preferred option</label>
            <select name="preferred_option">
              <option value="">Select…</option>
              <option>Magnetic</option><option>Retractable</option><option>Stainless steel</option><option>Not sure</option>
            </select>
          </div>
        </div>
        <div class="field"><label>Openings &amp; rough sizes</label><textarea name="message" placeholder="e.g. 3 bedroom windows ~1.2m x 1.5m, 1 service yard door. Cat-safe needed."><?= e($old['message']) ?></textarea></div>
        <button type="submit" class="btn btn-primary btn-lg">Send my quote request</button>
        <p style="font-size:.82rem;text-align:center;margin-top:12px;color:#7c8a84">We use your details only to prepare your quote.</p>
      </form>
    </div>
    <aside class="contact-side">
      <h3>WhatsApp is fastest</h3>
      <p>Send photos of each opening with rough sizes. We usually reply the same day with options and a price guide.</p>
      <a class="btn btn-wa btn-lg" href="<?= e(wa_link()) ?>" target="_blank" rel="noopener" style="margin:10px 0 6px">Chat on WhatsApp</a>
      <div class="ci" style="margin-top:24px"><svg width="22" height="22" viewBox="0 0 24 24" fill="none"><path d="M3 7l9 6 9-6M4 5h16a1 1 0 011 1v12a1 1 0 01-1 1H4a1 1 0 01-1-1V6a1 1 0 011-1z" stroke="currentColor" stroke-width="1.6"/></svg><div><b>Email</b><br><?= e(CONTACT_EMAIL) ?></div></div>
      <div class="ci"><svg width="22" height="22" viewBox="0 0 24 24" fill="none"><path d="M12 21s-7-4.3-7-9.5A4 4 0 0112 8a4 4 0 017 3.5C19 16.7 12 21 12 21z" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"/></svg><div><b>Service area</b><br>HDB, condo &amp; landed homes islandwide</div></div>
      <h3>What to share for a quote</h3>
      <p style="font-size:.92rem">Home type, area, opening types, rough sizes, photos, what you need (insect, cat-safe, security) and your timeline.</p>
    </aside>
  </div>
</section>
<?php require __DIR__ . '/includes/footer.php'; ?>
