fellybikush's picture
Upload 99 files
0dff816 verified
raw
history blame
1.99 kB
<?php
// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Access-Control-Allow-Headers, Content-Type, Access-Control-Allow-Methods, Authorization, X-Requested-With');
// Simulate database connection (replace with your actual database code)
$subscriptionsFile = '../models/Subscription.php';
// Initialize subscriptions file if it doesn't exist
if (!file_exists($subscriptionsFile)) {
file_put_contents($subscriptionsFile, json_encode([]));
}
// Get POST data
$email = $_POST['email'] ?? '';
$notification_opt_in = isset($_POST['notification_opt_in']) ? (bool)$_POST['notification_opt_in'] : false;
// Validate email
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
http_response_code(400);
echo json_encode(['message' => 'Please provide a valid email address.']);
exit;
}
// Read existing subscriptions
$subscriptions = json_decode(file_get_contents($subscriptionsFile), true);
// Check if email already exists
foreach ($subscriptions as $sub) {
if ($sub['email'] === $email) {
http_response_code(409);
echo json_encode(['message' => 'This email is already subscribed.']);
exit;
}
}
// Add new subscription
$newSubscription = [
'email' => $email,
'notification_opt_in' => $notification_opt_in,
'subscribed_at' => date('Y-m-d H:i:s'),
'active' => true
];
$subscriptions[] = $newSubscription;
// Save subscriptions
if (file_put_contents($subscriptionsFile, json_encode($subscriptions, JSON_PRETTY_PRINT))) {
http_response_code(200);
echo json_encode(['message' => 'Successfully subscribed to our newsletter!']);
} else {
http_response_code(500);
echo json_encode(['message' => 'Subscription failed. Please try again.']);
}
exit;
?>