<?php 
/**
 * Modern Newsletter Subscription API
 * JSON endpoint for footer newsletter
 */

require 'core.php';

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

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

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);
$email = isset($input['email']) ? filter_var(strtolower(trim($input['email'])), FILTER_SANITIZE_EMAIL) : '';

// Validate email
if (empty($email)) {
    echo json_encode([
        'success' => false, 
        'message' => isset($translation['tr_158']) ? $translation['tr_158'] : 'Please enter your email address'
    ]);
    exit();
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode([
        'success' => false, 
        'message' => isset($translation['tr_163']) ? $translation['tr_163'] : 'Please enter a valid email address'
    ]);
    exit();
}

try {
    // Check if email already exists
    $statement = $connect->prepare("SELECT * FROM subscribers WHERE subscriber_email = :subscriber_email LIMIT 1");
    $statement->execute([':subscriber_email' => $email]);
    $result = $statement->fetch();
    
    if ($result) {
        // Already subscribed
        echo json_encode([
            'success' => true, 
            'message' => isset($translation['tr_189']) ? $translation['tr_189'] : 'You are already subscribed to our newsletter!'
        ]);
    } else {
        // Insert new subscriber
        $statement = $connect->prepare("INSERT INTO subscribers (subscriber_id, subscriber_email, subscriber_date) VALUES (null, :subscriber_email, CURRENT_TIME)");
        $statement->execute([':subscriber_email' => $email]);
        
        echo json_encode([
            'success' => true, 
            'message' => isset($translation['tr_189']) ? $translation['tr_189'] : 'Thank you for subscribing! Check your inbox for exclusive deals.'
        ]);
    }
} catch (Exception $e) {
    error_log('Newsletter subscription error: ' . $e->getMessage());
    echo json_encode([
        'success' => false, 
        'message' => 'An error occurred. Please try again later.'
    ]);
}
?>
