<?php
require_once 'db.php';

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

if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $email = trim($_POST['email']);
    
    if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
        try {
            $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            
            $stmt = $pdo->prepare("INSERT INTO newsletter_subscribers (email) VALUES (?)");
            $stmt->execute([$email]);
            
            echo json_encode(['success' => true, 'message' => 'Tu es maintenant abonné à notre newsletter !']);
            
        } catch(PDOException $e) {
            if($e->getCode() == 23000) {
                echo json_encode(['success' => false, 'message' => 'Cette adresse email est déjà abonnée.']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Erreur lors de l\'abonnement.']);
            }
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Adresse email invalide.']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Méthode non autorisée.']);
}
?>