<?php

require_once __DIR__ . '/../app/config/config.php';
require_once __DIR__ . '/../app/config/database.php';
require_once __DIR__ . '/../app/helpers/functions.php';
require_once __DIR__ . '/../app/helpers/activity.php';

if (!is_post()) {
    redirect(BASE_URL . '/public/index.php');
}

if (!verify_csrf()) {
    redirect(BASE_URL . '/public/index.php?newsletter=invalid');
}

$email = strtolower(trim($_POST['newsletter_email'] ?? ''));
$firstName = trim($_POST['newsletter_first_name'] ?? '');
$source = trim($_POST['newsletter_source'] ?? 'website_footer');

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    redirect(BASE_URL . '/public/index.php?newsletter=invalid_email');
}

try {
    $stmt = $pdo->prepare("
        SELECT *
        FROM newsletter_subscribers
        WHERE email = ?
        LIMIT 1
    ");
    $stmt->execute([$email]);
    $existingSubscriber = $stmt->fetch();

    if ($existingSubscriber) {
        if ($existingSubscriber['status'] === 'unsubscribed') {
            $stmt = $pdo->prepare("
                UPDATE newsletter_subscribers
                SET first_name = ?,
                    source = ?,
                    status = 'subscribed',
                    subscribed_at = CURRENT_TIMESTAMP
                WHERE id = ?
            ");
            $stmt->execute([
    $firstName !== '' ? $firstName : $existingSubscriber['first_name'],
    $source,
    $existingSubscriber['id']
]);

log_admin_activity(
    'newsletter_resubscribed',
    'Newsletter subscriber reactivated: ' . $email . ' | Source: ' . $source
);

redirect(BASE_URL . '/public/index.php?newsletter=resubscribed');
        }

        redirect(BASE_URL . '/public/index.php?newsletter=exists');
    }

    $discountCode = 'LOVE10';

    $stmt = $pdo->prepare("
        INSERT INTO newsletter_subscribers (
            email,
            first_name,
            source,
            discount_code,
            status
        ) VALUES (?, ?, ?, ?, 'subscribed')
    ");

    $stmt->execute([
    $email,
    $firstName !== '' ? $firstName : null,
    $source,
    $discountCode
]);

log_admin_activity(
    'newsletter_subscribed',
    'New newsletter subscriber: ' . $email . ' | Source: ' . $source . ' | Discount: ' . $discountCode
);

redirect(BASE_URL . '/public/index.php?newsletter=success');
} catch (Exception $e) {
    redirect(BASE_URL . '/public/index.php?newsletter=error');
}