<?php
require_once '../inc/dbconn.php';

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

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

$email = filter_var($_POST['email'] ?? '', FILTER_VALIDATE_EMAIL);
if (!$email) {
    echo json_encode(['success' => false, 'message' => 'Please enter a valid email address']);
    exit;
}

try {
    // Check if email already exists
    $checkSql = "SELECT id, status FROM newsletter_subscribers WHERE email = :email";
    $checkStmt = $pdo->prepare($checkSql);
    $checkStmt->execute([':email' => $email]);
    $existing = $checkStmt->fetch(PDO::FETCH_ASSOC);
    
    if ($existing) {
        if ($existing['status'] === 'unsubscribed') {
            // Reactivate unsubscribed user
            $updateSql = "UPDATE newsletter_subscribers 
                         SET status = 'active', 
                             unsubscribed_at = NULL,
                             updated_at = NOW() 
                         WHERE id = :id";
            $updateStmt = $pdo->prepare($updateSql);
            $updateStmt->execute([':id' => $existing['id']]);
            
            echo json_encode([
                'success' => true, 
                'message' => 'Welcome back! You have been re-subscribed to our newsletter.'
            ]);
        } else {
            echo json_encode([
                'success' => false, 
                'message' => 'This email is already subscribed to our newsletter.'
            ]);
        }
        exit;
    }
    
    // Generate discount code
    $discountCode = 'NEWS' . strtoupper(substr(md5(uniqid()), 0, 6));
    
    // Insert new subscriber
    $sql = "INSERT INTO newsletter_subscribers 
            (email, discount_code, status, subscribed_at, ip_address, user_agent) 
            VALUES (:email, :discount_code, 'active', NOW(), :ip_address, :user_agent)";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':email' => $email,
        ':discount_code' => $discountCode,
        ':ip_address' => $_SERVER['REMOTE_ADDR'] ?? '',
        ':user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? ''
    ]);
    
    // Send welcome email (you can implement this function)
    // sendWelcomeEmail($email, $discountCode);
    
    echo json_encode([
        'success' => true, 
        'message' => 'Thank you for subscribing! Check your email for a special discount code.',
        'discount_code' => $discountCode
    ]);
    
} catch(PDOException $e) {
    error_log("Newsletter subscription error: " . $e->getMessage());
    echo json_encode([
        'success' => false, 
        'message' => 'An error occurred. Please try again later.'
    ]);
}
?>