<?php
$pageTitle = "Messages";
require_once 'sidebar.php';

$adminId = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reply'])) {
    $receiver_id = (int)$_POST['receiver_id'];
    $subject = clean($conn, $_POST['subject']);
    $message = clean($conn, $_POST['message']);
    mysqli_query($conn, "INSERT INTO messages (sender_id, receiver_id, subject, message) 
                         VALUES ($adminId, $receiver_id, '$subject', '$message')");
    redirect(BASE_URL.'/admin/messages.php', 'Reply sent successfully.');
}

if (isset($_GET['read'])) {
    $id = (int)$_GET['read'];
    mysqli_query($conn, "UPDATE messages SET is_read=1 WHERE id=$id AND receiver_id=$adminId");
}

if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    mysqli_query($conn, "DELETE FROM messages WHERE id=$id AND (sender_id=$adminId OR receiver_id=$adminId)");
    redirect(BASE_URL.'/admin/messages.php', 'Message deleted.');
}

$messages = mysqli_query($conn, "SELECT m.*, s.name as sender_name, s.email as sender_email, s.phone as sender_phone 
                                 FROM messages m 
                                 JOIN users s ON m.sender_id = s.id 
                                 WHERE m.receiver_id = $adminId 
                                 ORDER BY m.is_read ASC, m.created_at DESC");

$replyTo = null;
if (isset($_GET['reply_to'])) {
    $rid = (int)$_GET['reply_to'];
    $replyTo = getUser($conn, $rid);
}
?>

<div class="page-header">
    <h1>Messages Inbox</h1>
    <p style="color:#888; font-size:14px;"><?php echo mysqli_num_rows($messages); ?> messages</p>
</div>

<?php showFlash(); ?>

<?php if ($replyTo): ?>
<div class="dashboard-card">
    <h2 class="full">Reply to <?php echo htmlspecialchars($replyTo['name']); ?></h2>
    <form method="POST">
        <input type="hidden" name="receiver_id" value="<?php echo $replyTo['id']; ?>">
        <div class="form-group">
            <label>Subject</label>
            <input type="text" name="subject" required>
        </div>
        <div class="form-group">
            <label>Message</label>
            <textarea name="message" rows="5" required></textarea>
        </div>
        <button type="submit" name="reply" class="btn">Send Reply</button>
        <a href="messages.php" class="btn btn-gold">Cancel</a>
    </form>
</div>
<?php endif; ?>

<div class="table-wrapper">
    <table>
        <thead>
            <tr>
                <th>From</th>
                <th>Contact</th>
                <th>Subject</th>
                <th>Message</th>
                <th>Date</th>
                <th>Status</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php if (mysqli_num_rows($messages) > 0): ?>
                <?php while ($m = mysqli_fetch_assoc($messages)): ?>
                    <tr style="<?php echo $m['is_read']==0?'background:#fef8ec;':''; ?>">
                        <td><strong><?php echo htmlspecialchars($m['sender_name']); ?></strong></td>
                        <td><small><?php echo htmlspecialchars($m['sender_email']); ?><br>
                            <?php echo htmlspecialchars($m['sender_phone']); ?></small></td>
                        <td><strong style="color:var(--maroon);"><?php echo htmlspecialchars($m['subject']); ?></strong></td>
                        <td><?php echo nl2br(htmlspecialchars(substr($m['message'], 0, 120))); ?><?php echo strlen($m['message'])>120?'...':''; ?></td>
                        <td><small><?php echo date('d M Y H:i', strtotime($m['created_at'])); ?></small></td>
                        <td>
                            <?php if ($m['is_read']==0): ?>
                                <span class="badge badge-pending">New</span>
                            <?php else: ?>
                                <span class="badge badge-confirmed">Read</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ($m['is_read']==0): ?>
                                <a href="?read=<?php echo $m['id']; ?>" class="btn btn-sm">Mark Read</a>
                            <?php endif; ?>
                            <a href="?reply_to=<?php echo $m['sender_id']; ?>" class="btn btn-sm btn-gold">Reply</a>
                            <a href="?delete=<?php echo $m['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Delete?')">🗑</a>
                        </td>
                    </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr><td colspan="7" style="text-align:center; padding:40px; color:#888;">
                    <div style="font-size:40px; color:var(--bronze); margin-bottom:10px;">❦</div>
                    No messages yet.
                </td></tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

</main></div></body></html>
