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

header('Content-Type: application/json');

// Only allow POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
}

// Read JSON body
$raw = file_get_contents('php://input');
$data = json_decode($raw, true);

if (!is_array($data)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Invalid request data']);
    exit;
}

// Validate CSRF token (sent via header from main.js)
$csrf = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? ($data['_csrf'] ?? '');
if (!validateCSRF($csrf)) {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => 'Session expired. Please refresh the page and try again.']);
    exit;
}

// --- ANTI-SPAM LAYER 1: Honeypot ---
// The "website" field is hidden from real users via CSS in register.php.
// Bots fill every field they find, so a non-empty value here means it's a bot.
// We return a FAKE success so the bot's script doesn't know it was blocked
// (this discourages the bot operator from retrying/adapting).
if (!empty(trim($data['website'] ?? ''))) {
    echo json_encode(['success' => true, 'message' => 'Thank you! We will be in touch shortly.']);
    exit;
}

// --- ANTI-SPAM LAYER 2: Rate limiting per IP ---
// File-based, no session dependency (this is a stateless JSON API call).
// Blocks more than 3 submissions from the same IP within 60 seconds.
$ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
$rateLimitFile = __DIR__ . '/../data/rate_limit.json';
$rateLimitWindow = 60;   // seconds
$rateLimitMax    = 3;    // max submissions per window

$rateData = [];
if (file_exists($rateLimitFile)) {
    $rateData = json_decode(file_get_contents($rateLimitFile), true);
    if (!is_array($rateData)) $rateData = [];
}

$now = time();
// Prune old entries for this IP
$rateData[$ip] = array_values(array_filter($rateData[$ip] ?? [], function($ts) use ($now, $rateLimitWindow) {
    return ($now - $ts) < $rateLimitWindow;
}));

if (count($rateData[$ip]) >= $rateLimitMax) {
    http_response_code(429);
    echo json_encode(['success' => false, 'error' => 'Too many submissions. Please wait a minute and try again.']);
    exit;
}

$rateData[$ip][] = $now;
@file_put_contents($rateLimitFile, json_encode($rateData), LOCK_EX);

// --- ANTI-SPAM LAYER 3: Bot-pattern detection ---
// Catches randomly-generated strings like "UpDbsiaNPlqqEeOIW" or "WofgZSeHYBsomwBKp"
// (no vowels, or excessive upper/lowercase alternation — humans don't type like this).
function looksLikeBotString($str) {
    $str = trim($str);
    if ($str === '' || strlen($str) < 6) return false;

    // No vowels at all in a 6+ letter alphabetic string
    if (preg_match('/^[a-zA-Z]{6,}$/', $str) && !preg_match('/[aeiouAEIOU]/', $str)) {
        return true;
    }
    // Excessive case-alternation (e.g. UpDbsiaNPlqqEeOIW has many switches)
    $switches = preg_match_all('/[a-z][A-Z]|[A-Z][a-z]/', $str);
    if ($switches >= 5) {
        return true;
    }
    return false;
}

// Basic required-field validation
$type  = trim($data['type'] ?? 'other');
$name  = trim($data['name'] ?? '');
$email = trim($data['email'] ?? '');

if (looksLikeBotString($name) || looksLikeBotString(trim($data['company'] ?? ''))) {
    // Fake success — don't tip off the bot operator
    echo json_encode(['success' => true, 'message' => 'Thank you! We will be in touch shortly.']);
    exit;
}

if ($type !== 'newsletter' && $name === '') {
    echo json_encode(['success' => false, 'error' => 'Name is required.']);
    exit;
}

if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(['success' => false, 'error' => 'A valid email address is required.']);
    exit;
}

// Build the lead record
$lead = [
    'id'         => bin2hex(random_bytes(8)),
    'type'       => $type,
    'name'       => $name,
    'email'      => $email,
    'phone'      => trim($data['phone'] ?? ''),
    'company'    => trim($data['company'] ?? ''),
    'job_title'  => trim($data['job_title'] ?? ''),
    'country'    => trim($data['country'] ?? ''),
    'city'       => trim($data['city'] ?? ''),
    'interest'   => trim($data['interest'] ?? ''),
    'sector'     => $data['sector'] ?? [],
    'source'     => trim($data['source'] ?? ''),
    'message'    => trim($data['message'] ?? ''),
    'consent'    => !empty($data['consent']),
    'created_at' => date('Y-m-d H:i:s'),
    'ip'         => $_SERVER['REMOTE_ADDR'] ?? '',
];

