<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require '../vendor/autoload.php';
include '../db_connect.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['email'])) {
    $email = trim($_POST['email']);

    // Check if already subscribed
    $check = $conn->prepare("SELECT id FROM newsletter_emails WHERE email = ?");
    $check->bind_param("s", $email);
    $check->execute();
    $check->store_result();

    if ($check->num_rows > 0) {
        echo "You're already subscribed!";
        exit;
    }

    // Save to database
    $stmt = $conn->prepare("INSERT INTO newsletter_emails (email) VALUES (?)");
    $stmt->bind_param("s", $email);

    if ($stmt->execute()) {
        // Send email to yourself (notification)
        $mail = new PHPMailer(true);
        try {
            $mail->isSMTP();
            $mail->Host = 'smtp.gmail.com';
            $mail->SMTPAuth = true;
            $mail->Username = 'benjamindanieljr11@gmail.com'; // your Gmail
            $mail->Password = 'tvvvkzlylfgdmcys'; // Gmail App Password
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port = 587;

            $mail->setFrom('benjamindanieljr11@gmail.com', 'Zemaraim Technology');
            $mail->addAddress('benjamindanieljr11@gmail.com'); // Send to yourself

            $mail->isHTML(true);
            $mail->Subject = "New Newsletter Subscription";
            $mail->Body = "<h3>New subscriber:</h3><p><strong>Email:</strong> $email</p>";

            $mail->send();
        } catch (Exception $e) {
            // No need to show error to user — just log
            error_log("Mail Error: {$mail->ErrorInfo}");
        }

        echo "Thank you for subscribing!";
    } else {
        echo "Database error. Please try again.";
    }

    $stmt->close();
    $conn->close();
} else {
    echo "Invalid request.";
}
?>
