<?php
// Enable error reporting for debugging (remove in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Set headers to prevent caching
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");

// Validate request method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    die(json_encode(['success' => false, 'message' => 'Method not allowed']));
}

// Get and sanitize form data
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$subject = filter_input(INPUT_POST, 'subject', FILTER_SANITIZE_STRING);
$message = filter_input(INPUT_POST, 'message', FILTER_SANITIZE_STRING);

// Validate inputs
$errors = [];

// Name validation (2-50 characters)
if (empty($name) || strlen($name) < 2 || strlen($name) > 50) {
    $errors['name'] = 'Please enter a valid name (2-50 characters)';
}

// Email validation
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors['email'] = 'Please enter a valid email address';
}

// Subject validation (optional, but if provided, validate)
if (!empty($subject) && (strlen($subject) < 3 || strlen($subject) > 100)) {
    $errors['subject'] = 'Subject must be between 3-100 characters';
}

// Message validation (10-2000 characters)
if (empty($message) || strlen($message) < 10 || strlen($message) > 2000) {
    $errors['message'] = 'Message must be between 10-2000 characters';
}

// Check for errors
if (!empty($errors)) {
    http_response_code(400);
    die(json_encode(['success' => false, 'errors' => $errors]));
}

// Email configuration
$to = 'mohamedouldethman@gmail.com'; // Replace with your email
$subject = $subject ?: 'New Contact Form Submission';
$headers = [
    'From' => $email,
    'Reply-To' => $email,
    'X-Mailer' => 'PHP/' . phpversion(),
    'Content-Type' => 'text/plain; charset=UTF-8'
];

// Build email body
$emailBody = "You have received a new message from your website contact form.\n\n";
$emailBody .= "Name: $name\n";
$emailBody .= "Email: $email\n\n";
$emailBody .= "Message:\n$message\n";

// Additional security headers for email
$headersString = '';
foreach ($headers as $key => $value) {
    $headersString .= "$key: $value\r\n";
}

// Send email
$mailSent = mail($to, $subject, $emailBody, $headersString);

if ($mailSent) {
    // Log the successful submission (optional)
    $logMessage = date('[Y-m-d H:i:s]') . " - Message from $name ($email) successfully sent\n";
    file_put_contents('contact_log.txt', $logMessage, FILE_APPEND);
    
    // Return success response
    die(json_encode([
        'success' => true,
        'message' => 'Thank you! Your message has been sent successfully.'
    ]));
} else {
    // Log the error (optional)
    $errorLog = date('[Y-m-d H:i:s]') . " - Failed to send message from $name ($email)\n";
    file_put_contents('contact_errors.txt', $errorLog, FILE_APPEND);
    
    http_response_code(500);
    die(json_encode([
        'success' => false,
        'message' => 'Sorry, there was an error sending your message. Please try again later.'
    ]));
}
?>