<?php
/**
 * Newsletter Subscription Endpoint
 */

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

if ($method === 'POST' && $id === 'subscribe') {
    $input = getJsonInput();
    
    if (!isset($input['email']) || !isValidEmail($input['email'])) {
        jsonResponse(['error' => 'Valid email address is required'], 400);
    }
    
    $email = sanitizeString($input['email']);
    
    // Check if already subscribed
    $stmt = $db->prepare("SELECT id FROM newsletter_subscribers WHERE email = ?");
    $stmt->execute([$email]);
    
    if ($stmt->fetch()) {
        jsonResponse(['message' => 'Email already subscribed']);
    }
    
    $id = generateUuid();
    
    $stmt = $db->prepare("
        INSERT INTO newsletter_subscribers (id, email, subscribed_at)
        VALUES (?, ?, NOW())
    ");
    
    $stmt->execute([$id, $email]);
    
    jsonResponse(['message' => 'Successfully subscribed to newsletter']);
}

jsonResponse(['error' => 'Invalid newsletter endpoint'], 404);
