<?php
/**
 * Email Configuration for GermCure
 * With SMTP support and spam protection
 */

// SMTP Configuration
define('SMTP_HOST', 'mail.germcure.co.za');
define('SMTP_PORT', 587);
define('SMTP_SECURE', 'tls');
define('SMTP_USERNAME', 'info@germcure.co.za');
define('SMTP_PASSWORD', 'T9!jL5$xFm2pK8#dW');
define('SMTP_FROM_EMAIL', 'info@germcure.co.za');
define('SMTP_FROM_NAME', 'GermCure');

// Rate limiting for emails (max emails per hour from same IP)
define('EMAIL_RATE_LIMIT', 5);
define('EMAIL_RATE_WINDOW', 3600); // 1 hour in seconds

// Get email addresses for a specific brand
function getBrandEmails($brand) {
    $domain = $brand . '.co.za';

    $emails = [
        'info' => 'info@' . $domain,
        'cois' => 'cois@' . $domain,
        'admin' => 'admin@' . $domain,
        'quotes' => 'quotes@' . $domain,
        'sales' => 'sales@' . $domain,
    ];

    // Additional email for farmcure, germcure, pestcure
    if (in_array($brand, ['farmcure', 'germcure', 'pestcure'])) {
        $emails['mariaan'] = 'mariaan@' . $domain;
    }

    return $emails;
}

// Get quote recipients
function getQuoteRecipients($brand) {
    $emails = getBrandEmails($brand);
    return [$emails['quotes'], $emails['sales']];
}

// Get general contact recipient
function getContactRecipient($brand) {
    $emails = getBrandEmails($brand);
    // GermCure emails go to Mariaan
    if ($brand === 'germcure') {
        return $emails['mariaan'];
    }
    return $emails['info'];
}

/**
 * Check email rate limit to prevent spam
 */
function checkEmailRateLimit($identifier = null) {
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }

    $identifier = $identifier ?? ($_SERVER['REMOTE_ADDR'] ?? 'unknown');
    $key = 'email_rate_' . md5($identifier);
    $now = time();

    if (!isset($_SESSION[$key])) {
        $_SESSION[$key] = [];
    }

    // Remove old entries outside the window
    $_SESSION[$key] = array_filter($_SESSION[$key], function($timestamp) use ($now) {
        return ($now - $timestamp) < EMAIL_RATE_WINDOW;
    });

    // Check if over limit
    if (count($_SESSION[$key]) >= EMAIL_RATE_LIMIT) {
        return false;
    }

    // Add current timestamp
    $_SESSION[$key][] = $now;
    return true;
}

/**
 * Validate email content for spam patterns
 */
function isSpamContent($content) {
    $spamPatterns = [
        '/\b(viagra|cialis|pharmacy|casino|lottery|winner|million\s*dollars?)\b/i',
        '/\b(click\s*here|act\s*now|limited\s*time|free\s*money)\b/i',
        '/(http[s]?:\/\/[^\s]+){3,}/i', // Too many URLs
        '/(.)\1{10,}/', // Repeated characters
        '/[А-Яа-яЁё]{5,}/', // Cyrillic text (common in spam)
    ];

    foreach ($spamPatterns as $pattern) {
        if (preg_match($pattern, $content)) {
            return true;
        }
    }

    return false;
}

/**
 * Sanitize email content
 */
function sanitizeEmailContent($content) {
    // Remove potentially dangerous content
    $content = strip_tags($content);
    $content = htmlspecialchars($content, ENT_QUOTES, 'UTF-8');
    // Limit length
    $content = substr($content, 0, 5000);
    return $content;
}

/**
 * Send email using PHP mail() with proper headers
 * For production with high volume, consider using PHPMailer with SMTP
 */
