<?php
// messages.php
require 'config/db.php';


// 1. Session Security Check
if (!isset($_SESSION['user_id'])) { 
    header("Location: login.php"); 
    exit; 
}

// We already have the numeric ID from login.php
$current_user_id = $_SESSION['user_id'];

try {
    /** * 2. Fetch Chat List
     * This query finds the latest message for each unique contact.
     * We use a subquery to ensure we get the actual LATEST message text.
     */
    $stmt_chats = $pdo->prepare("
        SELECT 
            u.id as contact_id, 
            u.username as contact_name,
            m.message, 
            m.created_at, 
            m.is_read,
            m.sender_id
        FROM messages m
        JOIN users u ON (m.sender_id = u.id OR m.receiver_id = u.id)
        WHERE (m.sender_id = ? OR m.receiver_id = ?) 
        AND u.id != ?
        AND m.id IN (
            SELECT MAX(id) 
            FROM messages 
            WHERE sender_id = ? OR receiver_id = ? 
            GROUP BY IF(sender_id = ?, receiver_id, sender_id)
        )
        ORDER BY m.created_at DESC
    ");
    
    $stmt_chats->execute([
        $current_user_id, $current_user_id, $current_user_id,
        $current_user_id, $current_user_id, $current_user_id
    ]);
    $chats = $stmt_chats->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    // Prevent the "offset on bool" warning by initializing as empty array
    $chats = [];
    error_log("Messages query failed: " . $e->getMessage());
}

include 'includes/header.php';
?>

<div style="max-width: 600px; margin: 40px auto; background: var(--nav-bg); border: 1px solid var(--border); border-radius: 15px; overflow: hidden; font-family: 'Inter', sans-serif;">
    <div style="padding: 20px; border-bottom: 1px solid var(--border); font-weight: bold; color: white; display: flex; align-items: center; gap: 10px;">
        <i class="fa-solid fa-comments" style="color: var(--primary);"></i> YOUR MESSAGES
    </div>

    <?php if (!empty($chats)): ?>
        <?php foreach($chats as $c): 
            // Mark as unread only if I am the receiver and haven't read it
            $unread = ($c['is_read'] == 0 && $c['sender_id'] != $current_user_id);
        ?>
            <a href="chat_view.php?id=<?php echo $c['contact_id']; ?>" 
               style="display: flex; padding: 15px; border-bottom: 1px solid var(--border); text-decoration: none; align-items: center; gap: 15px; transition: 0.2s; background: <?php echo $unread ? 'rgba(0, 255, 136, 0.02)' : 'transparent'; ?>;"
               onmouseover="this.style.background='rgba(255,255,255,0.03)'"
               onmouseout="this.style.background='<?php echo $unread ? 'rgba(0, 255, 136, 0.02)' : 'transparent'; ?>'">
                
                <div style="width: 45px; height: 45px; background: #222; border: 1px solid var(--border); border-radius: 50%; display: flex; align-items: center; justify-content: center; color: var(--primary); font-weight: bold;">
                    <?php echo strtoupper(substr($c['contact_name'], 0, 1)); ?>
                </div>

                <div style="flex: 1; overflow: hidden;">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px;">
                        <span style="color: white; font-weight: bold; font-size: 14px;">@<?php echo htmlspecialchars($c['contact_name']); ?></span>
                        <span style="color: #444; font-size: 10px;"><?php echo date('M d', strtotime($c['created_at'])); ?></span>
                    </div>
                    <div style="color: var(--text-gray); font-size: 13px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
                        <?php if($c['sender_id'] == $current_user_id) echo '<span style="color: #555;">You: </span>'; ?>
                        <?php echo htmlspecialchars($c['message']); ?>
                    </div>
                </div>

                <?php if($unread): ?>
                    <div style="width: 8px; height: 8px; background: var(--primary); border-radius: 50%; box-shadow: 0 0 10px var(--primary);"></div>
                <?php endif; ?>
            </a>
        <?php endforeach; ?>
    <?php else: ?>
        <div style="padding: 60px; text-align: center; color: var(--text-gray);">
            <i class="fa-solid fa-comment-dots" style="font-size: 30px; opacity: 0.1; margin-bottom: 10px;"></i>
            <p style="font-size: 13px;">No conversations found.</p>
        </div>
    <?php endif; ?>
</div>

<?php include 'includes/footer.php'; ?>