// Save to leads.json
$leads = readJSON(LEADS_FILE);
if (!is_array($leads)) $leads = [];
$leads[] = $lead;
writeJSON(LEADS_FILE, $leads);

// Send notification email
sendLeadNotification($lead);

echo json_encode(['success' => true, 'message' => 'Thank you! We will be in touch shortly.']);
exit;


/**
 * Sends a notification email to all addresses in NOTIFY_EMAILS
 * for any new lead/contact/newsletter submission.
 * Logs every attempt (success/failure) to data/mail_log.txt for debugging.
 */
function sendLeadNotification($lead) {
    $recipients = defined('NOTIFY_EMAILS') ? NOTIFY_EMAILS : [SITE_EMAIL];

    $typeLabel = ucfirst($lead['type']);
    $subject = '[' . SITE_NAME . '] New ' . $typeLabel . ' Submission: ' . $lead['name'];

    $body  = "A new submission was received on " . SITE_URL . "\n\n";
    $body .= "Type:       " . $typeLabel . "\n";
    $body .= "Name:       " . $lead['name'] . "\n";
    $body .= "Email:      " . $lead['email'] . "\n";
    if (!empty($lead['phone']))      $body .= "Phone:      " . $lead['phone'] . "\n";
    if (!empty($lead['company']))    $body .= "Company:    " . $lead['company'] . "\n";
    if (!empty($lead['job_title']))  $body .= "Job Title:  " . $lead['job_title'] . "\n";
    if (!empty($lead['country']))    $body .= "Country:    " . $lead['country'] . "\n";
    if (!empty($lead['city']))       $body .= "City:       " . $lead['city'] . "\n";
    if (!empty($lead['interest']))   $body .= "Interest:   " . $lead['interest'] . "\n";
    if (!empty($lead['sector']) && is_array($lead['sector'])) {
        $body .= "Sectors:    " . implode(', ', $lead['sector']) . "\n";
    }
    if (!empty($lead['source']))     $body .= "Source:     " . $lead['source'] . "\n";
    if (!empty($lead['message']))    $body .= "Message:\n" . $lead['message'] . "\n";
    $body .= "\nSubmitted:  " . $lead['created_at'] . "\n";
    $body .= "IP Address: " . $lead['ip'] . "\n";

    // Use a known-working, deliverable mailbox as the From address.
    $fromAddress = defined('ADMIN_EMAIL') ? ADMIN_EMAIL : (defined('SITE_EMAIL') ? SITE_EMAIL : 'no-reply@' . parse_url(SITE_URL, PHP_URL_HOST));

    $headers = [];
    $headers[] = 'From: ' . SITE_NAME . ' <' . $fromAddress . '>';
    if (!empty($lead['email'])) {
        $headers[] = 'Reply-To: ' . $lead['email'];
    }
    $headers[] = 'Content-Type: text/plain; charset=UTF-8';
    $headers[] = 'X-Mailer: PHP/' . phpversion();
    $headerStr = implode("\r\n", $headers);

    $logFile = __DIR__ . '/../data/mail_log.txt';
    $logLines = [];

    // Send individually to each recipient so one bad/blocked address
    // doesn't silently affect delivery to the others, and so we can log per-recipient results.
    foreach ($recipients as $recipient) {
        $recipient = trim($recipient);
        if ($recipient === '') continue;

        $ok = @mail($recipient, $subject, $body, $headerStr, '-f' . $fromAddress);

        $logLines[] = sprintf(
            '[%s] To: %-30s | From: %-30s | Result: %s',
            date('Y-m-d H:i:s'),
            $recipient,
            $fromAddress,
            $ok ? 'ACCEPTED by mail()' : 'FAILED — mail() returned false'
        );
    }

    // Append to log file (create if missing); never let logging break the request.
    @file_put_contents($logFile, implode("\n", $logLines) . "\n", FILE_APPEND | LOCK_EX);
}