<?php
session_start();
include 'config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

// Get form data
$name = isset($_POST['contact-name']) ? trim($_POST['contact-name']) : '';
$email = isset($_POST['contact-email']) ? trim($_POST['contact-email']) : '';
$phone = isset($_POST['contact-phone']) ? trim($_POST['contact-phone']) : '';
$subject = isset($_POST['contact-subject']) ? trim($_POST['contact-subject']) : '';
$message = isset($_POST['contact-message']) ? trim($_POST['contact-message']) : '';

error_log("Contact form received - Name: $name, Email: $email, Phone: $phone, Subject: $subject");

// Validate required fields
if (empty($name) || empty($email) || empty($phone) || empty($subject) || empty($message)) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'All fields are required']);
    exit;
}

// Validate email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Invalid email format']);
    exit;
}

// Validate phone
if (!preg_match('/^[0-9+\-\s()]+$/', $phone) || strlen(preg_replace('/[^0-9]/', '', $phone)) < 10) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Invalid phone number']);
    exit;
}

// Prepare and execute SQL statement
$stmt = $conn->prepare("INSERT INTO contacts (name, email, phone, subject, message, status) VALUES (?, ?, ?, ?, ?, 'new')");

if (!$stmt) {
    error_log("Prepare failed: " . $conn->error);
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Database error']);
    exit;
}

$stmt->bind_param('sssss', $name, $email, $phone, $subject, $message);

if ($stmt->execute()) {
    $contactId = $conn->insert_id;
    
    error_log("Contact message saved successfully with ID: " . $contactId);
    
    header('Content-Type: application/json');
    echo json_encode([
        'success' => true,
        'message' => 'Thank you for contacting us! We will get back to you soon.',
        'contact_id' => $contactId
    ]);
} else {
    error_log("Execute failed: " . $stmt->error);
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Error saving contact information: ' . $stmt->error]);
}

$stmt->close();
$conn->close();
?>
