<?php
/**
 * subscribe.php — AJAX endpoint for newsletter form
 * Called via fetch() from the frontend form
 */
header('Content-Type: application/json');
include_once __DIR__ . '/config/db.php';

$email = trim($_POST['email'] ?? '');

if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(['success' => false, 'message' => 'Please enter a valid email address.']);
    exit;
}

try {
    // Check duplicate
    $chk = $pdo->prepare("SELECT id, status FROM email_subscribe WHERE email = ?");
    $chk->execute([$email]);
    $existing = $chk->fetch();

    if ($existing) {
        if ($existing['status'] == 1) {
            echo json_encode(['success' => false, 'message' => 'This email is already subscribed!']);
        } else {
            // Re-activate unsubscribed email
            $pdo->prepare("UPDATE email_subscribe SET status = 1 WHERE id = ?")->execute([$existing['id']]);
            echo json_encode(['success' => true, 'message' => 'Welcome back! You have been re-subscribed.']);
        }
        exit;
    }

    $pdo->prepare("INSERT INTO email_subscribe (email, status) VALUES (?, 1)")->execute([$email]);
    echo json_encode(['success' => true, 'message' => 'Thank you for subscribing!']);

} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Something went wrong. Please try again.']);
}