<?php
$page_title = 'Manage Emails';
require_once('includes/load.php');
page_require_level(3);

include_once('layouts/header.php');

if (isset($_POST['submit'])) {
    $email = $db->escape($_POST['email']);

    if (!empty($email) && filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $sql = "INSERT INTO email_list (email) VALUES ('{$email}')";
        if ($db->query($sql)) {
            $message = "Email added successfully.";
        } else {
            $message = "Failed to add email.";
        }
    } else {
        $message = "Invalid email address.";
    }
}

// Fetch email addresses
$sql_emails = "SELECT * FROM email_list";
$result_emails = $db->query($sql_emails);
?>

<div class="container">
    <h1>Email Management</h1>

    <!-- Form to add new email -->
    <form action="email.php" method="post">
        <div class="form-group">
            <label for="email">Email Address:</label>
            <input type="email" id="email" name="email" class="form-control" required>
        </div>
        <button type="submit" name="submit" class="btn btn-primary">Add Email</button>
    </form>

    <!-- Display message -->
    <?php if (isset($message)): ?>
        <div class="alert alert-info">
            <?php echo $message; ?>
        </div>
    <?php endif; ?>

    <!-- Table to display email addresses -->
    <h2>Email List</h2>
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>ID</th>
                <th>Email Address</th>
                <th>Added At</th>
            </tr>
        </thead>
        <tbody>
            <?php if ($result_emails->num_rows > 0): ?>
                <?php while ($row = $result_emails->fetch_assoc()): ?>
                    <tr>
                        <td><?php echo $row['id']; ?></td>
                        <td><?php echo $row['email']; ?></td>
                        <td><?php echo $row['created_at']; ?></td>
                    </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr>
                    <td colspan="3">No emails found.</td>
                </tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<?php include_once('layouts/footer.php'); ?>
