<?php
// File: newsletter_handler.php (Final Version)
session_start();
require_once 'db.php';
require_once 'email_helper.php'; // Ensure the email helper is included

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['email'])) {
    $email = filter_var(trim($_POST['email']), FILTER_SANITIZE_EMAIL);
    $status = 'subscribed'; // Set default status for new/resubscribed users
    $unsubscribe_token = bin2hex(random_bytes(32)); // Generate a unique token

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        // Redirect back with an error message if email is invalid
        header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? 'index.php') . '?newsletter_status=error&msg=Invalid email format.');
        exit();
    }

    // Check if the email already exists in the database
    $stmt_check = $conn->prepare("SELECT email, status FROM newsletter_subscribers WHERE email = ?");
    $stmt_check->bind_param("s", $email);
    $stmt_check->execute();
    $result_check = $stmt_check->get_result();

    if ($result_check->num_rows > 0) {
        // Email exists, check its current status
        $existing_sub = $result_check->fetch_assoc();
        if ($existing_sub['status'] === 'subscribed') {
            // If already subscribed, redirect back with a message
            header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? 'index.php') . '?newsletter_status=error&msg=You are already subscribed.');
        } else {
            // If they were previously unsubscribed, update their status back to 'subscribed'
            // and generate a new unsubscribe token for security.
            $stmt_update = $conn->prepare("UPDATE newsletter_subscribers SET status = 'subscribed', unsubscribe_token = ? WHERE email = ?");
            $stmt_update->bind_param("ss", $unsubscribe_token, $email);
            if ($stmt_update->execute()) {
                 // Send a 'Welcome Back' email
                $subject = "Welcome Back to the UCF Newsletter!";
                $message = "<h1>Subscription Confirmed!</h1><p>You have successfully re-subscribed to the United Cultural Forum newsletter. We're glad to have you back!</p>";
                try {
                    sendEmail($email, $subject, $message);
                } catch (Exception $e) {
                    // Log error if email sending fails, but don't block the user
                    error_log("Failed to send re-subscription email to " . $email . ": " . $e->getMessage());
                }
                // Redirect back with success message
                header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? 'index.php') . '?newsletter_status=success');
            } else {
                // Handle database update error
                error_log("Failed to update subscriber status for: " . $email . " Error: " . $stmt_update->error);
                header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? 'index.php') . '?newsletter_status=error&msg=Could not update subscription.');
            }
        }
    } else {
        // Email does not exist, insert the new subscriber
        $stmt_insert = $conn->prepare("INSERT INTO newsletter_subscribers (email, status, unsubscribe_token) VALUES (?, ?, ?)");
        $stmt_insert->bind_param("sss", $email, $status, $unsubscribe_token);
        if ($stmt_insert->execute()) {
            // Send the initial 'Welcome' email
            $subject = "Welcome to the UCF Newsletter!";
            $message = "<h1>Subscription Confirmed!</h1><p>Thank you for subscribing to the United Cultural Forum newsletter. You'll now receive updates on news, events, and competitions.</p>";
            try {
                 sendEmail($email, $subject, $message);
            } catch (Exception $e) {
                 // Log error if email sending fails, but don't block the user
                 error_log("Failed to send welcome email to " . $email . ": " . $e->getMessage());
            }
            // Redirect back with success message
            header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? 'index.php') . '?newsletter_status=success');
        } else {
            // Handle database insert error
            error_log("Failed to insert new subscriber: " . $email . " Error: " . $stmt_insert->error);
            header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? 'index.php') . '?newsletter_status=error&msg=Could not save subscription.');
        }
    }

    // Close the initial check statement if it was opened
    if (isset($stmt_check)) $stmt_check->close();
    // Close update/insert statements if they were opened
    if (isset($stmt_update)) $stmt_update->close();
    if (isset($stmt_insert)) $stmt_insert->close();
    
    $conn->close();
    exit();

} else {
    // If not a POST request or email is missing, redirect to the home page
    header('Location: index.php');
    exit();
}
?>

