<?php
// Prevent ANY output before JSON
ob_start();

// Disable all error display immediately
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(0);

session_start();

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

require_once dirname(__DIR__) . '/vendor/autoload.php';

// Clear any buffered output
ob_clean();

// Set headers
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-cache, must-revalidate');

try {
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $subject = trim($_POST['subject'] ?? '');
    $message = trim($_POST['message'] ?? '');

    if (empty($name) || empty($email) || empty($subject) || empty($message)) {
        ob_end_clean();
        echo json_encode(['status' => false, 'message' => 'Please fill in all required fields.']);
        exit;
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        ob_end_clean();
        echo json_encode(['status' => false, 'message' => 'Please provide a valid email address.']);
        exit;
    }

    $mail = new PHPMailer(true);

    $mail->isSMTP();
    $mail->Host = 'mail.findcarrierjob.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'info@findcarrierjob.com';
    $mail->Password = '(z_,o1r9s~MsFAD?';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
    $mail->Port = 465;
    $mail->SMTPDebug = 0;

    $mail->setFrom('info@findcarrierjob.com', 'Carrier Jobs');
    $mail->addAddress('bamaniamohit2@gmail.com');
    $mail->addReplyTo($email, $name);

    $mail->isHTML(true);
    $mail->Subject = "Contact Form: " . htmlspecialchars($subject);
    $mail->Body = "
        <h2>New Contact Message</h2>
        <p><strong>Name:</strong> " . htmlspecialchars($name) . "</p>
        <p><strong>Email:</strong> " . htmlspecialchars($email) . "</p>
        <p><strong>Subject:</strong> " . htmlspecialchars($subject) . "</p>
        <p><strong>Message:</strong><br>" . nl2br(htmlspecialchars($message)) . "</p>
    ";

    $mail->send();

    ob_end_clean();
    echo json_encode(['status' => true, 'message' => 'Your message has been sent successfully!']);

} catch (Exception $e) {
    error_log("Contact form error: " . $e->getMessage());
    ob_end_clean();
    echo json_encode(['status' => false, 'message' => 'Unable to send message. Please try again later.']);
}

exit;