<?php
require_once __DIR__ . '/db/config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $message = trim($_POST['message']);

    if (empty($name) || empty($email) || empty($message) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        // Handle validation error
        header('Location: index.php?status=error');
        exit;
    }

    try {
        $pdo = db();
        $sql = "INSERT INTO contact_messages (name, email, message) VALUES (?, ?, ?)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$name, $email, $message]);

        // Redirect with success status
        header('Location: index.php?status=success#contact');
        exit;
    } catch (PDOException $e) {
        // Handle DB error
        header('Location: index.php?status=dberror');
        exit;
    }
}
