<?php
/**
 * Contact Form Handler
 * Save contact messages to database
 */

header('Content-Type: application/json');
require_once __DIR__ . '/../config/database.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit();
}

$response = ['success' => false, 'message' => ''];

try {
    // Get POST data
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $subject = trim($_POST['subject'] ?? '');
    $message = trim($_POST['message'] ?? '');

    // Validation
    if (empty($name)) {
        throw new Exception('Name is required');
    }
    
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        throw new Exception('Valid email address is required');
    }
    
    if (empty($subject)) {
        throw new Exception('Subject is required');
    }
    
    if (empty($message)) {
        throw new Exception('Message is required');
    }

    // Insert contact message
    $sql = "INSERT INTO contact_messages (name, email, phone, subject, message, status) 
            VALUES (?, ?, ?, ?, ?, 'new')";
    $stmt = $conn->prepare($sql);
    
    if (!$stmt) {
        throw new Exception('Database error: ' . $conn->error);
    }

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

    if ($stmt->execute()) {
        $response['success'] = true;
        $response['message'] = 'Thank you! Your message has been sent. We will contact you soon.';
        
        // Send confirmation email (optional)
        // mail($email, 'Message Received - Zemaraim Hotel', 'Thank you for contacting us...');
    } else {
        throw new Exception('Failed to send message. Please try again.');
    }

} catch (Exception $e) {
    http_response_code(400);
    $response['message'] = $e->getMessage();
}

echo json_encode($response);
$conn->close();
?>
