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

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = trim($_POST['name'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $course = trim($_POST['course'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $userMessage = trim($_POST['message'] ?? '');
    $captcha = trim($_POST['captcha'] ?? '');
    $captchaExpected = trim($_POST['captcha_expected'] ?? '');
    
    // Basic validation
    if (empty($name) || empty($phone) || empty($email)) {
        echo json_encode(["status" => "error", "message" => "Name, Email and Phone are required."]);
        exit;
    }
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo json_encode(["status" => "error", "message" => "Please enter a valid email address."]);
        exit;
    }
    // Captcha validation (simple maths)
    if ($captchaExpected === '' || $captcha === '' || $captcha !== $captchaExpected) {
        echo json_encode(["status" => "error", "message" => "Captcha incorrect. Please try again."]);
        exit;
    }

    $to = "Admin@mytechcertificate.com";
    $subject = "New Lead from Popup Form: " . $course;
    
    // Format email
    $message = "You have received a new lead from the website popup.\n\n";
    $message .= "Name: " . $name . "\n";
    $message .= "Email: " . $email . "\n";
    $message .= "Phone: " . $phone . "\n";
    $message .= "Course Interested: " . ($course ? $course : "Not specified") . "\n";
    if (!empty($userMessage)) {
        $message .= "Message: " . $userMessage . "\n";
    }
    
    $headers = "From: no-reply@mytechcertificate.com\r\n";
    $headers .= "Reply-To: Admin@mytechcertificate.com\r\n";

    // Send email
    @mail($to, $subject, $message, $headers);
    
    echo json_encode(["status" => "success", "message" => "Thank you for your interest! Our team will contact you shortly."]);
} else {
    echo json_encode(["status" => "error", "message" => "Invalid request method."]);
}
?>
