<?php
// contact_us.php
header('Content-Type: application/json');
include_once('../../includes/db.php');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => false, 'message' => 'Invalid request method.']);
    exit;
}

$name = trim($_POST['name'] ?? '');
$email = trim($_POST['email'] ?? '');
$message = trim($_POST['message'] ?? '');

if (!$name || !$email || !$message) {
    echo json_encode(['status' => false, 'message' => 'All fields are required.']);
    exit;
}

// Insert into DB
$inserted = execute("INSERT INTO contact_messages (name, email, message) VALUES (?, ?, ?)", [$name, $email, $message]);

// Send email (basic mail function)
$to = "admin@yourdomain.com"; // Replace with your admin email
$subject = "New Contact Message from $name";
$body = "Name: $name\nEmail: $email\nMessage:\n$message";
$headers = "From: $email";
@mail($to, $subject, $body, $headers);

if ($inserted) {
    echo json_encode(['status' => true, 'message' => 'Message submitted successfully.']);
} else {
    echo json_encode(['status' => false, 'message' => 'Failed to submit message.']);
}
