<?php

session_start();

if (!isset($_SESSION['uid'])) {
	header('Location: /admin/login.php');
	die;
}

$conn = new mysqli("localhost", "mileslinden", "Daiso@6969", "mileslinden");

$result = $conn->query("SELECT * FROM subscribers");
if (!$result) {
	http_response_code(500);
	die("Error retrieving subscribers: {$conn->error}");
}

$subscribers = [];
while ($row = $result->fetch_assoc()) {
    $subscribers[] = $row;
}

$result = $conn->query("SELECT id, full_name, subject, send_date FROM messages ORDER BY send_date DESC");
if (!$result) {
	http_response_code(500);
	die("Error retrieving messages: {$conn->error}");
}

$messages = [];
while ($row = $result->fetch_assoc()) {
	$messages[] = $row;
}
?>
<!DOCTYPE HTML>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Miles Linden for San Jose City Council</title>
		<style>
			.cols {
				display: flex;
				gap: 4rem;
			}
			.cols > div {
				flex: 1 1 0;
			}
			.tasks {
				display: flex;
				gap: 4rem;
			}
			.message {
				display: flex;
				justify-content: space-between;
			}
		</style>
    </head>
    <body>
        <h1>Admin Panel</h1>
		<div class="tasks">
			<a href="logout.php">Logout</a>
			<a href="mail.php">Mail All</a>
		</div>
		<div class="cols">
			<div>
				<h2>Subscribers</h2>
				<table cellpadding="5">
				<thead>
					<tr>
						<th>Name</th>
						<th>Email</th>
						<th>Phone</th>
						<!--<th>Gender</th>-->
						<th>Join Date</th>
						<th>Actions</th>
					</tr>
				</thead>
				<tbody>
<?php
	foreach ($subscribers as $row) {
?>
					<tr>
						<td><?= htmlspecialchars($row['full_name']) ?></td>
						<td>
							<a href="mailto:<?= htmlspecialchars($row['email']) ?>"><?= htmlspecialchars($row['email']) ?></a></td>
						<td><?= htmlspecialchars($row['phone']) ?></td>
						<!--<td><?= htmlspecialchars($row['gender']) ?></td>-->
						<td><?= htmlspecialchars($row['join_date']) ?></td>
						<td>
							<button class="deleteEmail" data-email="<?= htmlspecialchars($row['email']) ?>">Delete</button>
						</td>
					</tr>
<?php
	}
?>
				</tbody>
				</table>
			</div>
			<div>
				<h2>Messages</h2>
				<div class="messages">
<?php
	foreach ($messages as $row) {
?>
					<div class="message">
						<div>
							<a href="message.php?id=<?= $row['id'] ?>">
								[<?= $row['send_date'] ?>] <?= htmlspecialchars($row['full_name']) ?>: <?= isset($row['subject']) ? htmlspecialchars($row['subject']) : '(no subject)' ?>
							</a>
						</div>
						<div>
							<button class="deleteMessage" data-message="<?= $row['id'] ?>">Delete</button>
						</div>
					</div>
<?php
	}
?>
				</div>
			</div>
		</div>

		<script>
			document.addEventListener('DOMContentLoaded', function () {
				for (const btn of document.querySelectorAll('button.deleteEmail')) {
					btn.addEventListener('click', function (e) {
						var email = e.target.dataset.email;
						if (confirm(`Are you sure you want to delete ${email}?`)) {
							var fd = new FormData();
							fd.append('email', email);
							fetch('/admin/unsubscribe.php', {
								method: 'POST',
								body: fd
							}).then(function (res) {
								if (!res.ok) {
									res.text().then(alert);
								} else {
									window.location.reload();
								}
							});
						}
					});
				}

				for (const btn of document.querySelectorAll('button.deleteMessage')) {
					btn.addEventListener('click', function (e) {
						var id = e.target.dataset.message;
						var message = e.target.parentElement.parentElement.children[0];
						var summary = message.innerText;
						if (confirm(`Are you sure you want to delete message "${summary}"?`)) {
							var fd = new FormData();
							fd.append('id', id);
							fetch('/admin/deleteMessage.php', {
								method: 'POST',
								body: fd
							}).then(function (res) {
								if (!res.ok) {
									res.text().then(alert);
								} else {
									window.location.reload();
								}
							});
						}
					});
				}
			});
		</script>
    </body>
</html>