<?php
/* =============================================================
 *  AEE Group Digital Business Card — Lead Capture Engine
 *  -------------------------------------------------------------
 *  Graham Yoko - Chief Executive Officer
 *  Accelerated Education Enterprises
 *
 *  Architecturally identical to the Buffalo Motors, FinMACC,
 *  Ferns, and David Fernandes AEE send-email.php files on this
 *  platform:
 *  - Writes to the SAME shared leads file (../techno-card-leads.json)
 *    so every cardholder on this hosting domain shows up in one
 *    central FinMACC-branded dashboard at /leads.php
 *  - From: leads@techno-card.co.za (the hosting domain mailbox)
 *  - Bcc:  leads@techno-card.co.za (silent archive)
 *  - To:   Graham.Yoko@aeegroup.co.za + info@aeegroup.co.za
 *  - Reference series: AE-GRA-001, AE-GRA-002, ...
 *  - Cardholder tag: "AEE - Graham Yoko"
 *
 *  PHP 5.6+ compatible. No null-coalesce, no short-array, no
 *  arrow functions, no return-type declarations.
 *
 *  -------------------- CONFIGURATION -------------------- */
$NOTIFY_TO         = array('Graham.Yoko@aeegroup.co.za', 'info@aeegroup.co.za');
$NOTIFY_BCC        = array('leads@techno-card.co.za'); // silent archive copy on hosting domain
$REF_PREFIX        = 'AE-GRA-';                        // AEE - Graham series
$CARDHOLDER        = 'AEE - Graham Yoko';              // tags every lead (matches dashboard visibility filter)
$CARDHOLDER_SLUG   = 'graham-aee';                     // used in counter filename: techno-card-graham-aee-counter.json
$FROM_ADDRESS      = 'leads@techno-card.co.za';        // must exist as a mailbox on techno-card.co.za cPanel
$FROM_NAME         = 'AEE Group Card';
$JSON_PREFIX       = 'techno-card';                    // SHARED across all cardholders on this hosting domain
$RATE_LIMIT_HOUR   = 8;
$AUTOREPLY_ENABLED = true;
$AUTOREPLY_SUBJECT = 'Thanks for connecting with AEE Group';
$BRAND_NAME        = 'AEE Group';
$BRAND_FULLNAME    = 'Accelerated Education Enterprises';
$BRAND_PERSON      = 'Graham Yoko';
$BRAND_TITLE       = 'Chief Executive Officer';
$BRAND_TAGLINE     = 'Christian education that unlocks potential & inspires faith';
$BRAND_BLUE        = '#00B0C0';
$BRAND_NAVY        = '#0B1F3A';
$BRAND_GREY        = '#6B7280';
$BRAND_DIVIDER     = '#E5E7EB';
/* ------------------------------------------------------ */

header('Content-Type: application/json; charset=utf-8');
header('X-Robots-Tag: noindex');

function fail($status, $msg) {
  http_response_code($status);
  echo json_encode(array('ok' => false, 'error' => $msg));
  exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  fail(405, 'Method not allowed');
}

/* ---------- Read JSON body ---------- */
$raw = file_get_contents('php://input');
if (!$raw || strlen($raw) > 16 * 1024) fail(400, 'Empty or oversized payload');
$data = json_decode($raw, true);
if (!is_array($data)) fail(400, 'Invalid JSON');

/* ---------- Honeypot ---------- */
if (isset($data['website']) && $data['website'] !== '') {
  echo json_encode(array('ok' => true, 'reference' => ''));
  exit;
}

/* ---------- Rate limit by IP ---------- */
$ip     = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '0.0.0.0';
$ipHash = hash('sha256', $ip);
$rateFile = sys_get_temp_dir() . '/aee-card-rl-' . $ipHash . '.json';
$now = time();
$rl = array('hits' => array());
if (is_file($rateFile)) {
  $stored = @file_get_contents($rateFile);
  $decoded = $stored ? json_decode($stored, true) : null;
  if (is_array($decoded) && isset($decoded['hits'])) $rl = $decoded;
}
$kept = array();
foreach ($rl['hits'] as $t) {
  if (($now - $t) < 3600) $kept[] = $t;
}
$rl['hits'] = $kept;
if (count($rl['hits']) >= $RATE_LIMIT_HOUR) fail(429, 'Rate limit exceeded');
$rl['hits'][] = $now;
@file_put_contents($rateFile, json_encode($rl));

