<?php
/**
 * Contact Form Endpoint
 */

$db = Database::getInstance()->getConnection();

if ($method === 'POST') {
    $input = getJsonInput();

    $errors = validateRequired($input, ['name', 'email', 'message']);
    if (!empty($errors)) {
        jsonResponse(['error' => implode(', ', $errors)], 400);
    }

    if (!isValidEmail($input['email'])) {
        jsonResponse(['error' => 'Invalid email address'], 400);
    }

    $name    = sanitizeString($input['name']);
    $email   = sanitizeString($input['email']);
    $message = $input['message'];
    $id      = generateUuid();

    $stmt = $db->prepare("
        INSERT INTO contacts (id, name, email, message, created_at)
        VALUES (?, ?, ?, ?, NOW())
    ");
    $stmt->execute([$id, $name, $email, $message]);

    // Send admin alert and customer confirmation via SendGrid
    sendContactAlert($name, $email, $message);
    sendContactConfirmation($email, $name);

    jsonResponse(['message' => 'Contact form submitted successfully']);
}

jsonResponse(['error' => 'Method not allowed'], 405);
