<?php
/**
 * GermCure - Contact Form Handler
 * With security: Math CAPTCHA, honeypot, rate limiting, time check
 */

require_once __DIR__ . '/includes/security.php';
require_once __DIR__ . '/includes/email_config.php';

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

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

// Security validation
$securityCheck = validateFormSubmission('germcure_contact_form', true);
if (!$securityCheck['valid']) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => $securityCheck['error']]);
    exit;
}

// Sanitize inputs
$firstName = sanitizeString($_POST['first_name'] ?? '', 50);
$lastName = sanitizeString($_POST['last_name'] ?? '', 50);
$name = trim($firstName . ' ' . $lastName);
$email = sanitizeEmail($_POST['email'] ?? '');
$phone = sanitizePhone($_POST['phone'] ?? '');
$company = sanitizeString($_POST['company'] ?? '', 100);
$subject = sanitizeString($_POST['subject'] ?? '', 100);
$message = sanitizeString($_POST['message'] ?? '', 2000);

if (empty($firstName) || empty($email) || empty($message)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Please fill in all required fields']);
    exit;
}

if ($email === false) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Please enter a valid email address']);
    exit;
}

$to = 'cois@germcure.co.za';
$emailSubject = "GermCure Contact: " . ($subject ?: 'General Inquiry');

$emailBody = "
===========================================
GERMCURE - CONTACT FORM MESSAGE
===========================================

CUSTOMER DETAILS:
-----------------
Name: {$name}
Email: {$email}
Phone: {$phone}
Company: {$company}
Subject: {$subject}

MESSAGE:
--------
{$message}

===========================================
Submitted via GermCure website contact form.
";

$headers = "From: GermCure Website <noreply@germcure.co.za>\r\n";
$headers .= "Reply-To: {$email}\r\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\r\n";

$mailSent = mail($to, $emailSubject, $emailBody, $headers);

if ($mailSent) {
    // Send confirmation to customer
    $customerSubject = "Message Received - GermCure";
    $customerBody = "Dear {$name},

Thank you for contacting GermCure.

We have received your message and will get back to you within 24 hours.

Best regards,
GermCure Team
Disinfection & Hygiene Solutions
Pretoria, South Africa
";
    $customerHeaders = "From: GermCure <cois@germcure.co.za>\r\n";
    $customerHeaders .= "Content-Type: text/plain; charset=UTF-8\r\n";
    mail($email, $customerSubject, $customerBody, $customerHeaders);

    echo json_encode(['success' => true, 'message' => 'Message sent successfully!']);
} else {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Failed to send. Please try again or contact us directly.']);
}
?>
