<?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' => __('newsletter_invalid_email', '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' => __('newsletter_success', 'Thank you for subscribing!')]);
        } catch (\PDOException $e) {
            if ($e->getCode() == 23000) { // Duplicate entry
                echo json_encode(['success' => __('newsletter_already_subscribed', 'You are already subscribed!')]);
            } else {
                echo json_encode(['error' => __('newsletter_error', 'An error occurred. Please try again.')]);
            }
        }
    }
}