<?php
require 'auth_check.php';
require '../config/db.php';

// DELETE MESSAGE
if (isset($_GET['delete'])) {
    $pdo->prepare("DELETE FROM contact_messages WHERE id = ?")->execute([$_GET['delete']]);
    header("Location: inbox.php"); exit();
}

// FETCH MESSAGES
$msgs = $pdo->query("SELECT * FROM contact_messages ORDER BY created_at DESC")->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Inbox</title>
    <link rel="stylesheet" href="admin_style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
</head>
<body>

    <div class="sidebar">
        <?php include 'sidebar.php'; ?>
    </div>

    <div class="content">
        <h1>Inbox <span style="font-size:16px; color:#777;">(<?php echo count($msgs); ?>)</span></h1>
        
        <?php if(empty($msgs)): ?>
            <p style="background:white; padding:20px; border-radius:8px;">No messages yet.</p>
        <?php else: ?>
            <div style="display: grid; gap: 20px;">
                <?php foreach($msgs as $m): ?>
                <div style="background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.05); border-left: 5px solid #3498db;">
                    <div style="display: flex; justify-content: space-between; margin-bottom: 10px;">
                        <div>
                            <strong><?php echo htmlspecialchars($m['name']); ?></strong> 
                            <small style="color:#777;">(<?php echo htmlspecialchars($m['email']); ?>)</small>
                        </div>
                        <small style="color:#999;"><?php echo date('d M Y, h:i A', strtotime($m['created_at'])); ?></small>
                    </div>
                    
                    <h4 style="margin: 0 0 5px 0; color: #2c3e50;"><?php echo htmlspecialchars($m['subject']); ?></h4>
                    <p style="color: #555; font-size: 14px; line-height: 1.6;"><?php echo nl2br(htmlspecialchars($m['message'])); ?></p>
                    
                    <div style="margin-top: 15px; text-align: right;">
                        <a href="reply_message.php?id=<?php echo $m['id']; ?>" class="btn btn-primary" style="font-size: 12px; padding: 5px 10px; background: #3498db; border: none;">
    <i class="fas fa-reply"></i> Reply
</a>
                        <a href="inbox.php?delete=<?php echo $m['id']; ?>" style="color: red; font-size: 12px; margin-left: 10px;" onclick="return confirm('Delete this message?')">Delete</a>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

</body>
</html>