<?php
// newsletter_subscribe.php

// Start session and include database
session_start();
require_once 'database.php';

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

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

// Validate CSRF token


// Get and validate email
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);

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

try {
    // Instantiate database
    $database = new Database();
    
    // Check if email already exists
    $result = $database->Newsletter_Insert($email);
    
    if ($result === true) {
        // Successfully inserted
        echo json_encode([
            'success' => true, 
            'message' => 'Thank you for subscribing to our newsletter!'
        ]);
        
        // Log activity
        $database->log_activity('newsletter_subscribe', "New subscriber: $email");
        
    } elseif ($result === "exists") {
        // Already subscribed
        echo json_encode([
            'success' => false, 
            'message' => 'This email is already subscribed to our newsletter.'
        ]);
    } else {
        // Database error
        echo json_encode([
            'success' => false, 
            'message' => 'An error occurred. Please try again later.'
        ]);
    }
    
} catch (Exception $e) {
    error_log("Newsletter subscription error: " . $e->getMessage());
    echo json_encode([
        'success' => false, 
        'message' => 'An unexpected error occurred. Please try again later.'
    ]);
}
?>