| <?php |
| |
| 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'); |
|
|
| |
| $subscriptionsFile = '../models/Subscription.php'; |
|
|
| |
| if (!file_exists($subscriptionsFile)) { |
| file_put_contents($subscriptionsFile, json_encode([])); |
| } |
|
|
| |
| $email = $_POST['email'] ?? ''; |
| $notification_opt_in = isset($_POST['notification_opt_in']) ? (bool)$_POST['notification_opt_in'] : false; |
|
|
| |
| if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) { |
| http_response_code(400); |
| echo json_encode(['message' => 'Please provide a valid email address.']); |
| exit; |
| } |
|
|
| |
| $subscriptions = json_decode(file_get_contents($subscriptionsFile), true); |
|
|
| |
| foreach ($subscriptions as $sub) { |
| if ($sub['email'] === $email) { |
| http_response_code(409); |
| echo json_encode(['message' => 'This email is already subscribed.']); |
| exit; |
| } |
| } |
|
|
| |
| $newSubscription = [ |
| 'email' => $email, |
| 'notification_opt_in' => $notification_opt_in, |
| 'subscribed_at' => date('Y-m-d H:i:s'), |
| 'active' => true |
| ]; |
|
|
| $subscriptions[] = $newSubscription; |
|
|
| |
| 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; |
| ?> |