<?php
session_start();
require_once 'config.php';
require_once __DIR__ . '/tracking-core.php';

define('LEADS_FILE', __DIR__ . '/leads.jsonl');

function contact_csrf_token(): string {
    if (empty($_SESSION['contact_csrf'])) {
        $_SESSION['contact_csrf'] = bin2hex(random_bytes(32));
    }
    return (string) $_SESSION['contact_csrf'];
}

function contact_reset_captcha(): void {
    $left = random_int(2, 9);
    $right = random_int(1, 9);
    $_SESSION['contact_captcha_question'] = $left . ' + ' . $right;
    $_SESSION['contact_captcha_answer'] = (string) ($left + $right);
}

function contact_captcha_question(): string {
    if (empty($_SESSION['contact_captcha_answer']) || empty($_SESSION['contact_captcha_question'])) {
        contact_reset_captcha();
    }
    return (string) $_SESSION['contact_captcha_question'];
}

function contact_captcha_valid(string $answer): bool {
    $expected = (string) ($_SESSION['contact_captcha_answer'] ?? '');
    $answer = preg_replace('/\s+/', '', trim($answer));
    return $expected !== '' && $answer !== '' && hash_equals($expected, (string) $answer);
}

/**
 * Logs a contact.php submission as a lead record consumed by admin-leads.php.
 * Replaces the old details.txt flat-file logger — leads now show up on the
 * Lead Dashboard exactly like the popup-lead-submit.php captures do.
 */
function log_submission($step, $data = []): bool {
    global $db;

    $ip =
        $_SERVER['HTTP_CF_CONNECTING_IP'] ??
        $_SERVER['HTTP_X_FORWARDED_FOR'] ??
        $_SERVER['REMOTE_ADDR'] ??
        'unknown';
    $ip = trim(explode(',', $ip)[0]);

    $type = $data['type'] ?? 'message';
    if ($step === 'STEP 1') {
        $method     = $type === 'viewing' ? 'contact_viewing' : 'contact_message';
        $methodName = $type === 'viewing' ? 'Viewing Request (Contact Form)' : 'Message Owner (Contact Form)';
        $whatsapp   = '';
        $notes      = $data['message'] ?? '';
        // Carry email + message across to step 2 so the follow-up lead is linked.
        $_SESSION['ct_email']   = $data['email']   ?? '';
        $_SESSION['ct_message'] = $data['message'] ?? '';
    } else {
        $method     = $type === 'viewing' ? 'contact_viewing' : 'contact_message';
        $methodName = $type === 'viewing' ? 'Viewing Request (Phone Follow-up)' : 'Message Owner (Phone Follow-up)';
        $whatsapp   = $data['phone'] ?? '';
        $notes      = $_SESSION['ct_message'] ?? '';
    }

    $email = $data['email'] ?? ($_SESSION['ct_email'] ?? '');
    $page  = $data['slug'] ?? ($_GET['slug'] ?? '');

    if (!isset($db) || !($db instanceof PDO)) {
        error_log('[contact] lead storage failed: database unavailable');
        return false;
    }

    $eventId = log_conversion_event($db, 'lead', [
        'method'        => $method,
        'method_name'   => $methodName,
        'whatsapp'      => $whatsapp,
        'name'          => $email,
        'email'         => $email,
        'notes'         => $notes,
        'property_slug' => $page,
        'page_url'      => $page !== '' ? '/contact.php?slug=' . urlencode($page) : '/contact.php',
    ]);
    if ($eventId <= 0) {
        error_log('[contact] lead storage failed: conversion_events insert returned no ID');
        return false;
    }
    return true;
}

try {
    $db = get_db();
} catch (Throwable $e) {
    die('<h2 style="font-family:sans-serif;color:#c00;padding:40px">Database connection failed: ' . htmlspecialchars($e->getMessage()) . '</h2>');
}
$slug = trim($_GET['slug'] ?? '');
$type = trim($_GET['type'] ?? 'message');
$type = in_array($type, ['message', 'viewing'], true) ? $type : 'message';

