<?php
// 1. INCLUDE THE UNIFIED HEADER
// This path now correctly points to your single, site-wide header file.
include '../includes/header.php';

// --- Page-Specific Logic Starts Here ---
// The $user_id and $user_data variables are available from header.php

// 2. FETCH ALL MESSAGES for the logged-in user
// We JOIN with the users table to get sender information, including their verification status.
$stmt = $conn->prepare("
    SELECT 
        m.id, 
        m.message_text, 
        m.created_at, 
        m.is_read,
        m.booking_type,
        u.full_name as sender_name, 
        u.role as sender_role, 
        u.verification_status as sender_verification,
        COALESCE(b.booking_ref, fb.booking_ref, frb.booking_ref, hb.booking_ref) as booking_ref
    FROM messages m
    JOIN users u ON m.sender_id = u.id
    LEFT JOIN bookings b ON m.booking_id = b.id AND m.booking_type IN ('tour', 'service')
    LEFT JOIN flight_bookings fb ON m.booking_id = fb.id AND m.booking_type = 'flight'
    LEFT JOIN ferry_bookings frb ON m.booking_id = frb.id AND m.booking_type = 'ferry'
    LEFT JOIN hotel_bookings hb ON m.booking_id = hb.id AND m.booking_type = 'hotel'
    WHERE m.recipient_id = ?
    ORDER BY m.created_at DESC
");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$messages_result = $stmt->get_result();
$messages = $messages_result->fetch_all(MYSQLI_ASSOC);
$stmt->close();
?>

<style>
    /* Custom styles for the inbox layout */
    .inbox-container { height: 75vh; overflow: hidden; }
    .message-list { height: 100%; overflow-y: auto; }
    .message-content { height: 100%; overflow-y: auto; }
    .message-list .list-group-item { cursor: pointer; border-right: 0; border-left: 0; }
    .message-list .list-group-item.active { background-color: var(--primary-color); border-color: var(--primary-color); }
    .message-body { white-space: pre-wrap; /* Preserves line breaks */ }
</style>

<div class="container my-5">
    <div class="dashboard-content">
        <h1 class="h2 mb-4">My Messages</h1>

        <div class="card shadow-sm">
            <div class="row g-0 inbox-container">
                <div class="col-lg-4 border-end">
                    <div class="message-list">
                        <?php if (!empty($messages)): ?>
                        <div class="list-group list-group-flush">
                            <?php foreach ($messages as $index => $message): ?>
                                <?php $subject_preview = substr($message['message_text'], 0, 50) . (strlen($message['message_text']) > 50 ? '...' : ''); ?>
                                <a href="#" class="list-group-item list-group-item-action <?php if($index === 0) echo 'active'; ?>" 
                                   data-message-id="<?php echo $message['id']; ?>"
                                   data-sender="<?php echo htmlspecialchars($message['sender_name']); ?>"
                                   data-date="<?php echo date('F j, Y, h:i A', strtotime($message['created_at'])); ?>"
                                   data-body="<?php echo htmlspecialchars($message['message_text']); ?>"
                                   data-booking-ref="<?php echo htmlspecialchars($message['booking_ref']); ?>"
                                   data-verified="<?php echo (str_contains($message['sender_role'], '_partner') && $message['sender_verification'] === 'verified') ? 'true' : 'false'; ?>">
                                    <div class="d-flex w-100 justify-content-between">
                                        <h6 class="mb-1">
                                            <?php echo htmlspecialchars($message['sender_name']); ?>
                                            <?php echo display_verified_badge($message['sender_verification']); ?>
                                        </h6>
                                        <small><?php echo date('M d', strtotime($message['created_at'])); ?></small>
                                    </div>
                                    <p class="mb-1"><?php echo htmlspecialchars($subject_preview); ?></p>
                                    <small class="text-muted">Regarding: <?php echo htmlspecialchars($message['booking_ref']); ?></small>
                                </a>
                            <?php endforeach; ?>
                        </div>
                        <?php else: ?>
                            <div class="p-4 text-center text-muted">You have no messages.</div>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="col-lg-8">
                    <div class="message-content p-4">
                        <?php if (!empty($messages)): $first_message = $messages[0]; ?>
                            <div id="message-header">
                                <h3 id="message-subject">
                                    Conversation about Booking #<span id="message-booking-ref"><?php echo htmlspecialchars($first_message['booking_ref']); ?></span>
                                </h3>
                                <div class="d-flex align-items-center mb-3">
                                    <div class="flex-grow-1">
                                        <strong id="message-sender-name">
                                            <?php echo htmlspecialchars($first_message['sender_name']); ?>
                                            <span id="message-verified-icon">
                                                <?php echo display_verified_badge($first_message['sender_verification']); ?>
                                            </span>
                                        </strong>
                                        <div class="text-muted small" id="message-date"><?php echo date('F j, Y, h:i A', strtotime($first_message['created_at'])); ?></div>
                                    </div>
                                    <button class="btn btn-outline-secondary btn-sm"><i class="bi bi-reply-fill"></i> Reply</button>
                                </div>
                            </div>
                            <hr>
                            <div id="message-body" class="message-body">
                                <?php echo nl2br(htmlspecialchars($first_message['message_text'])); ?>
                            </div>
                        <?php else: ?>
                            <div class="text-center text-muted h-100 d-flex align-items-center justify-content-center">
                                <p>Select a message on the left to read it.</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const messageListItems = document.querySelectorAll('.message-list .list-group-item');
    
    const subjectEl = document.getElementById('message-subject');
    const bookingRefSpan = document.getElementById('message-booking-ref');
    const senderNameEl = document.getElementById('message-sender-name');
    const verifiedIconEl = document.getElementById('message-verified-icon');
    const dateEl = document.getElementById('message-date');
    const bodyEl = document.getElementById('message-body');
    const verifiedBadgeHTML = ' <span class="verified-badge" title="Verified Partner"><i class="bi bi-patch-check-fill"></i> Verified</span>';

    messageListItems.forEach(item => {
        item.addEventListener('click', function(e) {
            e.preventDefault();
            messageListItems.forEach(i => i.classList.remove('active'));
            this.classList.add('active');

            const bookingRef = this.dataset.bookingRef;
            const sender = this.dataset.sender;
            const date = this.dataset.date;
            const body = this.dataset.body;
            const isVerified = this.dataset.verified === 'true';

            bookingRefSpan.textContent = bookingRef;
            senderNameEl.textContent = sender;
            dateEl.textContent = date;
            bodyEl.innerHTML = body.replace(/\n/g, '<br>');
            
            if (isVerified) {
                verifiedIconEl.innerHTML = verifiedBadgeHTML;
            } else {
                verifiedIconEl.innerHTML = '';
            }
        });
    });
});
</script>

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