<?php
// contact_process.php
include('db/connection.php');

// Set headers for JSON response
header('Content-Type: application/json');

// Initialize response array
$response = [
    'success' => false,
    'message' => '',
    'errors' => []
];

// Check if it's a POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $response['message'] = 'Invalid request method';
    echo json_encode($response);
    exit;
}

// Get and sanitize POST data
$name = mysqli_real_escape_string($conn, trim($_POST['name'] ?? ''));
$email = mysqli_real_escape_string($conn, trim($_POST['email'] ?? ''));
$subject = mysqli_real_escape_string($conn, trim($_POST['subject'] ?? ''));
$message = mysqli_real_escape_string($conn, trim($_POST['message'] ?? ''));

// Validation
$errors = [];

if (empty($name)) {
    $errors['name'] = 'Name is required';
} elseif (strlen($name) < 2) {
    $errors['name'] = 'Name must be at least 2 characters';
}

if (empty($email)) {
    $errors['email'] = 'Email is required';
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors['email'] = 'Invalid email format';
}

if (empty($subject)) {
    $errors['subject'] = 'Subject is required';
} elseif (strlen($subject) < 3) {
    $errors['subject'] = 'Subject must be at least 3 characters';
}

if (empty($message)) {
    $errors['message'] = 'Message is required';
} elseif (strlen($message) < 10) {
    $errors['message'] = 'Message must be at least 10 characters';
}

// If there are errors, return them
if (!empty($errors)) {
    $response['errors'] = $errors;
    $response['message'] = 'Please fix the errors below';
    echo json_encode($response);
    exit;
}

// Get user IP and user agent
$ip_address = $_SERVER['REMOTE_ADDR'] ?? '';
$user_agent = mysqli_real_escape_string($conn, $_SERVER['HTTP_USER_AGENT'] ?? '');

// Insert into database
$sql = "INSERT INTO contact_messages (name, email, subject, message, ip_address, user_agent) 
        VALUES ('$name', '$email', '$subject', '$message', '$ip_address', '$user_agent')";

if (mysqli_query($conn, $sql)) {
    // Send email notification (optional)
    $to = "sdbinnovation@mail.com"; // Change to your email
    $email_subject = "New Contact Form Message: $subject";
    $email_body = "You have received a new message from the contact form.\n\n";
    $email_body .= "Name: $name\n";
    $email_body .= "Email: $email\n";
    $email_body .= "Subject: $subject\n";
    $email_body .= "Message:\n$message\n";
    $email_body .= "\nIP Address: $ip_address\n";
    
    $headers = "From: $email\r\n";
    $headers .= "Reply-To: $email\r\n";
    
    // Uncomment below to enable email
    // mail($to, $email_subject, $email_body, $headers);
    
    $response['success'] = true;
    $response['message'] = 'Thank you! Your message has been sent successfully.';
} else {
    $response['message'] = 'Database error: ' . mysqli_error($conn);
}

echo json_encode($response);
exit;
?>