<?php
session_start();
require_once 'database.php';
require_once 'functions.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = sanitize_input($_POST['email'] ?? '');
    
    if (empty($email) || !validate_email($email)) {
        set_flash_message('Please provide a valid email address.', 'danger');
    } else {
        if (subscribe_newsletter($pdo, $email)) {
            set_flash_message('Thank you for subscribing! You will receive updates about PrismaOS development.', 'success');
        } else {
            // Check if email already exists
            $stmt = $pdo->prepare("SELECT id FROM newsletter_subscriptions WHERE email = :email");
            $stmt->execute([':email' => $email]);
            
            if ($stmt->fetch()) {
                set_flash_message('This email is already subscribed to our newsletter.', 'info');
            } else {
                set_flash_message('Sorry, there was an error processing your subscription. Please try again.', 'danger');
            }
        }
    }
}

// Redirect back to the referring page or home
$redirect_to = $_SERVER['HTTP_REFERER'] ?? 'index.php';
header('Location: ' . $redirect_to);
exit;
?>