<?php
/**
 * Enhanced Messages/Chat Interface with Real-time Updates
 * OBGYN Research & Collaboration Platform
 */

require_once '../config/config.php';

requireLogin();
if (!isResearcher()) {
    redirect(SITE_URL . '/index.php');
}

$pageTitle = 'Messages';
$userId = getCurrentUserId();

$isMobile = preg_match('/Mobile|Android|iPhone|iPad|iPod/', $_SERVER['HTTP_USER_AGENT']);

// Include appropriate header based on device
if ($isMobile) {
    include '../templates/researcher-mobile-header.php';
} else {
    include '../templates/researcher-header.php';
}
?>

<!-- Bootstrap CSS and JS for modal functionality -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

<?php if (!$isMobile): ?>
<style>
/* Hide sidebar/menu on desktop for messages page */
.sidebar, .side-menu, #sidebar, .col-md-3, .col-lg-2 {
    display: none !important;
}
.main-content {
    margin-left: 0 !important;
    width: 100% !important;
}
</style>

<div class="container-fluid">
    <div class="row">
        <?php include 'message-container.php'; ?>
    </div>
</div>
<?php else: ?>
<!-- Mobile View -->
<?php include 'message-container-mobile.php'; ?>
<?php endif; ?>

<script>
// Check for URL parameters to auto-open chat
const urlParams = new URLSearchParams(window.location.search);
const targetUserId = urlParams.get('user') || urlParams.get('to');

if (targetUserId) {
    // Wait for page to load and ChatManager to be available
    function checkAndOpenChat() {
        // Check for both desktop ChatManager and mobile setup
        const isMobile = <?php echo $isMobile ? 'true' : 'false'; ?>;
        
        if (isMobile) {
            // For mobile, check if the global showNewChatModal function is available
            if (typeof showNewChatModal === 'function' && document.getElementById('newChatModal')) {
                console.log('Opening chat with user ID:', targetUserId, 'using mobile showNewChatModal');
                showNewChatModal(targetUserId);
                return true;
            }
        } else {
            // For desktop, check if ChatManager is available
            if (typeof ChatManager !== 'undefined' && typeof ChatManager.showNewChatModal === 'function' && document.getElementById('newChatModal')) {
                console.log('Opening chat with user ID:', targetUserId, 'using ChatManager');
                ChatManager.showNewChatModal(targetUserId);
                return true;
            }
        }
        return false;
    }
    
    // Try immediately
    if (!checkAndOpenChat()) {
        // Set up listeners for both DOMContentLoaded and load events
        function setupChatOpening() {
            if (!checkAndOpenChat()) {
                const checkInterval = setInterval(() => {
                    if (checkAndOpenChat()) {
                        clearInterval(checkInterval);
                    }
                }, 100);
                
                // Timeout after 5 seconds
                setTimeout(() => {
                    clearInterval(checkInterval);
                    console.warn('Timeout waiting for ChatManager to load');
                }, 5000);
            }
        }
        
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', setupChatOpening);
        } else {
            // DOM already loaded, try immediately and set up interval
            setupChatOpening();
        }
        
        // Also try on window load as a fallback
        window.addEventListener('load', () => {
            if (!checkAndOpenChat()) {
                const fallbackInterval = setInterval(() => {
                    if (checkAndOpenChat()) {
                        clearInterval(fallbackInterval);
                    }
                }, 200);
                
                setTimeout(() => {
                    clearInterval(fallbackInterval);
                }, 3000);
            }
        });
    }
}
</script>

<!-- New Chat Modal -->
<div class="modal fade" id="newChatModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">New Message</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">Select Researcher</label>
                    <select id="researcher-select" class="form-select">
                        <option value="">Loading researchers...</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">Message</label>
                    <textarea id="initial-message" class="form-control" rows="3" placeholder="Type your first message..."></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button id="send-new-message-btn" type="button" class="btn btn-primary">Send Message</button>
            </div>
        </div>
    </div>
</div>

<!-- Add Participants Modal -->
<div class="modal fade" id="addParticipantsModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add Participants</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">Select Researcher to Add</label>
                    <select id="add-participant-select" class="form-select">
                        <option value="">Loading researchers...</option>
                    </select>
                </div>
                <div class="alert alert-info">
                    <i class="fas fa-info-circle"></i> Adding a participant will convert this conversation to a group chat if it isn't already one.
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button id="add-participant-btn" type="button" class="btn btn-primary" onclick="ChatManager.addParticipant()">Add Participant</button>
            </div>
        </div>
    </div>
</div>

<?php
// Include appropriate footer based on device
if ($isMobile) {
    include '../templates/researcher-mobile-footer.php';
} else {
    include '../templates/footer.php';
}
?>
