<?php
// Determine the correct path to config
$configPath = '';
if (file_exists(__DIR__ . '/../config/config.php')) {
    $configPath = __DIR__ . '/../config/config.php';
} elseif (file_exists(dirname(dirname(__FILE__)) . '/config/config.php')) {
    $configPath = dirname(dirname(__FILE__)) . '/config/config.php';
}

if ($configPath && !defined('ROOT_PATH')) {
    require_once $configPath;
}

$currentPage = basename($_SERVER['PHP_SELF'], '.php');
$pageTitle = $pageTitle ?? SITE_NAME;
$flashMessage = getFlashMessage();

// Determine base URL dynamically if not set
if (!defined('SITE_URL') || empty(SITE_URL)) {
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'];
    $basePath = '/obgyn-research-platform';
    $baseUrl = $protocol . '://' . $host . $basePath;
    define('SITE_URL_DYNAMIC', rtrim($baseUrl, '/'));
} else {
    define('SITE_URL_DYNAMIC', SITE_URL);
}

// Get unread notifications count
$unreadCount = 0;
if (function_exists('getUnreadNotificationsCount') && function_exists('getCurrentUserId')) {
    $unreadCount = getUnreadNotificationsCount(getCurrentUserId());
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://cdnjs.cloudflare.com https://unpkg.com; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net https://cdnjs.cloudflare.com https://unpkg.com https://code.jquery.com; font-src 'self' https://cdnjs.cloudflare.com; img-src 'self' data: https:;">
    <title><?php echo e($pageTitle); ?> - <?php echo e(getSiteName()); ?></title>
    
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Custom CSS -->
    <link rel="stylesheet" href="<?php echo SITE_URL_DYNAMIC; ?>/assets/css/style.css">
    
    <style>
        /* Mobile-specific styles */
        body {
            overflow-x: hidden;
            padding-top: 60px; /* Fixed header height */
            padding-bottom: 80px; /* Fixed footer height */
        }

        /* Fixed Mobile Header - Messenger Style */
        .mobile-messenger-header {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 1030;
            background: #fff;
            border-bottom: 1px solid #e9ecef;
            box-shadow: 0 2px 4px rgba(0,0,0,0.08);
            height: 60px;
        }

        .mobile-messenger-header .header-content {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 8px 16px;
            height: 100%;
        }

        .mobile-messenger-header .header-left {
            display: flex;
            align-items: center;
            gap: 12px;
            flex: 1;
        }

        .mobile-messenger-header .header-center {
            flex: 2;
            text-align: center;
        }

        .mobile-messenger-header .header-right {
            display: flex;
            align-items: center;
            gap: 8px;
            flex: 1;
            justify-content: flex-end;
        }

        .mobile-messenger-header .page-title {
            font-size: 1.1rem;
            font-weight: 600;
            margin: 0;
            color: #1c1e21;
        }

        .mobile-messenger-header .btn-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            background: transparent;
            border: none;
            color: #050505;
            transition: background-color 0.2s;
            padding: 0;
        }

        .mobile-messenger-header .btn-icon:hover,
        .mobile-messenger-header .btn-icon:active {
            background-color: #f0f2f5;
        }

        .mobile-messenger-header .btn-icon i {
            font-size: 1.2rem;
        }

        .mobile-messenger-header .logo-img {
            height: 36px;
            width: auto;
        }

        /* Header Quick Nav */
        .header-quick-nav {
            display: flex;
            gap: 4px;
            align-items: center;
            justify-content: center;
        }

        .quick-nav-link {
            width: 44px;
            height: 44px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #65676b;
            text-decoration: none;
            transition: all 0.2s;
        }

        .quick-nav-link:hover,
        .quick-nav-link.active {
            background: #f0f2f5;
            color: #0d6efd;
        }

        .quick-nav-link i {
            font-size: 1.1rem;
        }

        /* Search Container */
        .mobile-search-container {
            position: fixed;
            top: 60px;
            left: 0;
            right: 0;
            background: #fff;
            padding: 12px 16px;
            border-bottom: 1px solid #e9ecef;
            box-shadow: 0 2px 4px rgba(0,0,0,0.08);
            z-index: 1029;
            display: none;
            animation: slideDown 0.3s ease-out;
        }

        .mobile-search-container.show {
            display: block;
        }

        @keyframes slideDown {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .mobile-search-container .search-input {
            width: 100%;
            padding: 10px 16px;
            border: 1px solid #e9ecef;
            border-radius: 20px;
            background: #f0f2f5;
            font-size: 0.95rem;
        }

        .mobile-search-container .search-input:focus {
            outline: none;
            background: #fff;
            border-color: #0d6efd;
        }

        /* Notification Badge */
        .notification-badge {
            position: absolute;
            top: -4px;
            right: -4px;
            background: #dc3545;
            color: white;
            border-radius: 10px;
            padding: 2px 6px;
            font-size: 0.7rem;
            font-weight: 600;
            min-width: 18px;
            text-align: center;
        }

        /* Main Content Area */
        .mobile-content-wrapper {
            min-height: calc(100vh - 140px);
            padding: 0;
        }

        /* Offcanvas Menu */
        .mobile-offcanvas {
            width: 280px;
        }

        .mobile-offcanvas .offcanvas-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .mobile-offcanvas .nav-link {
            padding: 12px 16px;
            color: #333;
            border-radius: 8px;
            margin-bottom: 4px;
            transition: all 0.2s;
        }

        .mobile-offcanvas .nav-link:hover {
            background: #f0f2f5;
            color: #0d6efd;
        }

        .mobile-offcanvas .nav-link.active {
            background: #0d6efd;
            color: white;
        }

        .mobile-offcanvas .nav-link i {
            width: 24px;
            margin-right: 12px;
        }

        /* Mobile Nav Sections */
        .mobile-nav-section {
            padding: 16px;
            border-bottom: 1px solid #e9ecef;
        }

        .mobile-nav-section:last-child {
            border-bottom: none;
        }

        .mobile-nav-title {
            font-weight: 600;
            color: #495057;
            margin-bottom: 12px;
            font-size: 0.9rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .mobile-social-links {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
        }

        .social-link {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #f8f9fa;
            color: #6c757d;
            text-decoration: none;
            transition: all 0.2s;
        }

        .social-link:hover {
            background: #0d6efd;
            color: white;
            transform: translateY(-2px);
        }
    </style>
    
    <?php if (isset($additionalCSS)): ?>
        <?php echo $additionalCSS; ?>
    <?php endif; ?>
</head>
<body>
    <!-- Fixed Mobile Header - Messenger Style -->
    <header class="mobile-messenger-header">
        <div class="header-content">
            <!-- Left: Back/Menu Button -->
            <div class="header-left">
                <?php if (isset($showBackButton) && $showBackButton): ?>
                    <button class="btn-icon" onclick="window.history.back()">
                        <i class="fas fa-arrow-left"></i>
                    </button>
                <?php else: ?>
                    <button class="btn-icon" type="button" data-bs-toggle="offcanvas" data-bs-target="#mobileMenu">
                        <i class="fas fa-bars"></i>
                    </button>
                <?php endif; ?>
                
                <?php 
                $headerContactInfo = getContactInfo();
                $headerCompanyName = !empty($headerContactInfo['company_name']) ? $headerContactInfo['company_name'] : getSiteName();
                $logoUrl = getLogoUrl();
                
                if ($logoUrl && file_exists(str_replace(SITE_URL_DYNAMIC, ROOT_PATH, $logoUrl))): ?>
                    <img src="<?php echo $logoUrl; ?>" alt="<?php echo e($headerCompanyName); ?>" class="logo-img">
                <?php elseif (file_exists(ROOT_PATH . '/assets/images/logo.png')): ?>
                    <img src="<?php echo SITE_URL_DYNAMIC; ?>/assets/images/logo.png" alt="<?php echo e($headerCompanyName); ?>" class="logo-img">
                <?php endif; ?>
            </div>

            <!-- Center: Quick Nav Links -->
            <div class="header-center">
                <?php if ($currentPage === 'messages-enhanced' || $currentPage === 'messages'): ?>
                    <h1 class="page-title"><?php echo e($pageTitle); ?></h1>
                <?php else: ?>
                    <div class="header-quick-nav">
                        <a href="<?php echo SITE_URL_DYNAMIC; ?>/index.php" class="quick-nav-link">
                            <i class="fas fa-home"></i>
                        </a>
                        <a href="<?php echo SITE_URL_DYNAMIC; ?>/public/studies.php" class="quick-nav-link">
                            <i class="fas fa-flask"></i>
                        </a>
                        <a href="<?php echo SITE_URL_DYNAMIC; ?>/public/researchers.php" class="quick-nav-link">
                            <i class="fas fa-users"></i>
                        </a>
                        <a href="<?php echo SITE_URL_DYNAMIC; ?>/public/publications.php" class="quick-nav-link">
                            <i class="fas fa-book"></i>
                        </a>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Right: Action Buttons -->
            <div class="header-right">
                <?php if ($currentPage === 'messages-enhanced' || $currentPage === 'messages'): ?>
                    <!-- Search Button for Messages -->
                    <button class="btn-icon" id="search-toggle-btn" onclick="toggleMobileSearch()">
                        <i class="fas fa-search"></i>
                    </button>
                    
                    <!-- New Message Button -->
                    <button class="btn-icon" onclick="showNewChatModal()">
                        <i class="fas fa-edit"></i>
                    </button>
                <?php else: ?>
                    <!-- Notifications button removed -->
                <?php endif; ?>
            </div>
        </div>
    </header>

    <!-- Search Container (Hidden by default) -->
    <div id="mobile-search-container" class="mobile-search-container">
        <input type="text" id="mobile-search-input" class="search-input" placeholder="Search conversations...">
    </div>

    <!-- Offcanvas Menu -->
    <div class="offcanvas offcanvas-start mobile-offcanvas" tabindex="-1" id="mobileMenu">
        <div class="offcanvas-header">
            <h5 class="offcanvas-title">
                <i class="fas fa-user-circle me-2"></i>
                <?php echo e($_SESSION['user_name'] ?? 'Menu'); ?>
            </h5>
            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="offcanvas"></button>
        </div>
        <div class="offcanvas-body p-3">
            <!-- Quick Links Section -->
            <div class="mobile-nav-section">
                <h6 class="mobile-nav-title">Quick Links</h6>
                <nav class="nav flex-column">
                    <a class="nav-link" href="<?php echo SITE_URL_DYNAMIC; ?>/index.php">
                        <i class="fas fa-home"></i> Home
                    </a>
                    <a class="nav-link" href="<?php echo SITE_URL_DYNAMIC; ?>/public/about.php">
                        <i class="fas fa-info-circle"></i> About
                    </a>
                    <a class="nav-link" href="<?php echo SITE_URL_DYNAMIC; ?>/public/studies.php">
                        <i class="fas fa-flask"></i> Studies
                    </a>
                    <a class="nav-link" href="<?php echo SITE_URL_DYNAMIC; ?>/public/researchers.php">
                        <i class="fas fa-users"></i> Researchers
                    </a>
                </nav>
            </div>

            <!-- Resources Section -->
            <div class="mobile-nav-section">
                <h6 class="mobile-nav-title">Resources</h6>
                <nav class="nav flex-column">
                    <a class="nav-link" href="<?php echo SITE_URL_DYNAMIC; ?>/public/publications.php">
                        <i class="fas fa-book"></i> Publications
                    </a>
                    <a class="nav-link" href="<?php echo SITE_URL_DYNAMIC; ?>/public/help.php">
                        <i class="fas fa-question-circle"></i> Help Center
                    </a>
                    <a class="nav-link" href="<?php echo SITE_URL_DYNAMIC; ?>/public/faq.php">
                        <i class="fas fa-question"></i> FAQ
                    </a>
                    <a class="nav-link" href="<?php echo SITE_URL_DYNAMIC; ?>/public/contact.php">
                        <i class="fas fa-envelope"></i> Contact
                    </a>
                </nav>
            </div>

            <!-- Connect Section -->
            <div class="mobile-nav-section">
                <h6 class="mobile-nav-title">Connect</h6>
                <div class="mobile-social-links">
                    <?php
                    $socialMedia = getSocialMediaLinks();
                    $socialIcons = [
                        'facebook' => 'fab fa-facebook',
                        'twitter' => 'fab fa-twitter',
                        'linkedin' => 'fab fa-linkedin',
                        'instagram' => 'fab fa-instagram',
                        'youtube' => 'fab fa-youtube',
                        'researchgate' => 'fab fa-researchgate',
                        'orcid' => 'fab fa-orcid'
                    ];
                    
                    foreach ($socialMedia as $platform => $url):
                        if (!empty($url) && isset($socialIcons[$platform])):
                    ?>
                        <a href="<?php echo e($url); ?>" target="_blank" class="social-link" title="<?php echo ucfirst($platform); ?>">
                            <i class="<?php echo $socialIcons[$platform]; ?>"></i>
                        </a>
                    <?php 
                        endif;
                    endforeach;
                    
                    // Show default icons if no social media configured
                    if (empty($socialMedia)):
                    ?>
                        <a href="#" class="social-link"><i class="fab fa-facebook"></i></a>
                        <a href="#" class="social-link"><i class="fab fa-twitter"></i></a>
                        <a href="#" class="social-link"><i class="fab fa-linkedin"></i></a>
                        <a href="#" class="social-link"><i class="fab fa-researchgate"></i></a>
                    <?php endif; ?>
                </div>
                
                <?php 
                $contactInfo = getContactInfo();
                if (!empty($contactInfo['email_primary']) || !empty($contactInfo['phone_primary'])):
                ?>
                <div class="mt-3 small">
                    <?php if (!empty($contactInfo['email_primary'])): ?>
                        <div class="mb-2">
                            <i class="fas fa-envelope me-2"></i>
                            <a href="mailto:<?php echo e($contactInfo['email_primary']); ?>" class="text-decoration-none">
                                <?php echo e($contactInfo['email_primary']); ?>
                            </a>
                        </div>
                    <?php endif; ?>
                    
                    <?php if (!empty($contactInfo['phone_primary'])): ?>
                        <div>
                            <i class="fas fa-phone me-2"></i>
                            <a href="tel:<?php echo e($contactInfo['phone_primary']); ?>" class="text-decoration-none">
                                <?php echo e($contactInfo['phone_primary']); ?>
                            </a>
                        </div>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
            </div>

            <!-- Logout Section -->
            <div class="mobile-nav-section">
                <a href="<?php echo SITE_URL_DYNAMIC; ?>/logout.php" class="btn btn-outline-danger w-100">
                    <i class="fas fa-sign-out-alt"></i> Logout
                </a>
            </div>
        </div>
    </div>

    <!-- Flash Messages -->
    <?php if ($flashMessage): ?>
        <div class="container-fluid mt-2 px-3">
            <div class="alert alert-<?php echo $flashMessage['type'] === 'error' ? 'danger' : $flashMessage['type']; ?> alert-dismissible fade show" role="alert">
                <?php echo e($flashMessage['message']); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        </div>
    <?php endif; ?>

    <!-- Main Content Wrapper -->
    <div class="mobile-content-wrapper">

    <script>
    // Mobile header functionality
    function toggleMobileSearch() {
        const searchContainer = document.getElementById('mobile-search-container');
        const searchInput = document.getElementById('mobile-search-input');
        
        if (searchContainer.classList.contains('show')) {
            searchContainer.classList.remove('show');
            document.body.style.paddingTop = '60px';
        } else {
            searchContainer.classList.add('show');
            document.body.style.paddingTop = '120px';
            setTimeout(() => searchInput.focus(), 300);
        }
    }

    // Close search when clicking outside
    document.addEventListener('click', function(e) {
        const searchContainer = document.getElementById('mobile-search-container');
        const searchBtn = document.getElementById('search-toggle-btn');
        
        if (searchContainer && searchBtn &&
            !searchContainer.contains(e.target) &&
            !searchBtn.contains(e.target) &&
            searchContainer.classList.contains('show')) {
            toggleMobileSearch();
        }
    });

    // Search functionality
    document.addEventListener('DOMContentLoaded', function() {
        const searchInput = document.getElementById('mobile-search-input');
        if (searchInput) {
            searchInput.addEventListener('input', function(e) {
                const searchTerm = e.target.value.toLowerCase();
                // This will be connected to ChatManager search functionality
                if (typeof ChatManager !== 'undefined' && ChatManager.searchConversations) {
                    ChatManager.searchConversations(searchTerm);
                }
            });
        }
    });
    </script>
