<?php
/**
 * Newsletter Subscription Handler
 * Works on both localhost and cPanel
 */

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

// Load database helper
require_once __DIR__ . '/config/database_helper.php';

// Get data directory
$dataDir = DatabaseHelper::getDataDirectory();
$newsletterFile = DatabaseHelper::getJsonFilePath('newsletter_subscribers.json');

// Load existing subscribers
$subscribers = DatabaseHelper::loadJson('newsletter_subscribers.json');

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['email'])) {
    $email = filter_var(trim($_POST['email']), FILTER_SANITIZE_EMAIL);
    
    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        // Check if already subscribed
        $exists = false;
        foreach ($subscribers as $sub) {
            if ($sub['email'] === $email) {
                $exists = true;
                break;
            }
        }
        
        if ($exists) {
            echo json_encode(['success' => false, 'message' => 'This email is already subscribed!']);
            exit;
        }
        
        // Add new subscriber
        $subscribers[] = [
            'email' => $email,
            'subscribed_date' => date('Y-m-d H:i:s'),
            'ip_address' => $_SERVER['REMOTE_ADDR']
        ];
        
        // Save subscribers using database helper
        if (DatabaseHelper::saveJson('newsletter_subscribers.json', $subscribers)) {
            echo json_encode(['success' => true, 'message' => 'Successfully subscribed!']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Error saving subscription.']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid email address!']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'No email provided.']);
}
?>
