34 lines
1.0 KiB
PHP
34 lines
1.0 KiB
PHP
<?php
|
|
|
|
namespace App\Controllers;
|
|
|
|
use App\Core\Controller;
|
|
|
|
class NewsletterController extends Controller {
|
|
|
|
public function subscribe() {
|
|
header('Content-Type: application/json');
|
|
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
$email = $input['email'] ?? '';
|
|
|
|
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
|
echo json_encode(['error' => 'Please provide a valid email address.']);
|
|
return;
|
|
}
|
|
|
|
$db = db_pdo();
|
|
try {
|
|
$stmt = $db->prepare("INSERT INTO newsletter_subscribers (email) VALUES (?)");
|
|
$stmt->execute([$email]);
|
|
echo json_encode(['success' => 'Thank you for subscribing!']);
|
|
} catch (\PDOException $e) {
|
|
if ($e->getCode() == 23000) { // Duplicate entry
|
|
echo json_encode(['success' => 'You are already subscribed!']);
|
|
} else {
|
|
echo json_encode(['error' => 'An error occurred. Please try again.']);
|
|
}
|
|
}
|
|
}
|
|
}
|