$property = null;
if ($slug) {
    $stmt = $db->prepare(
        "SELECT id, title, price, location_city, location_province, listing_type,
                bedrooms, bathrooms, acreage, thumbnail_paths, large_image_paths, slug
         FROM scrapy WHERE slug = :slug LIMIT 1"
    );
    $stmt->execute([':slug' => $slug]);
    $property = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
}

$thumb = '';
if ($property) {
    $paths = $property['large_image_paths'] ?: $property['thumbnail_paths'];
    if ($paths) {
        $raw = trim($paths);
        if ($raw !== '' && ($raw[0] === '[' || $raw[0] === '{')) {
            $decoded = json_decode($raw, true);
            if (is_array($decoded) && !empty($decoded)) $thumb = ltrim(str_replace('\\','/',trim((string)$decoded[0])),'/');
        }
        if (!$thumb) {
            $parts = explode(',', $raw);
            $thumb = ltrim(str_replace('\\','/',trim((string)($parts[0] ?? ''))),'/');
        }
    }
}

$step       = 1;
$errors     = [];
$sent_step1 = false;
$sent_step2 = false;
$post_slug  = trim($_POST['slug'] ?? $slug);
$post_type  = in_array(trim($_POST['type'] ?? $type), ['message','viewing'], true) ? trim($_POST['type'] ?? $type) : $type;
$contact_csrf = contact_csrf_token();
if (empty($_SESSION['contact_captcha_answer']) || empty($_SESSION['contact_captcha_question'])) {
    contact_reset_captcha();
}

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

    if (($_POST['step'] ?? '') === '1') {
        $email   = trim($_POST['email'] ?? '');
        $message = trim($_POST['message'] ?? '');
        $posted_csrf = (string) ($_POST['contact_csrf'] ?? '');
        $honeypot = trim((string) ($_POST['website'] ?? ''));

        if ($posted_csrf === '' || !hash_equals($contact_csrf, $posted_csrf)) {
            $errors[] = 'Your form session expired. Please refresh and try again.';
        }
        if ($honeypot !== '') {
            $errors[] = 'Please try again.';
        }
        if (!contact_captcha_valid((string) ($_POST['captcha_answer'] ?? ''))) {
            $errors[] = 'Please complete the safety check correctly.';
        }
        if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors[] = 'Please enter a valid email address.';
        }
        if (!$message) {
            $errors[] = 'Please enter a message.';
        }
        if (!$errors && !log_submission('STEP 1', [
            'email' => $email,
            'message' => $message,
            'slug' => $post_slug,
            'type' => $post_type
        ])) {
            $errors[] = 'We could not save your message. Please try again.';
        }
        if (!$errors) {
            $prop_title = $property['title'] ?? 'Unknown property';
            $prop_url   = $property ? prop_url($property['slug']) : '';
            $subj_type  = $post_type === 'viewing' ? 'Viewing Request' : 'Owner Message';
            $subject    = "[DaNangBeachfront] {$subj_type}: " . $prop_title;
            $body  = "You have received a " . ($post_type === 'viewing' ? 'viewing request' : 'message') . " from a prospective buyer/tenant.\r\n\r\n";
            $body .= "Property : {$prop_title}\r\n";
            if ($prop_url) $body .= "Listing  : {$prop_url}\r\n";
            $body .= "\r\nFrom     : {$email}\r\n";
            $body .= "Message  :\r\n{$message}\r\n";
            $headers  = "From: noreply@danangbeachfront.com\r\n";
            $headers .= "Reply-To: {$email}\r\n";
            $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
            @mail('llppww997@gmail.com', $subject, $body, $headers);
            unset($_SESSION['contact_captcha_answer'], $_SESSION['contact_captcha_question']);
            $sent_step1 = true;
            $step = 2;
        } else {
            contact_reset_captcha();
            $step = 1;
        }

    } elseif (($_POST['step'] ?? '') === '2') {
        $phone = trim($_POST['phone'] ?? '');
        if (!$phone) {
            $errors[] = 'Please enter your phone number.';
        }
        if (!$errors && !log_submission('STEP 2', [
            'phone' => $phone,
            'slug' => $post_slug,
            'type' => $post_type
        ])) {
            $errors[] = 'We could not save your phone number. Please try again.';
        }
        if (!$errors) {
            $prop_title = $property['title'] ?? 'Unknown property';
            $subj_type  = $post_type === 'viewing' ? 'Viewing Request' : 'Owner Message';
            $subject    = "[DaNangBeachfront] Phone follow-up – {$subj_type}: " . $prop_title;
            $body  = "Phone number follow-up for the same enquiry.\r\n\r\n";
            $body .= "Property : {$prop_title}\r\n";
            $body .= "Phone    : {$phone}\r\n";
            $headers = "From: noreply@danangbeachfront.com\r\nContent-Type: text/plain; charset=UTF-8\r\n";
            @mail('contact@danangbeachfront.com', $subject, $body, $headers);
            $sent_step2 = true;
            $step = 3;
        } else {
            $step = 2;
        }
    }
}

