<?php
/**
 * controllers/contactSubmit.php
 *
 * Handles the homepage contact form submission.
 * Validates input, sends an email via PHPMailer, redirects back with status.
 */

require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../config/mail.php';
require_once __DIR__ . '/../lib/csrf.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Only accept POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: /#contact');
    exit;
}

// CSRF check
if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
    $_SESSION['contact_error'] = 'Invalid form submission. Please try again.';
    header('Location: /#contact');
    exit;
}

// Collect + sanitise fields
$firstName = trim(htmlspecialchars($_POST['first_name'] ?? '', ENT_QUOTES, 'UTF-8'));
$lastName  = trim(htmlspecialchars($_POST['last_name']  ?? '', ENT_QUOTES, 'UTF-8'));
$email     = trim(filter_var($_POST['email'] ?? '', FILTER_SANITIZE_EMAIL));
$farmType  = trim(htmlspecialchars($_POST['farm_type'] ?? '', ENT_QUOTES, 'UTF-8'));
$message   = trim(htmlspecialchars($_POST['message']   ?? '', ENT_QUOTES, 'UTF-8'));

// Basic validation
if (!$firstName || !$lastName) {
    $_SESSION['contact_error'] = 'Please enter your full name.';
    header('Location: /#contact');
    exit;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $_SESSION['contact_error'] = 'Please enter a valid email address.';
    header('Location: /#contact');
    exit;
}

if (!$message) {
    $_SESSION['contact_error'] = 'Please enter a message.';
    header('Location: /#contact');
    exit;
}

// Build email body
$fullName   = $firstName . ' ' . $lastName;
$farmLabel  = $farmType ?: 'Not specified';
$bodyHtml   = "
<h2>New Contact Form Submission</h2>
<table cellpadding='6' style='font-family:sans-serif;font-size:14px;'>
  <tr><td><strong>Name</strong></td><td>" . $fullName . "</td></tr>
  <tr><td><strong>Email</strong></td><td>" . $email . "</td></tr>
  <tr><td><strong>Farm Type</strong></td><td>" . $farmLabel . "</td></tr>
  <tr><td><strong>Message</strong></td><td>" . nl2br($message) . "</td></tr>
</table>
";
$bodyText = "Name: {$fullName}\nEmail: {$email}\nFarm Type: {$farmLabel}\n\nMessage:\n{$message}";

// Send via PHPMailer
$mail = new PHPMailer(true);

try {
    $mail->isSMTP();
    $mail->Host       = MAIL_HOST;
    $mail->SMTPAuth   = true;
    $mail->Username   = MAIL_USERNAME;
    $mail->Password   = MAIL_PASSWORD;
    $mail->SMTPSecure = MAIL_ENCRYPTION === 'ssl' ? PHPMailer::ENCRYPTION_SMTPS : PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = MAIL_PORT;

    $mail->setFrom(MAIL_FROM, MAIL_FROM_NAME);
    $mail->addAddress(MAIL_TO);
    $mail->addReplyTo($email, $fullName);

    $mail->isHTML(true);
    $mail->Subject = 'Contact Form: ' . $fullName . ' (' . $farmLabel . ')';
    $mail->Body    = $bodyHtml;
    $mail->AltBody = $bodyText;

    $mail->send();

    $_SESSION['contact_success'] = 'Thank you, ' . $firstName . '. We\'ll be in touch soon.';

} catch (Exception $e) {
    error_log('Contact form mailer error: ' . $mail->ErrorInfo);
    $_SESSION['contact_error'] = 'Sorry, we couldn\'t send your message. Please try again later.';
}

header('Location: /#contact');
exit;
