<?php
session_start();
require_once "db.php"; // Ensure db.php correctly sets up $conn as PDO

// Only process POST requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // Sanitize inputs
    $name    = trim($_POST['name'] ?? '');
    $email   = trim($_POST['email'] ?? '');
    $subject = trim($_POST['subject'] ?? '');
    $message = trim($_POST['message'] ?? '');

    // Basic validation
    $errors = [];
    if (empty($name))    $errors[] = "Name is required.";
    if (empty($email))   $errors[] = "Email is required.";
    elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Invalid email format.";
    if (empty($subject)) $errors[] = "Subject is required.";
    if (empty($message)) $errors[] = "Message cannot be empty.";

    // If errors exist, redirect back with error messages
    if (!empty($errors)) {
        $_SESSION['contact_error'] = implode(" ", $errors);
        header("Location: contactus.php");
        exit();
    }

    try {
        // Insert message into contact_messages table
        $stmt = $conn->prepare("
            INSERT INTO contact_messages (name, email, subject, message, status) 
            VALUES (:name, :email, :subject, :message, 'unread')
        ");
        $stmt->execute([
            ':name'    => $name,
            ':email'   => $email,
            ':subject' => $subject,
            ':message' => $message
        ]);

        $_SESSION['contact_success'] = "Your message has been sent successfully!";
    } catch (PDOException $e) {
        // Log error for debugging; do not expose to users
        error_log("Contact form DB error: " . $e->getMessage());
        $_SESSION['contact_error'] = "Failed to send message. Please try again later.";
    }

    header("Location: contactus.php");
    exit();
} else {
    // Redirect GET requests to contact page
    header("Location: contactus.php");
    exit();
}
?>