$captcha_question = contact_captcha_question();
$contact_site_name = defined('APP_DISPLAY_NAME') ? (string) APP_DISPLAY_NAME : 'DaNangBeachfront';
$contact_origin = 'https://danangbeachfront.com';
$contact_logo_path = '/assets/logo-dnb.svg';
$contact_description = 'Contact ' . $contact_site_name . ' for help with Da Nang property enquiries.';
$contact_canonical = $contact_origin . '/contact.php';
$contact_og_image = $contact_origin . $contact_logo_path;

$page_title = $property
    ? ($type === 'viewing' ? 'Arrange a Viewing – ' : 'Message Owner – ') . htmlspecialchars($property['title'])
    : 'Contact – DaNangBeachfront';

// Flush output buffer opened by config.php
while (ob_get_level() > 0) { ob_end_flush(); }
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= htmlspecialchars($page_title, ENT_QUOTES, 'UTF-8') ?> | <?= htmlspecialchars($contact_site_name, ENT_QUOTES, 'UTF-8') ?></title>
<meta name="description" content="<?= htmlspecialchars($contact_description, ENT_QUOTES, 'UTF-8') ?>">
<link rel="canonical" href="<?= htmlspecialchars($contact_canonical, ENT_QUOTES, 'UTF-8') ?>">
<meta property="og:type" content="website">
<meta property="og:site_name" content="<?= htmlspecialchars($contact_site_name, ENT_QUOTES, 'UTF-8') ?>">
<meta property="og:title" content="<?= htmlspecialchars($page_title . ' | ' . $contact_site_name, ENT_QUOTES, 'UTF-8') ?>">
<meta property="og:description" content="<?= htmlspecialchars($contact_description, ENT_QUOTES, 'UTF-8') ?>">
<meta property="og:url" content="<?= htmlspecialchars($contact_canonical, ENT_QUOTES, 'UTF-8') ?>">
<meta property="og:image" content="<?= htmlspecialchars($contact_og_image, ENT_QUOTES, 'UTF-8') ?>">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="<?= htmlspecialchars($page_title . ' | ' . $contact_site_name, ENT_QUOTES, 'UTF-8') ?>">
<meta name="twitter:description" content="<?= htmlspecialchars($contact_description, ENT_QUOTES, 'UTF-8') ?>">
<meta name="twitter:image" content="<?= htmlspecialchars($contact_og_image, ENT_QUOTES, 'UTF-8') ?>">
<script type="application/ld+json"><?= json_encode(['@context' => 'https://schema.org', '@type' => 'ContactPage', 'name' => 'Contact ' . $contact_site_name, 'url' => $contact_canonical, 'isPartOf' => ['@type' => 'WebSite', 'name' => $contact_site_name, 'url' => $contact_origin]], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?></script>
<style>
@keyframes btn-pulse{0%,100%{box-shadow:0 0 0 0 rgba(3,105,161,.5)}50%{box-shadow:0 0 0 12px rgba(3,105,161,0)}}
@keyframes fade-in{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:none}}
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
body{font-family:'Be Vietnam Pro',-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;background:#f0f4f8;color:#0d1b2a;min-height:100vh}

/* ── Layout ── */
.ct-wrap{max-width:600px;margin:0 auto;padding:28px 16px 80px;animation:fade-in .4s ease}

/* ── Progress bar ── */
.ct-progress{display:flex;align-items:center;gap:0;margin-bottom:28px}
.ct-step{display:flex;align-items:center;gap:8px;flex:1}
.ct-step-dot{width:28px;height:28px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:800;flex-shrink:0;transition:all .3s}
.ct-step-dot.done{background:#0369a1;color:#fff}
.ct-step-dot.active{background:#0369a1;color:#fff;box-shadow:0 0 0 4px rgba(3,105,161,.2)}
.ct-step-dot.pending{background:#e5e7eb;color:#9ca3af}
.ct-step-label{font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.05em}
.ct-step-label.active{color:#0369a1}
.ct-step-label.pending{color:#9ca3af}
.ct-step-label.done{color:#0369a1}
.ct-step-line{height:2px;flex:1;margin:0 6px;border-radius:1px;transition:background .3s}
.ct-step-line.done{background:#0369a1}
.ct-step-line.pending{background:#e5e7eb}

/* ── Property card ── */
.ct-prop-card{display:flex;gap:0;background:#fff;border:1px solid #e5e7eb;border-radius:16px;overflow:hidden;margin-bottom:24px;box-shadow:0 2px 12px rgba(0,0,0,.07)}
.ct-prop-img{width:130px;flex-shrink:0;background:#dde4ec}
.ct-prop-img img{width:100%;height:100%;object-fit:cover;display:block}
.ct-prop-img-ph{width:100%;height:100%;min-height:100px;display:flex;align-items:center;justify-content:center;font-size:2rem;background:linear-gradient(135deg,#dde4ec,#c5d0dc)}
.ct-prop-info{padding:14px 18px;min-width:0;display:flex;flex-direction:column;justify-content:center;gap:5px}
.ct-prop-badge{display:inline-block;padding:3px 9px;border-radius:6px;font-size:10px;font-weight:800;letter-spacing:.06em;background:#f0f9ff;color:#0369a1;border:1px solid #99f6e4;width:fit-content}
.ct-prop-title{font-size:13.5px;font-weight:800;color:#0d1b2a;line-height:1.35}
.ct-prop-meta{font-size:12px;color:#6b7280}
.ct-prop-price{font-size:14px;font-weight:800;color:#0369a1}

/* ── Hero heading ── */
.ct-hero{margin-bottom:20px}
.ct-intent-tag{display:inline-flex;align-items:center;gap:6px;background:#fff7ed;color:#c2410c;border:1px solid #fed7aa;border-radius:20px;padding:4px 12px;font-size:11px;font-weight:800;letter-spacing:.05em;margin-bottom:10px}
.ct-h1{font-size:24px;font-weight:900;color:#0d1b2a;line-height:1.25;margin-bottom:6px}
.ct-sub{font-size:14px;color:#6b7280;line-height:1.6}

/* ── Trust badges ── */
.ct-trust{display:flex;gap:6px;flex-wrap:wrap;margin-bottom:22px}
.ct-trust-badge{display:flex;align-items:center;gap:5px;background:#fff;border:1px solid #e5e7eb;border-radius:20px;padding:5px 11px;font-size:11px;font-weight:700;color:#374151}
.ct-trust-badge svg{color:#0369a1;flex-shrink:0}

/* ── Form card ── */
.ct-form-card{background:#fff;border:1px solid #e5e7eb;border-radius:20px;padding:26px;box-shadow:0 4px 20px rgba(0,0,0,.07)}
.ct-field{margin-bottom:18px}
.ct-label{display:block;font-size:11px;font-weight:800;color:#374151;text-transform:uppercase;letter-spacing:.06em;margin-bottom:7px}
.ct-input,.ct-textarea{width:100%;padding:12px 15px;border:1.5px solid #e5e7eb;border-radius:12px;font-size:14px;font-family:inherit;color:#0d1b2a;background:#fafafa;outline:none;transition:border-color .15s,background .15s,box-shadow .15s}
.ct-input:focus,.ct-textarea:focus{border-color:#0369a1;background:#fff;box-shadow:0 0 0 3px rgba(3,105,161,.12)}
.ct-textarea{resize:vertical;min-height:110px;line-height:1.6}

/* ── Submit button ── */
.ct-btn{width:100%;padding:16px;border:none;border-radius:14px;font-size:16px;font-weight:900;cursor:pointer;font-family:inherit;letter-spacing:.01em;display:flex;align-items:center;justify-content:center;gap:10px;transition:transform .18s,filter .18s;margin-bottom:12px}
.ct-btn:hover{transform:translateY(-2px);filter:brightness(1.07)}
.ct-btn:active{transform:translateY(0)}
.ct-btn-primary{background:linear-gradient(135deg,#0369a1,#075985);color:#fff;animation:btn-pulse 2.5s ease-in-out infinite}
.ct-btn-phone{background:linear-gradient(135deg,#1e3a5f,#1e40af);color:#fff;animation:btn-pulse 2.5s ease-in-out infinite}

/* ── Micro-copy under button ── */
.ct-btn-meta{text-align:center;font-size:11.5px;color:#9ca3af;display:flex;align-items:center;justify-content:center;gap:12px;flex-wrap:wrap}
.ct-btn-meta span{display:flex;align-items:center;gap:4px}

/* ── Errors ── */
.ct-errors{background:#fef2f2;border:1px solid #fecaca;border-radius:12px;padding:12px 16px;margin-bottom:18px;list-style:none}
.ct-errors li{font-size:13px;color:#dc2626;display:flex;align-items:center;gap:6px}
.ct-errors li::before{content:'!';background:#dc2626;color:#fff;border-radius:50%;width:16px;height:16px;display:inline-flex;align-items:center;justify-content:center;font-size:10px;font-weight:900;flex-shrink:0}

/* ── Success screens ── */
.ct-success{background:linear-gradient(135deg,#f0fdf4,#dcfce7);border:1px solid #bbf7d0;border-radius:18px;padding:30px 24px;margin-bottom:24px;text-align:center}
.ct-success-icon{font-size:2.8rem;margin-bottom:12px}
.ct-success-title{font-size:20px;font-weight:900;color:#15803d;margin-bottom:8px}
.ct-success-text{font-size:14px;color:#166534;line-height:1.6;max-width:380px;margin:0 auto}

/* ── Step 2 phone upsell ── */
.ct-phone-upsell{background:linear-gradient(135deg,#eff6ff,#dbeafe);border:1px solid #bfdbfe;border-radius:16px;padding:18px 20px;margin-bottom:20px;display:flex;align-items:flex-start;gap:14px}
.ct-phone-upsell-icon{width:40px;height:40px;border-radius:10px;background:#1e40af;display:flex;align-items:center;justify-content:center;flex-shrink:0}
.ct-phone-upsell-body{}
.ct-phone-upsell-title{font-size:14px;font-weight:800;color:#1e3a5f;margin-bottom:3px}
.ct-phone-upsell-text{font-size:12.5px;color:#1e40af;line-height:1.5}

/* ── Final success ── */
.ct-final{text-align:center;padding:10px 0}
.ct-final-title{font-size:22px;font-weight:900;color:#0d1b2a;margin-bottom:8px}
.ct-final-text{font-size:14px;color:#6b7280;line-height:1.6;margin-bottom:24px}
.ct-final-steps{display:flex;flex-direction:column;gap:10px;margin-bottom:28px;text-align:left}
.ct-final-step{display:flex;align-items:center;gap:12px;background:#fff;border:1px solid #e5e7eb;border-radius:12px;padding:12px 14px;font-size:13px;color:#374151}
.ct-final-step-num{width:26px;height:26px;border-radius:50%;background:#0369a1;color:#fff;display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:900;flex-shrink:0}
.ct-back-link{display:inline-flex;align-items:center;gap:5px;color:#0369a1;font-size:13px;font-weight:700;text-decoration:none}
.ct-back-link:hover{text-decoration:underline}

@media(max-width:480px){
  .ct-prop-card{flex-direction:column}
  .ct-prop-img{width:100%;height:180px}
  .ct-h1{font-size:21px}
  .ct-form-card{padding:20px 16px}
  .ct-progress{display:none}
}
</style>
</head>
<body>
<?php
include_once 'includes/header.php';
renderHeader(['enable_top_bar' => true, 'enable_logo_bar' => true, 'enable_search' => true]);
include_once __DIR__ . '/includes/section-nav.php';
include_once 'includes/ad-rotate.php';
?>

<div class="ct-wrap">

  <!-- Progress bar -->
  <div class="ct-progress">
    <div class="ct-step">
      <div class="ct-step-dot <?= $step >= 1 ? ($step > 1 ? 'done' : 'active') : 'pending' ?>">
        <?= $step > 1 ? '✓' : '1' ?>
      </div>
      <span class="ct-step-label <?= $step >= 1 ? ($step > 1 ? 'done' : 'active') : 'pending' ?>">Your message</span>
    </div>
    <div class="ct-step-line <?= $step > 1 ? 'done' : 'pending' ?>"></div>
    <div class="ct-step">
      <div class="ct-step-dot <?= $step >= 2 ? ($step > 2 ? 'done' : 'active') : 'pending' ?>">
        <?= $step > 2 ? '✓' : '2' ?>
      </div>
      <span class="ct-step-label <?= $step >= 2 ? ($step > 2 ? 'done' : 'active') : 'pending' ?>">Your number</span>
    </div>
    <div class="ct-step-line <?= $step > 2 ? 'done' : 'pending' ?>"></div>
    <div class="ct-step">
      <div class="ct-step-dot <?= $step >= 3 ? 'done' : 'pending' ?>">
        <?= $step >= 3 ? '✓' : '3' ?>
      </div>
      <span class="ct-step-label <?= $step >= 3 ? 'done' : 'pending' ?>">Done!</span>
    </div>
  </div>

  <!-- Property card -->
  <?php if ($property): ?>
  <div class="ct-prop-card">
    <div class="ct-prop-img">
      <?php if ($thumb): ?>
      <img src="<?= htmlspecialchars($thumb) ?>" alt="<?= htmlspecialchars($property['title']) ?>">
      <?php else: ?>
      <div class="ct-prop-img-ph">🏠</div>
      <?php endif; ?>
    </div>
    <div class="ct-prop-info">
      <?php
        $badge = '';
        if (isset($property['listing_type'])) {
            $badge = strpos($property['listing_type'], 'thuê') !== false ? 'FOR RENT' : 'FOR SALE';
        }
      ?>
      <?php if ($badge): ?><div class="ct-prop-badge"><?= $badge ?></div><?php endif; ?>
      <div class="ct-prop-title"><?= htmlspecialchars($property['title']) ?></div>
      <div class="ct-prop-meta">
        <?php
          $city = trim($property['location_city'] ?? '');
          $prov = trim($property['location_province'] ?? '');
          $loc  = $city ?: $prov;
          if ($city && $prov && $city !== $prov) $loc = $city . ', ' . $prov;
          echo htmlspecialchars($loc);
        ?>
      </div>
      <?php $p = shortPrice($property['price'] ?? ''); if ($p): ?>
      <div class="ct-prop-price"><?= htmlspecialchars($p) ?></div>
      <?php endif; ?>
    </div>
  </div>
  <?php endif; ?>


  <!-- ── STEP 3: All done ─────────────────────────────── -->
  <?php if ($step === 3 && $sent_step2): ?>

    <div class="ct-success" style="margin-bottom:20px">
      <div class="ct-success-icon">🎉</div>
      <div class="ct-success-title">You're all set!</div>
      <div class="ct-success-text">The owner has your details and will be in touch shortly. Keep an eye on your phone and email.</div>
    </div>

    <div class="ct-final">
      <div class="ct-final-title">What happens next?</div>
      <div class="ct-final-text">Here's what to expect over the next 24 hours.</div>
      <div class="ct-final-steps">
        <div class="ct-final-step"><div class="ct-final-step-num">1</div>The owner reviews your enquiry and message.</div>
        <div class="ct-final-step"><div class="ct-final-step-num">2</div>They contact you by email or phone to confirm details.</div>
        <div class="ct-final-step"><div class="ct-final-step-num">3</div>You visit the property at a time that suits you — free &amp; no obligation.</div>
      </div>
      <a href="index.php" class="ct-back-link" target="_blank">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="15 18 9 12 15 6"/></svg>
        Browse more properties
      </a>
    </div>


  <!-- ── STEP 2: Phone number ──────────────────────────── -->
  <?php elseif ($step === 2): ?>

    <?php if ($sent_step1): ?>
    <div class="ct-success">
      <div class="ct-success-icon">✅</div>
      <div class="ct-success-title">Message sent successfully!</div>
      <div class="ct-success-text">The owner has been notified and will reply to your email. Add your phone number below to get a faster, direct response.</div>
    </div>
    <?php endif; ?>

    <div class="ct-phone-upsell">
      <div class="ct-phone-upsell-icon">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2A19.79 19.79 0 0 1 11.63 19a19.5 19.5 0 0 1-6-6A19.79 19.79 0 0 1 2.12 4.18 2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.127.96.361 1.903.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0 1 22 16.92z"/></svg>
      </div>
      <div class="ct-phone-upsell-body">
        <div class="ct-phone-upsell-title">Get a faster response — add your phone number</div>
        <div class="ct-phone-upsell-text">Owners respond <strong>3× faster</strong> when they can call directly. Takes 5 seconds. No spam, ever.</div>
      </div>
    </div>

    <?php if ($errors): ?>
    <ul class="ct-errors"><?php foreach ($errors as $e): ?><li><?= htmlspecialchars($e) ?></li><?php endforeach; ?></ul>
    <?php endif; ?>

    <div class="ct-form-card">
      <form method="POST" action="contact.php?slug=<?= urlencode($post_slug) ?>&amp;type=<?= urlencode($post_type) ?>">
        <input type="hidden" name="step" value="2">
        <input type="hidden" name="slug" value="<?= htmlspecialchars($post_slug) ?>">
        <input type="hidden" name="type" value="<?= htmlspecialchars($post_type) ?>">
        <div class="ct-field">
          <label class="ct-label" for="phone">Your Phone Number</label>
          <input class="ct-input" type="tel" id="phone" name="phone"
                 placeholder="+84 90 000 0000"
                 value="<?= htmlspecialchars($_POST['phone'] ?? '') ?>" autocomplete="tel">
        </div>
        <button type="submit" class="ct-btn ct-btn-phone">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2A19.79 19.79 0 0 1 11.63 19a19.5 19.5 0 0 1-6-6A19.79 19.79 0 0 1 2.12 4.18 2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.127.96.361 1.903.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0 1 22 16.92z"/></svg>
          Send My Number &amp; Get a Fast Response
        </button>
        <div class="ct-btn-meta">
          <span><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg> Private &amp; secure</span>
          <span><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg> Usually contacted within 2 hrs</span>
        </div>
      </form>
    </div>
    <p style="margin-top:14px;text-align:center"><a href="javascript:history.back()" style="color:#9ca3af;font-size:12px;text-decoration:none">Skip this step →</a></p>


  <!-- ── STEP 1: Main enquiry form ─────────────────────── -->
  <?php else: ?>

    <?php
      $is_viewing = $type === 'viewing';
      $prop_name  = $property ? $property['title'] : 'this property';
      $default_msg = $is_viewing
        ? "Hi, I would like to arrange a viewing for this property. I am available on weekdays after 5pm and weekends — please let me know what times work best."
        : "Hi, I am interested in this property and would like to know more about availability and pricing. Please contact me at your earliest convenience.";
    ?>

    <div class="ct-hero">
      <div class="ct-intent-tag">
        <?php if ($is_viewing): ?>
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
        ARRANGE A FREE VIEWING
        <?php else: ?>
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
        MESSAGE THE OWNER
        <?php endif; ?>
      </div>
      <h1 class="ct-h1"><?= $is_viewing ? 'Book your free viewing' : 'Send a message to the owner' ?></h1>
      <p class="ct-sub"><?= $is_viewing ? 'Fill in your details below and we\'ll confirm a time that works for you — free and no obligation.' : 'Ask anything about this property. The owner usually responds within 2 hours.' ?></p>
    </div>

    <div class="ct-trust">
      <div class="ct-trust-badge">
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><polyline points="9 12 11 14 15 10"/></svg>
        100% Free
      </div>
      <div class="ct-trust-badge">
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
        No spam, ever
      </div>
      <div class="ct-trust-badge">
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
        Replies within 2 hours
      </div>
      <div class="ct-trust-badge">
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
        12,000+ enquiries sent
      </div>
    </div>

    <?php if ($errors): ?>
    <ul class="ct-errors"><?php foreach ($errors as $e): ?><li><?= htmlspecialchars($e) ?></li><?php endforeach; ?></ul>
    <?php endif; ?>

    <div class="ct-form-card">
      <form method="POST" action="contact.php?slug=<?= urlencode($slug) ?>&amp;type=<?= urlencode($type) ?>">
        <input type="hidden" name="step" value="1">
        <input type="hidden" name="slug" value="<?= htmlspecialchars($slug) ?>">
        <input type="hidden" name="type" value="<?= htmlspecialchars($type) ?>">
        <input type="hidden" name="contact_csrf" value="<?= htmlspecialchars($contact_csrf, ENT_QUOTES, 'UTF-8') ?>">
        <div aria-hidden="true" style="position:absolute;left:-10000px;width:1px;height:1px;overflow:hidden">
          <label for="website">Leave this field empty</label>
          <input type="text" id="website" name="website" tabindex="-1" autocomplete="off">
        </div>
        <div class="ct-field">
          <label class="ct-label" for="email">Your Email Address</label>
          <input class="ct-input" type="email" id="email" name="email"
                 placeholder="you@example.com"
                 value="<?= htmlspecialchars($_POST['email'] ?? '') ?>" autocomplete="email" required>
        </div>
        <div class="ct-field">
          <label class="ct-label" for="message">Your Message</label>
          <textarea class="ct-textarea" id="message" name="message" required><?= htmlspecialchars($_POST['message'] ?? $default_msg) ?></textarea>
        </div>
        <div class="ct-field">
          <label class="ct-label" for="captcha_answer">Safety check: what is <?= htmlspecialchars($captcha_question, ENT_QUOTES, 'UTF-8') ?>?</label>
          <input class="ct-input" type="text" id="captcha_answer" name="captcha_answer" inputmode="numeric" autocomplete="off" required>
          <small style="display:block;margin-top:6px;color:#6b7280">Please complete this quick check before sending your message.</small>
        </div>
        <button type="submit" class="ct-btn ct-btn-primary">
          <?php if ($is_viewing): ?>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
          Request My Free Viewing
          <?php else: ?>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M22 2L11 13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
          Send Message to Owner
          <?php endif; ?>
        </button>
        <div class="ct-btn-meta">
          <span><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg> Secure &amp; private</span>
          <span><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg> No obligation</span>
          <span>Takes 30 seconds</span>
        </div>
      </form>
    </div>

    <p style="margin-top:14px;text-align:center"><a href="javascript:history.back()" style="color:#9ca3af;font-size:12px;text-decoration:none">← Go back</a></p>

  <?php endif; ?>

</div>

<?php include 'includes/footer.php'; ?>
</body>
</html>