<?php
// ============================================================
//  contact.php submission handler
// ============================================================
//
//  Flow:
//   1. Validate input
//   2. Always: email the team (Phase 1 = log only; Phase 2 = real SMTP)
//   3. If the user ticked the "keep me updated" consent box, OR we want
//      to add them as a lead regardless — push to Mailchimp with
//      "Lead" lifecycle tag and "Contact Form" source tag.
//   4. Optionally trigger the contact-lead customer journey
//   5. Redirect with success flag
//
// ============================================================

require __DIR__ . '/includes/mailchimp.php';
require __DIR__ . '/includes/csrf.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: contact.php');
    exit;
}

csrf_verify();

// --- 1. Validate --------------------------------------------
$required = ['first_name', 'last_name', 'email', 'message'];
foreach ($required as $field) {
    if (empty($_POST[$field])) {
        header('Location: contact.php?error=missing#contact-form');
        exit;
    }
}

$email = trim($_POST['email']);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    header('Location: contact.php?error=missing');
    exit;
}

// --- 2. Log the message for the admin team ------------------
// Phase 2: replace with SMTP to SITE_EMAIL or a ticketing system
$log_line = sprintf(
    "[%s] Contact form: %s %s <%s> — topic: %s\n  %s\n",
    date('Y-m-d H:i:s'),
    $_POST['first_name'],
    $_POST['last_name'],
    $email,
    $_POST['topic'] ?? 'General enquiry',
    str_replace("\n", "\n  ", trim($_POST['message']))
);
@file_put_contents(__DIR__ . '/contact-messages.log', $log_line, FILE_APPEND | LOCK_EX);

// --- 3. Push to Mailchimp -----------------------------------
// We only subscribe them if they ticked the consent box.
// Without consent we still log and still create them in Mailchimp,
// but with status "transactional" — which means they won't receive
// marketing emails but we can track them as a lead.
$subscribe_status = !empty($_POST['consent']) ? 'subscribed' : 'transactional';

$merge = [
    'FNAME' => trim($_POST['first_name']),
    'LNAME' => trim($_POST['last_name']),
];
if (!empty($_POST['phone'])) {
    $merge['PHONE'] = trim($_POST['phone']);
}

// Attempt to push. Failures are logged; the user still gets a thank-you.
mc_upsert_member($email, $merge, ['Contact Form'], $subscribe_status);

// Lifecycle tag: mark as Lead (mutually exclusive). If they happen to
// already be a paying member this will override the existing lifecycle
// tag — which is probably wrong for members who are using the contact
// form for support. Phase 2: check current tags first.
if ($subscribe_status === 'subscribed') {
    mc_set_exclusive_tag($email, MC_LIFECYCLE_TAGS, 'Lead');
}

// --- 4. Trigger the contact-lead journey (if configured) ----
mc_trigger_journey(MC_JOURNEY_CONTACT_LEAD, $email);

// --- 5. Redirect --------------------------------------------
header('Location: contact.php?success=1');
exit;
