<?php
include 'admin/connection.php';

if (isset($_POST["submit"])) {

    $name    = trim($_POST["name"]);
    $email   = trim($_POST["email"]);
    $phone   = trim($_POST["phone"]);
    $subject = trim($_POST["subject"]);
    $message = trim($_POST["message"]);

    // Insert into database
    $stmt = $conn->prepare("INSERT INTO contact_enquiries (name, email, phone, subject, message, status) VALUES (?, ?, ?, ?, ?, 'pending')");
    $stmt->bind_param("sssss", $name, $email, $phone, $subject, $message);

    if ($stmt->execute()) {

        $to = "madhusmitap875@gmail.com";
        $mail_subject = "New Contact Enquiry - " . $subject;

        $mail_message  = "<h3>New Contact Form Submission</h3>";
        $mail_message .= "<p><strong>Name:</strong> $name</p>";
        $mail_message .= "<p><strong>Email:</strong> $email</p>";
        $mail_message .= "<p><strong>Phone:</strong> $phone</p>";
        $mail_message .= "<p><strong>Subject:</strong> $subject</p>";
        $mail_message .= "<p><strong>Message:</strong><br>$message</p>";

        $headers  = "MIME-Version: 1.0\r\n";
        $headers .= "Content-type:text/html;charset=UTF-8\r\n";
        $headers .= "From: $name <$email>\r\n";

        if (mail($to, $mail_subject, $mail_message, $headers)) {

            $conn->query("UPDATE contact_enquiries SET status='sent' WHERE id=" . $stmt->insert_id);

            echo "<script>
                alert('Thank you! Your enquiry has been submitted successfully.');
                window.location.href='contact.php';
            </script>";
        } else {

            echo "<script>
                alert('Mail not sent, but enquiry saved successfully.');
                window.location.href='contact.php';
            </script>";
        }
    } else {

        echo "<script>
            alert('Database error. Please try again.');
            window.location.href='contact.php';
        </script>";
    }

    $stmt->close();
    $conn->close();
} else {
    header("Location: contact.php");
    exit();
}