/* ---------- Sanitise ---------- */
function clean_val($s) {
  if (!is_string($s)) return '';
  $s = preg_replace('/[\x00-\x1F\x7F]/u', ' ', $s);
  return trim(substr($s, 0, 200));
}
$firstName = clean_val(isset($data['firstName']) ? $data['firstName'] : '');
$lastName  = clean_val(isset($data['lastName'])  ? $data['lastName']  : '');
$phone     = clean_val(isset($data['phone'])     ? $data['phone']     : '');
$email     = clean_val(isset($data['email'])     ? $data['email']     : '');
$channel   = clean_val(isset($data['channel'])   ? $data['channel']   : '');
if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) $email = '';
if ($email === '' && $phone === '') fail(400, 'Missing contact info');
if (!in_array($channel, array('whatsapp', 'email'), true)) $channel = 'unknown';

$fullName = trim($firstName . ' ' . $lastName);
if ($fullName === '') $fullName = '(no name)';

/* ---------- Storage paths (outside public_html, SHARED with other cards) ---------- */
$rootParent  = dirname($_SERVER['DOCUMENT_ROOT']);
$leadsFile   = $rootParent . '/' . $JSON_PREFIX . '-leads.json';                            // SHARED across all cardholders
$counterFile = $rootParent . '/' . $JSON_PREFIX . '-' . $CARDHOLDER_SLUG . '-counter.json'; // per-cardholder counter

/* ---------- Atomic counter ---------- */
$reference = '';
$fh = @fopen($counterFile, 'c+');
if ($fh) {
  flock($fh, LOCK_EX);
  $contents = stream_get_contents($fh);
  $counter  = $contents ? json_decode($contents, true) : null;
  if (!is_array($counter) || !isset($counter['n'])) $counter = array('n' => 0);
  $counter['n'] = intval($counter['n']) + 1;
  $reference = $REF_PREFIX . str_pad((string)$counter['n'], 3, '0', STR_PAD_LEFT);
  rewind($fh); ftruncate($fh, 0);
  fwrite($fh, json_encode($counter));
  flock($fh, LOCK_UN); fclose($fh);
} else {
  $reference = $REF_PREFIX . substr((string)time(), -4);
}

/* ---------- Build record ---------- */
$tzNow = new DateTime('now', new DateTimeZone('Africa/Johannesburg'));
$record = array(
  'reference'  => $reference,
  'cardholder' => $CARDHOLDER,
  'firstName'  => $firstName,
  'lastName'   => $lastName,
  'fullName'   => $fullName,
  'email'      => $email,
  'phone'      => $phone,
  'source'     => 'Digital Business Card',
  'channel'    => $channel,
  'timestamp'  => $tzNow->format(DateTime::ATOM),
  'humanDate'  => $tzNow->format('D, d M Y H:i') . ' SAST',
  'ipHash'     => substr($ipHash, 0, 16),
  'status'     => 'new',
  'notes'      => ''
);

