<?php

require_once '../config.php';


// Load emails from data.email.php
$emails = file_exists('../inc/data.email.php') ? include '../inc/data.email.php' : ['emails' => [], 'settings' => ['frequency' => 1, 'delay' => 60]];

// Pagination settings
$emails_per_page = 20; // Adjustable: Number of emails per page
$current_page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$total_emails = count($emails['emails']);
$total_pages = max(1, ceil($total_emails / $emails_per_page));
$offset = ($current_page - 1) * $emails_per_page;
$paginated_emails = array_slice($emails['emails'], $offset, $emails_per_page);

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['add_email'])) {
        $new_email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
        if ($new_email && !in_array($new_email, $emails['emails'])) {
            $emails['emails'][] = $new_email;
        }
    } elseif (isset($_POST['delete_emails'])) {
        $emails['emails'] = array_diff($emails['emails'], $_POST['selected_emails'] ?? []);
    } elseif (isset($_POST['update_settings'])) {
        $emails['settings']['frequency'] = (int)$_POST['frequency'];
        $emails['settings']['delay'] = (int)$_POST['delay'];
    }

    // Save updated emails and settings
    file_put_contents('../inc/data.email.php', '<?php return ' . var_export($emails, true) . ';');
    // Refresh to reset pagination if emails changed
    header("Location: edit-email.php?page=$current_page");
    exit;
}

// Handle download requests
if (isset($_GET['download'])) {
    $format = $_GET['download'];
    header('Content-Type: text/' . ($format === 'csv' ? 'csv' : 'plain'));
    header('Content-Disposition: attachment; filename="emails.' . $format . '"');
    
    if ($format === 'csv') {
        echo "Email\n";
        foreach ($emails['emails'] as $email) {
            echo "$email\n";
        }
    } else {
        echo implode("\n", $emails['emails']);
    }
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <?php include "data/styles.php"?>
    <title>Admin - Email Management</title>
    <style>
        .card { transition: transform 0.3s ease, box-shadow 0.3s ease; }
        .card:hover { transform: translateY(-2px); box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1); }
        .btn { transition: background-color 0.3s ease, transform 0.2s ease; }
        .btn:hover { transform: translateY(-1px); }
        .table-row { transition: background-color 0.2s ease; }
        .table-row:hover { background-color: #f9fafb; }
        .pagination-btn { transition: background-color 0.3s ease; }
        .pagination-btn:hover { background-color: #e5e7eb; }
        .pagination-btn.active { background-color: #2563eb; color: white; }
    </style>
</head>
<body class="bg-gray-100 min-h-screen">
    <div class="container mx-auto px-4 py-8 max-w-5xl">
        <!-- Header -->
        <header class="mb-8 text-center">
            <h1 class="text-3xl font-bold text-gray-900 flex items-center justify-center">
                <i data-lucide="mail" class="w-8 h-8 mr-3 text-blue-600"></i> Email Management Dashboard
            </h1>
            <p class="text-gray-600 mt-2">Manage collected emails and configure popup settings</p>
        </header>

        <!-- Email List Card -->
        <div class="card bg-white rounded-xl shadow p-6 mb-8">
            <h2 class="font-medium text-gray-400 mb-4">Collected Emails</h2>
            <form method="POST">
                <div class="overflow-x-auto">
                    <table class="w-full border-collapse">
                        <thead>
                            <tr class="bg-gray-100 text-gray-700">
                                <th class="p-3 text-left"><input type="checkbox" id="select-all" class="cursor-pointer rounded"></th>
                                <th class="p-3 text-left font-medium">Email Address</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($paginated_emails as $email): ?>
                                <tr class="table-row border-b border-gray-200">
                                    <td class="p-3"><input type="checkbox" name="selected_emails[]" value="<?= htmlspecialchars($email) ?>" class="cursor-pointer rounded"></td>
                                    <td class="p-3 text-gray-800"><?= htmlspecialchars($email) ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <!-- Pagination -->
                <?php if ($total_pages > 1): ?>
                    <div class="flex justify-end mt-4 space-x-2">
                        <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                            <a href="?page=<?= $i ?>" class="pagination-btn px-4 py-2 rounded-lg text-gray-700 <?= $i === $current_page ? 'active' : '' ?>">
                                <?= $i ?>
                            </a>
                        <?php endfor; ?>
                    </div>
                <?php endif; ?>
                <div class="flex justify-end space-x-4 mt-6">
                    <button type="submit" name="delete_emails" class="mt-4 inline-flex items-center gap-2 px-4 py-2 text-sm bg-red-100 text-red-700 rounded-md hover:bg-red-200">
                        <i data-lucide="trash-2" class="w-5 h-5 mr-2"></i> Delete
                    </button>
                    <a href="?download=csv" class="mt-4 inline-flex items-center gap-2 px-4 py-2 text-sm bg-blue-100 text-blue-700 rounded-md hover:bg-blue-200">
                        <i data-lucide="download" class="w-5 h-5 mr-2"></i> CSV
                    </a>
                    <a href="?download=txt" class="mt-4 inline-flex items-center gap-2 px-4 py-2 text-sm bg-blue-100 text-blue-700 rounded-md hover:bg-blue-200">
                        <i data-lucide="download" class="w-5 h-5 mr-2"></i> TXT
                    </a>
                </div>
            </form>
        </div>

        <!-- Add Email Card -->
        <div class="card bg-white rounded-xl shadow p-6 mb-8">
            <h2 class="font-medium text-gray-400 mb-4">Add New Email</h2>
            <form method="POST" class="flex justify-end space-x-4">
                <input type="email" name="email" placeholder="Enter email address" class="border border-gray-300 rounded-lg p-3 w-full focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                <button type="submit" name="add_email" class="btn bg-green-600 text-white px-5 py-3 rounded-xl shadow hover:bg-green-700 flex items-center">
                    <i data-lucide="plus" class="w-5 h-5 mr-2"></i> Add
                </button>
            </form>
        </div>

        <!-- Settings Card -->
        <div class="card bg-white rounded-xl shadow p-6">
            <h2 class="font-medium text-gray-400 mb-4">Popup Configuration</h2>
            <form method="POST" class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label class="block text-sm mb-2 font-medium text-gray-400">Popup Delay (seconds)</label>
                    <input type="number" name="delay" value="<?= $emails['settings']['delay'] ?>" min="1" class="mt-1 border border-gray-300 rounded-lg p-3 w-full focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>
                <div>
                    <label class="block text-sm mb-2 font-medium text-gray-400">Daily Frequency</label>
                    <input type="number" name="frequency" value="<?= $emails['settings']['frequency'] ?>" min="1" class="mt-1 border border-gray-300 rounded-lg p-3 w-full focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>
                <div class="md:col-span-2 flex justify-end">
                    <button type="submit" name="update_settings" class="btn bg-blue-600 text-white px-5 py-3 rounded-xl shadow hover:bg-blue-700 flex items-center">
                        <i data-lucide="save" class="w-5 h-5 mr-2"></i> Save Settings
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
        lucide.createIcons();
        document.getElementById('select-all').addEventListener('change', function() {
            document.querySelectorAll('input[name="selected_emails[]"]').forEach(checkbox => {
                checkbox.checked = this.checked;
            });
        });
    </script>
</body>
</html>