<?php
/**
 * Tom's Java Jive - Newsletter Subscribe API
 */

require_once __DIR__ . '/../includes/functions.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(['error' => 'Method not allowed'], 405);
}

$input = json_decode(file_get_contents('php://input'), true);
$email = trim($input['email'] ?? $_POST['email'] ?? '');

if (empty($email)) {
    jsonResponse(['error' => 'Email is required'], 400);
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    jsonResponse(['error' => 'Please enter a valid email address'], 400);
}

// Check if already subscribed
$existing = db()->fetch(
    "SELECT id FROM email_subscribers WHERE email = :email",
    ['email' => strtolower($email)]
);

if ($existing) {
    jsonResponse(['error' => 'This email is already subscribed'], 400);
}

// Add subscriber
try {
    db()->insert('email_subscribers', [
        'email' => strtolower($email),
        'source' => 'website',
        'is_active' => 1
    ]);
    
    // Send welcome email
    $html = <<<HTML
    <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
        <div style="background: #8B4513; color: white; padding: 20px; text-align: center;">
            <h1 style="margin: 0;">Tom's Java Jive</h1>
        </div>
        <div style="padding: 30px; background: #FDFBF7;">
            <h2>Welcome to the Java Jive Family!</h2>
            <p>Thanks for subscribing to our newsletter. You'll be the first to know about:</p>
            <ul>
                <li>New coffee releases</li>
                <li>Exclusive discounts and promotions</li>
                <li>Brewing tips and recipes</li>
                <li>Behind-the-scenes at our roastery</li>
            </ul>
            <p>As a thank you, enjoy <strong>10% off</strong> your first order with code: <strong>WELCOME10</strong></p>
            <p style="text-align: center; margin-top: 20px;">
                <a href="https://tomsjavajive.com/shop.php" style="background: #E86A33; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px;">Shop Now</a>
            </p>
        </div>
        <div style="padding: 20px; text-align: center; color: #666; font-size: 12px;">
            <p>Tom's Java Jive | Premium Coffee</p>
        </div>
    </div>
    HTML;
    
    sendEmail($email, 'Welcome to Tom\'s Java Jive!', $html);
    
    jsonResponse(['success' => true, 'message' => 'Successfully subscribed!']);
    
} catch (Exception $e) {
    jsonResponse(['error' => 'Subscription failed. Please try again.'], 500);
}