/* ---------- Append to shared leads file ---------- */
$lh = @fopen($leadsFile, 'c+');
if ($lh) {
  flock($lh, LOCK_EX);
  $existing = stream_get_contents($lh);
  $leads = $existing ? json_decode($existing, true) : array();
  if (!is_array($leads)) $leads = array();
  $leads[] = $record;
  rewind($lh); ftruncate($lh, 0);
  fwrite($lh, json_encode($leads, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
  flock($lh, LOCK_UN); fclose($lh);
}

/* ---------- Notification email (AEE sky-blue + navy branded) ---------- */
function ae_esc($s) { return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); }
function ae_boundary($prefix) {
  return $prefix . '_' . bin2hex(openssl_random_pseudo_bytes(8));
}

$fromHeader = $FROM_NAME . ' <' . $FROM_ADDRESS . '>';
$boundary   = ae_boundary('AENOT');

$plainBody  = "New lead via AEE Group Digital Business Card\r\n\r\n";
$plainBody .= "Reference: " . $reference . "\r\n";
$plainBody .= "Cardholder: " . $CARDHOLDER . "\r\n";
$plainBody .= "Name: " . $fullName . "\r\n";
if ($phone !== '') $plainBody .= "Mobile: " . $phone . "\r\n";
if ($email !== '') $plainBody .= "Email: " . $email . "\r\n";
$plainBody .= "Channel: " . $channel . "\r\n";
$plainBody .= "Received: " . $record['humanDate'] . "\r\n";

$htmlBody  = '<!doctype html><html><body style="margin:0;background:#F4F6F8;font-family:Helvetica,Arial,sans-serif;color:' . ae_esc($BRAND_NAVY) . ';padding:24px;">';
$htmlBody .= '<div style="max-width:560px;margin:0 auto;background:#FFFFFF;border:1px solid ' . ae_esc($BRAND_DIVIDER) . ';border-radius:14px;overflow:hidden;">';
// AEE half-moon-inspired header: sky-blue with white half-circle pseudo-element at top
$htmlBody .= '<div style="background:' . ae_esc($BRAND_BLUE) . ';padding:24px 22px 18px;color:#FFFFFF;position:relative;">';
$htmlBody .= '<div style="font-size:10.5px;letter-spacing:.30em;text-transform:uppercase;font-weight:700;opacity:.92;">' . ae_esc($BRAND_NAME) . '</div>';
$htmlBody .= '<div style="font-size:11px;opacity:.75;margin-top:2px;letter-spacing:.04em;">' . ae_esc($BRAND_FULLNAME) . '</div>';
$htmlBody .= '<div style="font-size:18px;font-weight:700;margin-top:10px;">New Lead, ' . ae_esc($reference) . '</div>';
$htmlBody .= '</div>';
$htmlBody .= '<div style="padding:22px;">';
$htmlBody .= '<table cellpadding="0" cellspacing="0" style="width:100%;font-size:14px;line-height:1.55;color:' . ae_esc($BRAND_NAVY) . ';">';
$htmlBody .= '<tr><td style="color:' . ae_esc($BRAND_GREY) . ';width:120px;padding:6px 0;font-weight:600;font-size:11px;letter-spacing:.10em;text-transform:uppercase;">Cardholder</td><td style="padding:6px 0;">' . ae_esc($CARDHOLDER) . '</td></tr>';
$htmlBody .= '<tr><td style="color:' . ae_esc($BRAND_GREY) . ';padding:6px 0;font-weight:600;font-size:11px;letter-spacing:.10em;text-transform:uppercase;">Name</td><td style="padding:6px 0;">' . ae_esc($fullName) . '</td></tr>';
if ($phone !== '') {
  $htmlBody .= '<tr><td style="color:' . ae_esc($BRAND_GREY) . ';padding:6px 0;font-weight:600;font-size:11px;letter-spacing:.10em;text-transform:uppercase;">Mobile</td><td style="padding:6px 0;"><a style="color:' . ae_esc($BRAND_NAVY) . ';text-decoration:none;" href="tel:' . ae_esc($phone) . '">' . ae_esc($phone) . '</a></td></tr>';
}
if ($email !== '') {
  $htmlBody .= '<tr><td style="color:' . ae_esc($BRAND_GREY) . ';padding:6px 0;font-weight:600;font-size:11px;letter-spacing:.10em;text-transform:uppercase;">Email</td><td style="padding:6px 0;"><a style="color:' . ae_esc($BRAND_NAVY) . ';text-decoration:none;" href="mailto:' . ae_esc($email) . '">' . ae_esc($email) . '</a></td></tr>';
}
$htmlBody .= '<tr><td style="color:' . ae_esc($BRAND_GREY) . ';padding:6px 0;font-weight:600;font-size:11px;letter-spacing:.10em;text-transform:uppercase;">Channel</td><td style="padding:6px 0;">' . ae_esc(ucfirst($channel)) . '</td></tr>';
$htmlBody .= '<tr><td style="color:' . ae_esc($BRAND_GREY) . ';padding:6px 0;font-weight:600;font-size:11px;letter-spacing:.10em;text-transform:uppercase;">Received</td><td style="padding:6px 0;">' . ae_esc($record['humanDate']) . '</td></tr>';
$htmlBody .= '</table></div>';
$htmlBody .= '<div style="padding:14px 22px;border-top:1px solid ' . ae_esc($BRAND_DIVIDER) . ';color:' . ae_esc($BRAND_NAVY) . ';font-size:11px;text-align:center;font-style:italic;">' . ae_esc($BRAND_TAGLINE) . '</div>';
$htmlBody .= '</div></body></html>';

$msg  = '--' . $boundary . "\r\n";
$msg .= "Content-Type: text/plain; charset=UTF-8\r\n";
$msg .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
$msg .= $plainBody . "\r\n";
$msg .= '--' . $boundary . "\r\n";
$msg .= "Content-Type: text/html; charset=UTF-8\r\n";
$msg .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
$msg .= $htmlBody . "\r\n";
$msg .= '--' . $boundary . "--\r\n";

$headers = array(
  'From: ' . $fromHeader,
  'Reply-To: ' . ($email !== '' ? $email : $FROM_ADDRESS),
  'MIME-Version: 1.0',
  'Content-Type: multipart/alternative; boundary="' . $boundary . '"',
  'X-Mailer: AEE-Card/1.0'
);

$subject = '[' . $BRAND_NAME . '] New lead ' . $reference . ': ' . $fullName;

// Deliver to each notification recipient
foreach ($NOTIFY_TO as $to) {
  @mail($to, $subject, $msg, implode("\r\n", $headers), '-f' . $FROM_ADDRESS);
}

// Silent BCC archive
foreach ($NOTIFY_BCC as $bcc) {
  @mail($bcc, $subject, $msg, implode("\r\n", $headers), '-f' . $FROM_ADDRESS);
}

/* ---------- Auto-reply (AEE-branded) ---------- */
if ($AUTOREPLY_ENABLED && $email !== '') {
  $greet = $firstName !== '' ? ('Hi ' . $firstName) : 'Hi there';
  $arPlain  = $greet . ",\r\n\r\n";
  $arPlain .= "Thanks for sharing your details with " . $BRAND_PERSON . " at " . $BRAND_NAME . " (" . $BRAND_FULLNAME . "). We have received your information and will be in touch soon.\r\n\r\n";
  $arPlain .= "Reference: " . $reference . "\r\n\r\n";
  $arPlain .= "From the team at " . $BRAND_NAME . "\r\n" . $BRAND_TAGLINE . "\r\n";

  $arHtml  = '<!doctype html><html><body style="margin:0;background:#F4F6F8;font-family:Helvetica,Arial,sans-serif;color:' . ae_esc($BRAND_NAVY) . ';padding:24px;">';
  $arHtml .= '<div style="max-width:560px;margin:0 auto;background:#FFFFFF;border:1px solid ' . ae_esc($BRAND_DIVIDER) . ';border-radius:14px;overflow:hidden;">';
  $arHtml .= '<div style="background:' . ae_esc($BRAND_BLUE) . ';padding:24px 22px 20px;color:#FFFFFF;">';
  $arHtml .= '<div style="font-size:10.5px;letter-spacing:.30em;text-transform:uppercase;font-weight:700;opacity:.92;">' . ae_esc($BRAND_NAME) . '</div>';
  $arHtml .= '<div style="font-size:11px;opacity:.75;margin-top:2px;letter-spacing:.04em;">' . ae_esc($BRAND_FULLNAME) . '</div>';
  $arHtml .= '<div style="font-size:20px;font-weight:700;margin-top:10px;">Thank you, ' . ae_esc($firstName !== '' ? $firstName : 'and welcome') . '</div>';
  $arHtml .= '</div><div style="padding:24px 22px;font-size:14px;line-height:1.65;">';
  $arHtml .= 'Thanks for sharing your details with <strong>' . ae_esc($BRAND_PERSON) . '</strong>, ' . ae_esc($BRAND_TITLE) . ' at ' . ae_esc($BRAND_NAME) . '. We have received your information and will be in touch soon.';
  $arHtml .= '<div style="margin-top:18px;color:' . ae_esc($BRAND_GREY) . ';font-size:12px;">Reference: ' . ae_esc($reference) . '</div>';
  $arHtml .= '</div><div style="padding:14px 22px;border-top:1px solid ' . ae_esc($BRAND_DIVIDER) . ';color:' . ae_esc($BRAND_NAVY) . ';font-size:11px;text-align:center;font-style:italic;">' . ae_esc($BRAND_TAGLINE) . '</div>';
  $arHtml .= '</div></body></html>';

  $arBoundary = ae_boundary('AEAR');
  $arMsg  = '--' . $arBoundary . "\r\n";
  $arMsg .= "Content-Type: text/plain; charset=UTF-8\r\n\r\n" . $arPlain . "\r\n";
  $arMsg .= '--' . $arBoundary . "\r\n";
  $arMsg .= "Content-Type: text/html; charset=UTF-8\r\n\r\n" . $arHtml . "\r\n";
  $arMsg .= '--' . $arBoundary . "--\r\n";
  $arHeaders = array(
    'From: ' . $fromHeader,
    'Reply-To: ' . $FROM_ADDRESS,
    'MIME-Version: 1.0',
    'Content-Type: multipart/alternative; boundary="' . $arBoundary . '"',
    'X-Mailer: AEE-Card/1.0'
  );
  @mail($email, $AUTOREPLY_SUBJECT, $arMsg, implode("\r\n", $arHeaders), '-f' . $FROM_ADDRESS);
}

echo json_encode(array('ok' => true, 'reference' => $reference));
