<?php
/**
 * Contact Form Submission Handler
 * Works on both localhost and cPanel
 */

header('Content-Type: application/json');

// Load database helper
require_once __DIR__ . '/config/database_helper.php';

// Load existing messages
$messages = DatabaseHelper::loadJson('contact_messages.json');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = filter_var(trim($_POST['name'] ?? ''), FILTER_SANITIZE_STRING);
    $email = filter_var(trim($_POST['email'] ?? ''), FILTER_SANITIZE_EMAIL);
    $subject = filter_var(trim($_POST['subject'] ?? ''), FILTER_SANITIZE_STRING);
    $message = filter_var(trim($_POST['message'] ?? ''), FILTER_SANITIZE_STRING);
    
    // Validate inputs
    if (empty($name) || empty($email) || empty($subject) || empty($message)) {
        echo json_encode(['success' => false, 'message' => 'All fields are required!']);
        exit;
    }
    
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo json_encode(['success' => false, 'message' => 'Invalid email address!']);
        exit;
    }
    
    // Add new message
    $messages[] = [
        'name' => $name,
        'email' => $email,
        'subject' => $subject,
        'message' => $message,
        'submitted_date' => date('Y-m-d H:i:s'),
        'ip_address' => $_SERVER['REMOTE_ADDR'],
        'status' => 'new'
    ];
    
    // Save message using database helper
    if (DatabaseHelper::saveJson('contact_messages.json', $messages)) {
        echo json_encode(['success' => true, 'message' => 'Message sent successfully! We\'ll get back to you soon.']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error saving message.']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request.']);
}
?>
