<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

// Only allow POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['submit'])) {
    die("Invalid form submission.");
}

$db_server   = "localhost";
$db_username = "thevault_landing";
$db_password = "";
$db_name     = "thevault_landing";

$conn = new mysqli(
    $db_server,
    $db_username,
    $db_password,
    $db_name
);

if ($conn->connect_error) {
    die("Database connection failed: " . $conn->connect_error);
}

$conn->set_charset("utf8mb4");


$fname         = trim($_POST['fname'] ?? '');
$phone         = trim($_POST['phone'] ?? '');
$email         = trim($_POST['email'] ?? '');

$errors = [];

if ($fname === '') {
    $errors[] = "Full Name is required.";
}

if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors[] = "Valid Email Address is required.";
}



// Show validation errors
if (!empty($errors)) {
    echo implode("<br>", $errors);
    exit;
}

$sql = "INSERT INTO `corporate_proposal`
        (`full_name`,`phone`,`email`)
        VALUES (?, ?, ?, ?, ?, ?, ?)";

$stmt = $conn->prepare($sql);

if (!$stmt) {
    die("Prepare failed: " . $conn->error);
}

$stmt->bind_param(
    "sssssss",
    $fname,$organisation,$email,$phone,$date,$event_type,$message
);

if (!$stmt->execute()) {
    die("Database Insert Error: " . $stmt->error);
}


// =========================
// SEND EMAIL
// =========================

$to = "info@thevaultstorage.ae";

$subject = "New Corporate Proposal";

$email_body  = "New Corporate Proposal\n\n";
$email_body .= "Name: " . $fname . "\n";
$email_body .= "Phone Number: " . $phone . "\n";
$email_body .= "Email Address: " . $email . "\n";


// Website domain
$domain = $_SERVER['HTTP_HOST'];

$headers  = "From: noreply@" . $domain . "\r\n";
$headers .= "Reply-To: " . $email . "\r\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\r\n";


// Send email
mail(
    $to,
    $subject,
    $email_body,
    $headers
);

$stmt->close();
$conn->close();

header("Location: thank-you.html");
exit;

?>