<?php
// process_contact.php
// Handles the submission of the contact form.

session_start();
require_once 'config.php';
require_once 'includes/auth.php'; // For set_message function
require_once 'classes/Contactus.php';

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

    if (empty($name) || empty($message)) {
        set_message('Please fill in all required fields (Name and Message).', 'danger');
        header('Location: index.php?page=contact');
        exit();
    }

    if (!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        set_message('Invalid email format.', 'danger');
        header('Location: index.php?page=contact');
        exit();
    }

    $contactUs = new Contactus($pdo);

    try {
        $contactUs->submitFeedback($name, $email, $message, $client_ip);
        set_message('Your message has been sent successfully! We will get back to you soon.', 'success');
    } catch (Exception $e) {
        set_message('Failed to send your message: ' . $e->getMessage(), 'danger');
    }

    header('Location: index.php?page=contact');
    exit();
} else {
    // If accessed directly without POST, redirect to contact page
    header('Location: index.php?page=contact');
    exit();
}