function sendSecureEmail($to, $subject, $message, $replyTo = null, $isHtml = false) {
    // Check rate limit
    if (!checkEmailRateLimit()) {
        error_log('Email rate limit exceeded for IP: ' . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
        return false;
    }

    // Sanitize inputs
    $to = filter_var($to, FILTER_SANITIZE_EMAIL);
    $subject = substr(strip_tags($subject), 0, 200);

    if (!$isHtml) {
        $message = sanitizeEmailContent($message);
    }

    // Check for spam
    if (isSpamContent($message) || isSpamContent($subject)) {
        error_log('Spam detected in email from IP: ' . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
        return false;
    }

    // Build headers
    $headers = [];
    $headers[] = 'MIME-Version: 1.0';
    $headers[] = $isHtml ? 'Content-type: text/html; charset=UTF-8' : 'Content-type: text/plain; charset=UTF-8';
    $headers[] = 'From: ' . SMTP_FROM_NAME . ' <' . SMTP_FROM_EMAIL . '>';
    $headers[] = 'X-Mailer: PHP/' . phpversion();
    $headers[] = 'X-Originating-IP: ' . ($_SERVER['REMOTE_ADDR'] ?? 'unknown');

    if ($replyTo && filter_var($replyTo, FILTER_VALIDATE_EMAIL)) {
        $headers[] = 'Reply-To: ' . $replyTo;
    }

    // Send email
    $result = mail($to, $subject, $message, implode("\r\n", $headers));

    if ($result) {
        error_log('Email sent successfully to: ' . $to . ' Subject: ' . $subject);
    } else {
        error_log('Email failed to: ' . $to . ' Subject: ' . $subject);
    }

    return $result;
}

/**
 * Send contact form email with all protections
 */
function sendContactEmail($brand, $data) {
    $to = getContactRecipient($brand);
    $subject = ucfirst($brand) . " Contact Form - " . ($data['subject'] ?? 'General Inquiry');

    $message = "NEW CONTACT FORM SUBMISSION\n";
    $message .= "===========================\n\n";
    $message .= "Name: " . sanitizeEmailContent($data['name'] ?? 'N/A') . "\n";
    $message .= "Email: " . filter_var($data['email'] ?? '', FILTER_SANITIZE_EMAIL) . "\n";
    $message .= "Phone: " . preg_replace('/[^0-9+\-\s()]/', '', $data['phone'] ?? 'N/A') . "\n";
    $message .= "Company: " . sanitizeEmailContent($data['company'] ?? 'N/A') . "\n";
    $message .= "Subject: " . sanitizeEmailContent($data['subject'] ?? 'N/A') . "\n\n";
    $message .= "Message:\n" . sanitizeEmailContent($data['message'] ?? 'N/A') . "\n\n";
    $message .= "---\n";
    $message .= "Submitted: " . date('Y-m-d H:i:s') . "\n";
    $message .= "IP Address: " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown') . "\n";

    $replyTo = filter_var($data['email'] ?? '', FILTER_VALIDATE_EMAIL) ? $data['email'] : null;

    return sendSecureEmail($to, $subject, $message, $replyTo);
}

/**
 * Send quote request email
 */
function sendQuoteEmail($brand, $data) {
    $recipients = getQuoteRecipients($brand);
    $to = implode(', ', $recipients);
    $subject = ucfirst($brand) . " - Quote Request";

    $message = "NEW QUOTE REQUEST\n";
    $message .= "=================\n\n";
    $message .= "Name: " . sanitizeEmailContent($data['name'] ?? 'N/A') . "\n";
    $message .= "Email: " . filter_var($data['email'] ?? '', FILTER_SANITIZE_EMAIL) . "\n";
    $message .= "Phone: " . preg_replace('/[^0-9+\-\s()]/', '', $data['phone'] ?? 'N/A') . "\n";
    $message .= "Company: " . sanitizeEmailContent($data['company'] ?? 'N/A') . "\n\n";
    $message .= "Products/Services:\n" . sanitizeEmailContent($data['products'] ?? 'N/A') . "\n\n";
    $message .= "Message:\n" . sanitizeEmailContent($data['message'] ?? 'N/A') . "\n\n";
    $message .= "---\n";
    $message .= "Submitted: " . date('Y-m-d H:i:s') . "\n";
    $message .= "IP Address: " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown') . "\n";

    $replyTo = filter_var($data['email'] ?? '', FILTER_VALIDATE_EMAIL) ? $data['email'] : null;

    return sendSecureEmail($to, $subject, $message, $replyTo);
}
?>
