<?php
/**
 * Newsletter Subscribe Handler
 * Digital Product Store
 */

require_once __DIR__ . '/config/database.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = sanitize_email($_POST['email'] ?? '');
    
    if (!empty($email) && is_valid_email($email)) {
        try {
            // Check if already subscribed
            $stmt = $pdo->prepare("SELECT id FROM subscribers WHERE email = ?");
            $stmt->execute([$email]);
            
            if ($stmt->fetch()) {
                set_flash_message('You are already subscribed!', 'info');
            } else {
                // Add subscriber
                $stmt = $pdo->prepare("INSERT INTO subscribers (email, is_active, subscribed_at, created_at) VALUES (?, 1, NOW(), NOW())");
                $stmt->execute([$email]);
                
                set_flash_message('Thank you for subscribing!', 'success');
            }
        } catch (PDOException $e) {
            set_flash_message('Subscription failed. Please try again.', 'error');
        }
    } else {
        set_flash_message('Please enter a valid email address.', 'error');
    }
}

header('Location: ' . BASE_URL . '/');
exit;
