<?php
/**
 * Browse Studies - Public Page
 * OBGYN Research & Collaboration Platform
 */

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

$pageTitle = 'Browse Studies';

// Get filters
$search = $_GET['search'] ?? '';
$type = $_GET['type'] ?? '';
$category = $_GET['category'] ?? '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 12;
$offset = ($page - 1) * $perPage;

$db = getDB();
$where = ["s.is_public = 1", "s.status IN ('active', 'completed')", "s.approval_status = 'approved'"];
$params = [];

if (!empty($search)) {
    $where[] = "(s.title LIKE ? OR s.summary LIKE ? OR s.description LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if (!empty($type)) {
    $where[] = "s.type = ?";
    $params[] = $type;
}

if (!empty($category)) {
    $where[] = "s.category_id = ?";
    $params[] = $category;
}

$whereClause = implode(' AND ', $where);

// Get total count
$stmt = $db->prepare("SELECT COUNT(*) FROM studies s WHERE $whereClause");
$stmt->execute($params);
$totalStudies = $stmt->fetchColumn();
$totalPages = ceil($totalStudies / $perPage);

// Get studies
$stmt = $db->prepare("
    SELECT s.*, u.first_name, u.last_name, c.name as category_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
    LEFT JOIN categories c ON s.category_id = c.id
    WHERE $whereClause
    ORDER BY s.created_at DESC
    LIMIT $perPage OFFSET $offset
");
$stmt->execute($params);
$studies = $stmt->fetchAll();

// Get categories for filter
$stmt = $db->prepare("SELECT * FROM categories ORDER BY name");
$stmt->execute();
$categories = $stmt->fetchAll();

include '../templates/header.php';
?>

<div class="container my-5">
    <div class="row">
        <div class="col-lg-3 mb-4">
            <!-- Filters Sidebar -->
            <div class="card shadow-sm">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0"><i class="fas fa-filter"></i> Filters</h5>
                </div>
                <div class="card-body">
                    <form method="GET" action="">
                        <div class="mb-3">
                            <label class="form-label">Search</label>
                            <input type="text" class="form-control" name="search" value="<?php echo e($search); ?>" placeholder="Search studies...">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Study Type</label>
                            <select class="form-select" name="type">
                                <option value="">All Types</option>
                                <option value="clinical" <?php echo $type === 'clinical' ? 'selected' : ''; ?>>Clinical</option>
                                <option value="surgical" <?php echo $type === 'surgical' ? 'selected' : ''; ?>>Surgical</option>
                                <option value="fertility" <?php echo $type === 'fertility' ? 'selected' : ''; ?>>Fertility</option>
                                <option value="urogynecology" <?php echo $type === 'urogynecology' ? 'selected' : ''; ?>>Urogynecology</option>
                                <option value="menopause" <?php echo $type === 'menopause' ? 'selected' : ''; ?>>Menopause</option>
                                <option value="other" <?php echo $type === 'other' ? 'selected' : ''; ?>>Other</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Category</label>
                            <select class="form-select" name="category">
                                <option value="">All Categories</option>
                                <?php foreach ($categories as $cat): ?>
                                    <option value="<?php echo $cat['id']; ?>" <?php echo $category == $cat['id'] ? 'selected' : ''; ?>>
                                        <?php echo e($cat['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <button type="submit" class="btn btn-primary w-100 mb-2">
                            <i class="fas fa-search"></i> Apply Filters
                        </button>
                        <a href="studies.php" class="btn btn-outline-secondary w-100">
                            <i class="fas fa-redo"></i> Reset
                        </a>
                    </form>
                </div>
            </div>
            
            <!-- Statistics -->
            <div class="card shadow-sm mt-4">
                <div class="card-body">
                    <h6 class="card-title">Statistics</h6>
                    <p class="mb-1"><strong><?php echo number_format($totalStudies); ?></strong> studies found</p>
                </div>
            </div>
        </div>
        
        <div class="col-lg-9">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2><i class="fas fa-flask"></i> Browse Studies</h2>
            </div>
            
            <?php if (empty($studies)): ?>
                <div class="alert alert-info">
                    <i class="fas fa-info-circle"></i> No studies found matching your criteria.
                </div>
            <?php else: ?>
                <div class="row g-4">
                    <?php foreach ($studies as $study): ?>
                        <div class="col-md-6 col-lg-4">
                            <div class="card study-card h-100 shadow-sm">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between align-items-start mb-2">
                                        <span class="badge bg-<?php echo $study['type'] == 'clinical' ? 'primary' : 'success'; ?>">
                                            <?php echo ucfirst($study['type']); ?>
                                        </span>
                                        <?php if ($study['category_name']): ?>
                                            <span class="badge bg-secondary"><?php echo e($study['category_name']); ?></span>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <h5 class="card-title">
                                        <a href="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-muted small" style="display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden;">
                                        <?php echo e($study['summary']); ?>
                                    </p>
                                    
                                    <div class="study-meta small text-muted">
                                        <div class="mb-1">
                                            <i class="fas fa-user"></i>
                                            <?php echo e($study['first_name'] . ' ' . $study['last_name']); ?>
                                        </div>
                                        <div class="mb-1">
                                            <i class="fas fa-users"></i>
                                            <?php echo $study['collaborators_count']; ?> collaborators
                                        </div>
                                        <div>
                                            <i class="fas fa-clock"></i>
                                            <?php echo timeAgo($study['created_at']); ?>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-footer bg-transparent">
                                    <a href="study-detail.php?id=<?php echo $study['id']; ?>" class="btn btn-sm btn-outline-primary w-100">
                                        <i class="fas fa-eye"></i> View Details
                                    </a>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
                
                <!-- Pagination -->
                <?php if ($totalPages > 1): ?>
                    <nav aria-label="Page navigation" class="mt-4">
                        <ul class="pagination justify-content-center">
                            <?php if ($page > 1): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&type=<?php echo $type; ?>&category=<?php echo $category; ?>">
                                        Previous
                                    </a>
                                </li>
                            <?php endif; ?>
                            
                            <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
                                <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&type=<?php echo $type; ?>&category=<?php echo $category; ?>">
                                        <?php echo $i; ?>
                                    </a>
                                </li>
                            <?php endfor; ?>
                            
                            <?php if ($page < $totalPages): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&type=<?php echo $type; ?>&category=<?php echo $category; ?>">
                                        Next
                                    </a>
                                </li>
                            <?php endif; ?>
                        </ul>
                    </nav>
                <?php endif; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

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