
<?php
require_once __DIR__ . '/includes/rbac.php';

$isMobile = preg_match('/Mobile|Android|iPhone|iPad|iPod/', $_SERVER['HTTP_USER_AGENT']);
/**
 * Home Page
 * OBGYN Research & Collaboration Platform
 */
ini_set('display_errors', 1);
error_reporting(E_ALL);
require_once 'config/config.php';

$pageTitle = 'Home';

// Get statistics
try {
    $db = getDB();
    
    // Count researchers
    $stmt = $db->query("SELECT COUNT(*) FROM users WHERE role_id = " . ROLE_RESEARCHER . " AND status = 'active'");
    $totalResearchers = $stmt->fetchColumn();
    
    // Count studies
    $stmt = $db->query("SELECT COUNT(*) FROM studies WHERE status IN ('active', 'completed')");
    $totalStudies = $stmt->fetchColumn();
    
    // Count publications
    $stmt = $db->query("SELECT COUNT(*) FROM publications WHERE status = 'published'");
    $totalPublications = $stmt->fetchColumn();
    
    // Count institutions
    $stmt = $db->query("SELECT COUNT(*) FROM institutions WHERE status = 'active'");
    $totalInstitutions = $stmt->fetchColumn();
    
    // Get recent studies
    $stmt = $db->prepare("
        SELECT s.*, u.first_name, u.last_name, 
               (SELECT COUNT(*) FROM study_collaborators WHERE study_id = s.id AND status = 'active') as collaborators_count
        FROM studies s
        JOIN users u ON s.creator_id = u.id
        WHERE s.is_public = 1 AND s.status = 'active'
        ORDER BY s.created_at DESC
        LIMIT 6
    ");
    $stmt->execute();
    $recentStudies = $stmt->fetchAll();
    
} catch (Exception $e) {
    error_log("Error fetching home page data: " . $e->getMessage());
    $totalResearchers = 0;
    $totalStudies = 0;
    $totalPublications = 0;
    $totalInstitutions = 0;
    $recentStudies = [];
}

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

<!-- Hero Slider Section -->
<section class="hero-swiper swiper">
    <div class="swiper-wrapper">
        <!-- Slide 1 -->
        <div class="swiper-slide" style="background-image: url('https://images.unsplash.com/photo-1576091160399-112ba8d25d1d?w=1920');">
            <div class="slide-content">
                <h1>Advancing Women's Health Research</h1>
                <h2>Join the global community of OB/GYN researchers</h2>
                <p>Connect with experts, share knowledge, and collaborate on groundbreaking studies in obstetrics and gynecology.</p>
                <?php if (!isLoggedIn()): ?>
                    <a href="<?php echo SITE_URL_DYNAMIC; ?>/register.php" class="btn btn-light btn-lg">
                        <i class="fas fa-user-plus"></i> Get Started
                    </a>
                <?php else: ?>
                    <a href="<?php echo SITE_URL_DYNAMIC; ?>/researcher/dashboard.php" class="btn btn-light btn-lg">
                        <i class="fas fa-tachometer-alt"></i> Go to Dashboard
                    </a>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Slide 2 -->
        <div class="swiper-slide" style="background-image: url('https://images.unsplash.com/photo-1559757175-5700dde675bc?w=1920');">
            <div class="slide-content">
                <h1>Collaborate with Global Experts</h1>
                <h2>Build your research network worldwide</h2>
                <p>Access a platform designed for seamless collaboration between researchers, institutions, and healthcare professionals.</p>
                <a href="<?php echo SITE_URL_DYNAMIC; ?>/public/researchers.php" class="btn btn-light btn-lg">
                    <i class="fas fa-users"></i> Explore Network
                </a>
            </div>
        </div>
        
        <!-- Slide 3 -->
        <div class="swiper-slide" style="background-image: url('https://images.unsplash.com/photo-1582719471384-894fbb16e074?w=1920');">
            <div class="slide-content">
                <h1>Access Cutting-Edge Studies</h1>
                <h2>Stay updated with latest research</h2>
                <p>Browse thousands of active studies, publications, and research findings from leading institutions worldwide.</p>
                <a href="<?php echo SITE_URL_DYNAMIC; ?>/public/studies.php" class="btn btn-light btn-lg">
                    <i class="fas fa-flask"></i> Browse Studies
                </a>
            </div>
        </div>
        
        <!-- Slide 4 -->
        <div class="swiper-slide" style="background-image: url('https://images.unsplash.com/photo-1631217868264-e5b90bb7e133?w=1920');">
            <div class="slide-content">
                <h1>Join Our Research Community</h1>
                <h2>Be part of something bigger</h2>
                <p>Connect with over 10,000 researchers, share insights, and contribute to advancing women's healthcare globally.</p>
                <?php if (!isLoggedIn()): ?>
                    <a href="<?php echo SITE_URL_DYNAMIC; ?>/register.php" class="btn btn-light btn-lg">
                        <i class="fas fa-user-plus"></i> Join Now
                    </a>
                <?php else: ?>
                    <a href="<?php echo SITE_URL_DYNAMIC; ?>/researcher/dashboard.php" class="btn btn-light btn-lg">
                        <i class="fas fa-tachometer-alt"></i> Dashboard
                    </a>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Slide 5 -->
        <div class="swiper-slide" style="background-image: url('https://images.unsplash.com/photo-1579154204601-01588f351e67?w=1920');">
            <div class="slide-content">
                <h1>Transform Healthcare Together</h1>
                <h2>Your research makes a difference</h2>
                <p>Collaborate on studies that impact millions of lives. Share your expertise and learn from the best in the field.</p>
                <a href="<?php echo SITE_URL_DYNAMIC; ?>/public/about.php" class="btn btn-light btn-lg">
                    <i class="fas fa-info-circle"></i> Learn More
                </a>
            </div>
        </div>
    </div>
    
    <!-- Navigation -->
    <div class="swiper-button-next"></div>
    <div class="swiper-button-prev"></div>
    
    <!-- Pagination -->
    <div class="swiper-pagination"></div>
</section>

<!-- About Snippet Section -->
<section class="about-snippet">
    <div class="container">
        <div class="row justify-content-center text-center mb-5" data-aos="fade-up">
            <div class="col-lg-8">
                <h2>Empowering Global OB/GYN Research</h2>
                <p class="lead">
                    Our platform connects researchers, institutions, and healthcare professionals worldwide, 
                    fostering collaboration and advancing women's health through innovative research and knowledge sharing.
                </p>
            </div>
        </div>
        
        <div class="row g-4">
            <div class="col-md-6 col-lg-4" data-aos="fade-up" data-aos-delay="100">
                <div class="about-highlight">
                    <div class="icon">
                        <i class="fas fa-globe"></i>
                    </div>
                    <h4>Global Network</h4>
                    <p>Connect with over 10,000 researchers from 150+ countries, building a truly global research community.</p>
                </div>
            </div>
            
            <div class="col-md-6 col-lg-4" data-aos="fade-up" data-aos-delay="200">
                <div class="about-highlight">
                    <div class="icon">
                        <i class="fas fa-shield-alt"></i>
                    </div>
                    <h4>Secure Platform</h4>
                    <p>Enterprise-grade security with 2FA, encryption, and compliance with international data protection standards.</p>
                </div>
            </div>
            
            <div class="col-md-6 col-lg-4" data-aos="fade-up" data-aos-delay="300">
                <div class="about-highlight">
                    <div class="icon">
                        <i class="fas fa-bolt"></i>
                    </div>
                    <h4>Real-time Collaboration</h4>
                    <p>Instant messaging, file sharing, and collaborative tools designed for seamless research teamwork.</p>
                </div>
            </div>
            
            <div class="col-md-6 col-lg-4" data-aos="fade-up" data-aos-delay="400">
                <div class="about-highlight">
                    <div class="icon">
                        <i class="fas fa-microscope"></i>
                    </div>
                    <h4>Evidence-Based</h4>
                    <p>Access peer-reviewed studies, publications, and research data from leading medical institutions.</p>
                </div>
            </div>
            
            <div class="col-md-6 col-lg-4" data-aos="fade-up" data-aos-delay="500">
                <div class="about-highlight">
                    <div class="icon">
                        <i class="fas fa-check-circle"></i>
                    </div>
                    <h4>HIPAA Compliant</h4>
                    <p>Full compliance with healthcare data regulations ensuring patient privacy and data security.</p>
                </div>
            </div>
            
            <div class="col-md-6 col-lg-4" data-aos="fade-up" data-aos-delay="600">
                <div class="about-highlight">
                    <div class="icon">
                        <i class="fas fa-headset"></i>
                    </div>
                    <h4>24/7 Support</h4>
                    <p>Dedicated support team available around the clock to assist with your research needs.</p>
                </div>
            </div>
        </div>
        
        <div class="text-center mt-5" data-aos="fade-up" data-aos-delay="700">
            <a href="<?php echo SITE_URL_DYNAMIC; ?>/public/about.php" class="btn btn-primary btn-lg">
                <i class="fas fa-info-circle"></i> Learn More About Us
            </a>
        </div>
    </div>
</section>

<!-- Statistics Section -->
<section class="py-5 bg-light">
    <div class="container">
        <div class="row g-4">
            <div class="col-md-3" data-aos="zoom-in" data-aos-delay="100">
                <div class="stats-card">
                    <h3 class="counter" data-target="<?php echo $totalResearchers; ?>"><?php echo number_format($totalResearchers); ?></h3>
                    <p><i class="fas fa-users"></i> Active Researchers</p>
                </div>
            </div>
            <div class="col-md-3" data-aos="zoom-in" data-aos-delay="200">
                <div class="stats-card" style="background: linear-gradient(135deg, #198754, #146c43);">
                    <h3 class="counter" data-target="<?php echo $totalStudies; ?>"><?php echo number_format($totalStudies); ?></h3>
                    <p><i class="fas fa-flask"></i> Research Studies</p>
                </div>
            </div>
            <div class="col-md-3" data-aos="zoom-in" data-aos-delay="300">
                <div class="stats-card" style="background: linear-gradient(135deg, #dc3545, #b02a37);">
                    <h3 class="counter" data-target="<?php echo $totalPublications; ?>"><?php echo number_format($totalPublications); ?></h3>
                    <p><i class="fas fa-book"></i> Publications</p>
                </div>
            </div>
            <div class="col-md-3" data-aos="zoom-in" data-aos-delay="400">
                <div class="stats-card" style="background: linear-gradient(135deg, #ffc107, #cc9a06);">
                    <h3 class="counter" data-target="<?php echo $totalInstitutions; ?>"><?php echo number_format($totalInstitutions); ?></h3>
                    <p><i class="fas fa-building"></i> Institutions</p>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Features Section -->
<section class="py-5">
    <div class="container">
        <div class="text-center mb-5" data-aos="fade-up">
            <h2 class="fw-bold">Platform Features</h2>
            <p class="text-muted">Everything you need for collaborative medical research</p>
        </div>
        
        <div class="row g-4">
            <div class="col-md-4" data-aos="fade-up" data-aos-delay="100">
                <div class="card h-100 text-center hover-lift">
                    <div class="card-body">
                        <div class="mb-3">
                            <i class="fas fa-network-wired fa-3x text-primary"></i>
                        </div>
                        <h5 class="card-title">Global Networking</h5>
                        <p class="card-text">
                            Connect with OBGYN researchers worldwide. Build your professional network 
                            and collaborate on groundbreaking studies.
                        </p>
                    </div>
                </div>
            </div>
            
            <div class="col-md-4" data-aos="fade-up" data-aos-delay="200">
                <div class="card h-100 text-center hover-lift">
                    <div class="card-body">
                        <div class="mb-3">
                            <i class="fas fa-file-medical fa-3x text-success"></i>
                        </div>
                        <h5 class="card-title">Research Documentation</h5>
                        <p class="card-text">
                            Comprehensive tools for documenting your research, managing studies, 
                            and tracking progress with version control.
                        </p>
                    </div>
                </div>
            </div>
            
            <div class="col-md-4" data-aos="fade-up" data-aos-delay="300">
                <div class="card h-100 text-center hover-lift">
                    <div class="card-body">
                        <div class="mb-3">
                            <i class="fas fa-users-cog fa-3x text-info"></i>
                        </div>
                        <h5 class="card-title">Team Collaboration</h5>
                        <p class="card-text">
                            Create collaborative studies, assign roles, share documents, 
                            and communicate in real-time with your research team.
                        </p>
                    </div>
                </div>
            </div>
            
            <div class="col-md-4" data-aos="fade-up" data-aos-delay="400">
                <div class="card h-100 text-center hover-lift">
                    <div class="card-body">
                        <div class="mb-3">
                            <i class="fas fa-comments fa-3x text-warning"></i>
                        </div>
                        <h5 class="card-title">Real-Time Messaging</h5>
                        <p class="card-text">
                            Integrated chat system for seamless communication between researchers 
                            with file sharing capabilities.
                        </p>
                    </div>
                </div>
            </div>
            
            <div class="col-md-4" data-aos="fade-up" data-aos-delay="500">
                <div class="card h-100 text-center hover-lift">
                    <div class="card-body">
                        <div class="mb-3">
                            <i class="fas fa-book-open fa-3x text-danger"></i>
                        </div>
                        <h5 class="card-title">Publication Hub</h5>
                        <p class="card-text">
                            Share your published research, link to external publications, 
                            and engage with peer feedback and discussions.
                        </p>
                    </div>
                </div>
            </div>
            
            <div class="col-md-4" data-aos="fade-up" data-aos-delay="600">
                <div class="card h-100 text-center hover-lift">
                    <div class="card-body">
                        <div class="mb-3">
                            <i class="fas fa-shield-alt fa-3x text-secondary"></i>
                        </div>
                        <h5 class="card-title">Secure & Compliant</h5>
                        <p class="card-text">
                            Enterprise-grade security with 2FA, data encryption, and compliance 
                            with international data protection standards.
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Latest Blog Posts Section -->
<?php
// Get latest blog posts
$stmt = $db->prepare("
    SELECT p.*, u.first_name, u.last_name
    FROM cms_posts p
    LEFT JOIN users u ON p.author_id = u.id
    WHERE p.status = 'published'
    ORDER BY p.published_at DESC
    LIMIT 3
");
$stmt->execute();
$latestPosts = $stmt->fetchAll();
?>

<?php if (!empty($latestPosts)): ?>
<section class="py-5">
    <div class="container">
        <div class="d-flex justify-content-between align-items-center mb-4" data-aos="fade-up">
            <div>
                <h2 class="fw-bold mb-2">Latest from Our Blog</h2>
                <p class="text-muted mb-0">Stay updated with the latest research insights and medical breakthroughs</p>
            </div>
            <a href="<?php echo SITE_URL_DYNAMIC; ?>/public/blog.php" class="btn btn-outline-primary">
                View All Posts <i class="fas fa-arrow-right"></i>
            </a>
        </div>
        
        <div class="row g-4">
            <?php foreach ($latestPosts as $index => $post): ?>
                <div class="col-md-4" data-aos="fade-up" data-aos-delay="<?php echo ($index + 1) * 100; ?>">
                    <div class="card blog-card h-100 shadow-sm">
                        <?php if ($post['featured_image']): ?>
                            <img src="<?php echo e($post['featured_image']); ?>" 
                                 class="card-img-top" 
                                 alt="<?php echo e($post['title']); ?>"
                                 style="height: 200px; object-fit: cover;">
                        <?php else: ?>
                            <div class="bg-gradient-primary d-flex align-items-center justify-content-center" 
                                 style="height: 200px;">
                                <i class="fas fa-newspaper fa-4x text-white opacity-25"></i>
                            </div>
                        <?php endif; ?>
                        
                        <div class="card-body d-flex flex-column">
                            <div class="mb-2">
                                <span class="badge bg-primary">
                                    <i class="fas fa-newspaper"></i> Blog Post
                                </span>
                                <?php if (isset($post['featured']) && $post['featured']): ?>
                                    <span class="badge bg-warning text-dark">
                                        <i class="fas fa-star"></i> Featured
                                    </span>
                                <?php endif; ?>
                            </div>
                            
                            <h5 class="card-title">
                                <a href="<?php echo SITE_URL_DYNAMIC; ?>/public/post.php?slug=<?php echo e($post['slug']); ?>" 
                                   class="text-decoration-none text-dark">
                                    <?php echo e($post['title']); ?>
                                </a>
                            </h5>
                            
                            <p class="card-text text-muted small mb-2">
                                <i class="fas fa-user"></i> <?php echo e($post['first_name'] . ' ' . $post['last_name']); ?>
                                <span class="mx-1">•</span>
                                <i class="fas fa-calendar"></i> <?php echo date('M j, Y', strtotime($post['published_at'])); ?>
                            </p>
                            
                            <p class="card-text flex-grow-1">
                                <?php echo e($post['excerpt'] ?: substr(strip_tags($post['content']), 0, 120) . '...'); ?>
                            </p>
                            
                            <div class="d-flex justify-content-between align-items-center mt-3">
                                <a href="<?php echo SITE_URL_DYNAMIC; ?>/public/post.php?slug=<?php echo e($post['slug']); ?>" 
                                   class="btn btn-outline-primary btn-sm">
                                    Read More <i class="fas fa-arrow-right ms-1"></i>
                                </a>
                                <small class="text-muted">
                                    <i class="fas fa-eye"></i> <?php echo number_format(isset($post['views']) ? $post['views'] : (isset($post['views_count']) ? $post['views_count'] : 0)); ?>
                                </small>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</section>
<?php endif; ?>



<!-- Recent Studies Section -->
<?php if (!empty($recentStudies)): ?>
<section class="py-5 bg-light">
    <div class="container">
        <div class="d-flex justify-content-between align-items-center mb-4" data-aos="fade-up">
            <h2 class="fw-bold">Recent Studies</h2>
            <a href="<?php echo SITE_URL_DYNAMIC; ?>/public/studies.php" class="btn btn-primary">
                View All Studies <i class="fas fa-arrow-right"></i>
            </a>
        </div>
        
        <div class="row g-4">
            <?php foreach ($recentStudies as $index => $study): ?>
                <div class="col-md-6 col-lg-4" data-aos="fade-up" data-aos-delay="<?php echo ($index + 1) * 100; ?>">
                    <div class="card study-card h-100 hover-lift">
                        <span class="badge bg-<?php echo $study['type'] == 'clinical' ? 'primary' : 'success'; ?>">
                            <?php echo ucfirst($study['type']); ?>
                        </span>
                        <div class="card-body">
                            <h5 class="card-title">
                            <a href="<?php echo SITE_URL_DYNAMIC; ?>/public/study-detail.php?id=<?php echo $study['id']; ?>" 
                                   class="text-decoration-none text-dark">
                                    <?php echo e($study['title']); ?>
                                </a>
                            </h5>
                            <p class="card-text text-truncate-3">
                                <?php echo e($study['summary']); ?>
                            </p>
                            <div class="study-meta">
                                <span>
                                    <i class="fas fa-user"></i>
                                    <?php echo e($study['first_name'] . ' ' . $study['last_name']); ?>
                                </span>
                                <span>
                                    <i class="fas fa-users"></i>
                                    <?php echo $study['collaborators_count']; ?> collaborators
                                </span>
                            </div>
                        </div>
                        <div class="card-footer bg-transparent">
                            <small class="text-muted">
                                <i class="fas fa-clock"></i> <?php echo timeAgo($study['created_at']); ?>
                            </small>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</section>
<?php endif; ?>

<!-- Call to Action -->
<?php if (!isLoggedIn()): ?>
<section class="py-5 bg-primary text-white" data-aos="fade-up">
    <div class="container text-center">
        <h2 class="fw-bold mb-4">Ready to Join Our Research Community?</h2>
        <p class="lead mb-4">
            Start collaborating with researchers worldwide and contribute to advancing OBGYN medical knowledge.
        </p>
        <a href="<?php echo SITE_URL_DYNAMIC; ?>/register.php" class="btn btn-light btn-lg">
            <i class="fas fa-user-plus"></i> Create Free Account
        </a>
    </div>
</section>
<?php endif; ?>

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