<?php
session_start();
require_once "db.php"; // PDO connection

// Check if admin is logged in
$isAdmin = $_SESSION['is_admin'] ?? 0;
$firstName = $_SESSION['firstName'] ?? 'Admin'; // <-- get from session

if (!$isAdmin) {
    header("Location: admin-login.php"); // redirect to login if not admin
    exit();
}

// Fetch messages
$stmt = $conn->prepare("SELECT * FROM contact_messages ORDER BY created_at DESC");
$stmt->execute();
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Messages - Taji Yetu</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="admin-sidebar.css">
<style>
body { font-family:'Segoe UI',sans-serif; background:#000; color:#fff; margin:0; }
.main-content { margin-left:250px; padding:20px; margin-top:60px; min-height:calc(100vh - 60px); }
table { width:100%; border-collapse:collapse; margin-top:20px; }
th, td { padding:12px; text-align:left; border-bottom:1px solid #333; font-size:14px; }
th { background:#111; }
tr.unread { font-weight:bold; color:#fff; }
tr.read { color:#888; }
button { background:#28a745; color:#fff; border:none; padding:6px 12px; border-radius:4px; cursor:pointer; transition:0.3s; }
button:hover { opacity:0.85; }
.modal { display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.8); justify-content:center; align-items:center; z-index:1000; }
.modal-content { background:#111; padding:20px; border-radius:8px; width:90%; max-width:600px; position:relative; color:#fff; }
.modal-close { position:absolute; top:10px; right:15px; font-size:18px; cursor:pointer; }
.modal label { font-weight:bold; display:block; margin-top:10px; }
.modal textarea { width:100%; padding:8px; border-radius:6px; border:none; background:#222; color:#fff; margin-top:5px; resize:vertical; }
.modal button { margin-top:10px; }
</style>
</head>
<body>

<?php include "navbar.php"; ?>
<?php include "admin-sidebar.php"; ?>

<div class="main-content">
    <h1>Contact Messages</h1>
    <h3>Hi <?= htmlspecialchars($firstName) ?>, welcome to the inbox, the one place you get insights from all your customers through the contact form!</h3>
    <table>
        <thead>
            <tr>
                <th>Name</th>
                <th>Email</th>
                <th>Subject</th>
                <th>Status</th>
                <th>Opened By</th>
                <th>Opened At</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach($messages as $msg): ?>
            <tr class="<?= $msg['read_status'] ? 'read' : 'unread' ?>" data-id="<?= $msg['id'] ?>" data-name="<?= htmlspecialchars($msg['name']) ?>" data-email="<?= htmlspecialchars($msg['email']) ?>" data-subject="<?= htmlspecialchars($msg['subject']) ?>" data-message="<?= htmlspecialchars($msg['message']) ?>" data-opened_by="<?= htmlspecialchars($msg['opened_by'] ?? '') ?>" data-opened_at="<?= htmlspecialchars($msg['opened_at'] ?? '') ?>">
                <td><?= htmlspecialchars($msg['name']) ?></td>
                <td><?= htmlspecialchars($msg['email']) ?></td>
                <td><?= htmlspecialchars($msg['subject']) ?></td>
                <td><?= $msg['read_status'] ? 'Read' : 'Unread' ?></td>
                <td><?= htmlspecialchars($msg['opened_by'] ?? '') ?></td>
                <td><?= htmlspecialchars($msg['opened_at'] ?? '') ?></td>
                <td>
                    <button class="view-btn">View</button>
                    <form action="delete_message.php" method="POST" style="display:inline;">
                        <input type="hidden" name="id" value="<?= $msg['id'] ?>">
                        <button type="submit" style="background:#c00;">Delete</button>
                    </form>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<?php include "footer.php"; ?>

<!-- Modal -->
<div class="modal" id="messageModal">
    <div class="modal-content">
        <span class="modal-close">&times;</span>
        <h2 id="modalSubject"></h2>
        <p><strong>From:</strong> <span id="modalName"></span> | <span id="modalEmail"></span></p>
        <p><strong>Opened By:</strong> <span id="modalOpenedBy"></span> | <span id="modalOpenedAt"></span></p>
        <label>Message:</label>
        <textarea id="modalMessage" readonly></textarea>
        <label>Reply:</label>
        <textarea id="modalReply" placeholder="Type your reply here..."></textarea>
        <button id="replyBtn">Send Reply</button>
    </div>
</div>

<script>
// Modal handling
const modal = document.getElementById('messageModal');
const modalClose = document.querySelector('.modal-close');
const viewBtns = document.querySelectorAll('.view-btn');
viewBtns.forEach(btn => {
    btn.addEventListener('click', () => {
        const row = btn.closest('tr');
        document.getElementById('modalName').textContent = row.dataset.name;
        document.getElementById('modalEmail').textContent = row.dataset.email;
        document.getElementById('modalSubject').textContent = row.dataset.subject;
        document.getElementById('modalMessage').value = row.dataset.message;
        document.getElementById('modalOpenedBy').textContent = row.dataset.opened_by || '---';
        document.getElementById('modalOpenedAt').textContent = row.dataset.opened_at || '---';
        modal.style.display = 'flex';

        // Optional: mark as read via AJAX
        fetch('mark_read.php', {
            method: 'POST',
            headers: {'Content-Type':'application/x-www-form-urlencoded'},
            body: 'id=' + row.dataset.id
        }).then(() => {
            row.classList.remove('unread');
            row.classList.add('read');
            row.cells[3].textContent = 'Read';
        });
    });
});

modalClose.addEventListener('click', () => modal.style.display = 'none');

// Send reply
document.getElementById('replyBtn').addEventListener('click', () => {
    const email = document.getElementById('modalEmail').textContent;
    const reply = document.getElementById('modalReply').value;
    if(!reply) return alert('Type a reply first!');
    window.location.href = `mailto:${email}?subject=Re: ${encodeURIComponent(document.getElementById('modalSubject').textContent)}&body=${encodeURIComponent(reply)}`;
});
</script>

</body>
</html>
