<?php
/**
 * Newsletter Subscription API
 * Digital Marketplace
 */

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

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_response(['success' => false, 'message' => 'Invalid request method']);
}

$email = sanitize_email($_POST['email'] ?? '');
$name = sanitize($_POST['name'] ?? '');
$source = sanitize($_POST['source'] ?? 'website');

if (empty($email)) {
    json_response(['success' => false, 'message' => 'Email address is required']);
}

if (!validate_email($email)) {
    json_response(['success' => false, 'message' => 'Please enter a valid email address']);
}

// Check if already subscribed
$stmt = $pdo->prepare("SELECT id, is_active FROM subscribers WHERE email = ?");
$stmt->execute([$email]);
$existing = $stmt->fetch();

if ($existing) {
    if ($existing['is_active']) {
        json_response(['success' => false, 'message' => 'You are already subscribed to our newsletter!']);
    } else {
        // Reactivate subscription
        $stmt = $pdo->prepare("UPDATE subscribers SET is_active = 1, name = ?, source = ?, updated_at = NOW() WHERE id = ?");
        $stmt->execute([$name, $source, $existing['id']]);
        
        json_response(['success' => true, 'message' => 'Welcome back! Your subscription has been reactivated.']);
    }
} else {
    // New subscription
    if (subscribe_newsletter($email, $name, $source)) {
        // Send welcome email
        $template = get_email_template('newsletter_welcome');
        if ($template) {
            $variables = [
                'name' => $name ?: 'Subscriber',
                'email' => $email,
                'site_name' => get_setting('site_name', 'Digital Marketplace'),
                'unsubscribe_url' => BASE_URL . '/api/unsubscribe.php?email=' . urlencode($email)
            ];
            send_template_email('newsletter_welcome', $email, $variables);
        }
        
        json_response(['success' => true, 'message' => 'Thank you for subscribing! Check your email for a welcome message.']);
    } else {
        json_response(['success' => false, 'message' => 'Failed to subscribe. Please try again.']);
    }
}
