<?php
$subject = "Leads | Beyond Browse";

$name = htmlspecialchars($_POST['name']);
$phone = htmlspecialchars($_POST['phone']);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    die('Invalid email format');
}

$message = isset($_POST['message']) ? htmlspecialchars($_POST['message']) : '';

$data = '<table style="width:100%; border: 1px solid black; border-collapse: collapse;">';
foreach ($_POST as $key => $value) {
    $_key = ucwords(str_replace('_', ' ', $key));
    
    if ($key == 'services') {
        $value = implode(', ', $value);  // Convert array to a comma-separated string
    }

    $data .= '<tr><td style="border: 1px solid black; border-collapse: collapse; padding: 15px; text-align: left; font-size:15px; font-weight: 500;">' . $_key . '</td><td style="border: 1px solid black; border-collapse: collapse; padding: 15px; text-align: left; font-size:15px">' . htmlspecialchars($value) . '</td></tr>';
}
$data .= '</table>';

// Email headers
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

$mailSent = mail("info@brandname.com", $subject, $data, $headers);

if ($mailSent) {
    header('Location: thank-you.php');
    exit();
} else {
    header('Location: error.php');
    exit();
}
?>