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

// Bootstrap app config (SMTP credentials, ADMIN_EMAIL, etc.)
require_once 'config/config.php';

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

// Sanitize helper
function clean($str) {
    return htmlspecialchars(strip_tags(trim($str)), ENT_QUOTES, 'UTF-8');
}

$name    = clean($_POST['form_name']    ?? '');
$email   = clean($_POST['form_email']   ?? '');
$message = clean($_POST['form_message'] ?? '');

// Validate
$errors = [];
if (empty($name))                          $errors[] = 'Name is required.';
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'A valid email address is required.';
if (empty($message))                       $errors[] = 'Message is required.';

if (!empty($errors)) {
    echo json_encode(['success' => false, 'message' => implode(' ', $errors)]);
    exit();
}

// ── PHPMailer ──────────────────────────────────────────────────────────────
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

if (!class_exists(PHPMailer::class)) {
    echo json_encode(['success' => false, 'message' => 'Mail library not available. Please try again later.']);
    exit();
}

$mail = new PHPMailer(true);

try {
    $mail->isSMTP();
    $mail->Host       = SMTP_HOST;
    $mail->SMTPAuth   = true;
    $mail->Username   = SMTP_USERNAME;
    $mail->Password   = SMTP_PASSWORD;
    $mail->SMTPSecure = SMTP_ENCRYPTION;
    $mail->Port       = SMTP_PORT;

    // ── To / From ───────────────────────────────────────────────────────────
    $mail->setFrom(SITE_EMAIL, SITE_NAME);
    $mail->addAddress(ADMIN_EMAIL, 'Avondex Capital Admin');
    $mail->addReplyTo($email, $name);

    // ── Content ─────────────────────────────────────────────────────────────
    $mail->isHTML(true);
    $mail->Subject = 'New Contact Message from ' . $name;
    $mail->Body    = "
        <h2 style='color:#1A4137;'>New Contact Form Submission</h2>
        <p><strong>Name:</strong> {$name}</p>
        <p><strong>Email:</strong> <a href='mailto:{$email}'>{$email}</a></p>
        <hr>
        <p><strong>Message:</strong></p>
        <p style='white-space:pre-wrap;'>{$message}</p>
        <hr>
        <small>Sent via the contact form on " . SITE_NAME . " &mdash; " . date('Y-m-d H:i:s T') . "</small>
    ";
    $mail->AltBody = "Name: {$name}\nEmail: {$email}\n\nMessage:\n{$message}";

    $mail->send();
    echo json_encode(['success' => true, 'message' => 'Thank you! Your message has been sent successfully. We will be in touch shortly.']);

} catch (Exception $e) {
    error_log('Contact form mail error: ' . $mail->ErrorInfo);
    echo json_encode(['success' => false, 'message' => 'Message could not be sent at this time. Please email us directly at ' . SITE_EMAIL]);
}
?>
