<?php
/**
 * Newsletter Subscription Handler
 */
require_once 'config.php';

$email = sanitize($_POST['email'] ?? '');

if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    redirect(BASE_URL, 'error', 'Please provide a valid email address');
}

try {
    // Check if email already exists
    $check = db()->prepare("SELECT id, status FROM newsletter_subscribers WHERE email = ?");
    $check->execute([$email]);
    $existing = $check->fetch();
    
    if ($existing) {
        if ($existing['status'] === 'active') {
            redirect(BASE_URL, 'info', 'You are already subscribed to our newsletter!');
        } else {
            // Reactivate subscription
            $update = db()->prepare("UPDATE newsletter_subscribers SET status = 'active', unsubscribed_at = NULL, updated_at = NOW() WHERE id = ?");
            $update->execute([$existing['id']]);
            redirect(BASE_URL, 'success', 'Welcome back! Your newsletter subscription has been reactivated.');
        }
    }
    
    // Add new subscriber
    $stmt = db()->prepare("INSERT INTO newsletter_subscribers (email, status, source, ip_address, created_at) VALUES (?, 'active', 'website', ?, NOW())");
    $stmt->execute([$email, $_SERVER['REMOTE_ADDR'] ?? null]);
    
    redirect(BASE_URL, 'success', 'Thank you for subscribing to our newsletter!');
} catch (PDOException $e) {
    error_log("Newsletter subscription error: " . $e->getMessage());
    redirect(BASE_URL, 'error', 'Something went wrong. Please try again later.');
}
