<?php
/**
 * My Studies List
 * OBGYN Research & Collaboration Platform
 */

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

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

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

// Get filter parameters
$status = $_GET['status'] ?? 'all';
$search = $_GET['search'] ?? '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = STUDIES_PER_PAGE;
$offset = ($page - 1) * $perPage;

// Build query
$db = getDB();
$where = ["s.creator_id = ?"];
$params = [$userId];

if ($status !== 'all') {
    $where[] = "s.status = ?";
    $params[] = $status;
}

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

$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.*, 
           (SELECT COUNT(*) FROM study_collaborators WHERE study_id = s.id AND status = 'active') as collaborators_count,
           (SELECT COUNT(*) FROM study_documents WHERE study_id = s.id) as documents_count
    FROM studies s
    WHERE $whereClause
    ORDER BY s.updated_at DESC
    LIMIT $perPage OFFSET $offset
");
$stmt->execute($params);
$studies = $stmt->fetchAll();

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

<div class="container-fluid p-4">
    <div class="row">
        <!-- Main content - full width since sidebar is offcanvas -->
        <main class="col-12">
            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                <h1 class="h2"><i class="fas fa-flask"></i> My Studies</h1>
                <a href="create-study.php" class="btn btn-primary">
                    <i class="fas fa-plus"></i> Create New Study
                </a>
            </div>

            <!-- Filters -->
            <div class="card shadow mb-4">
                <div class="card-body">
                    <form method="GET" action="" class="row g-3">
                        <div class="col-md-4">
                            <input type="text" class="form-control" name="search" 
                                   value="<?php echo e($search); ?>" 
                                   placeholder="Search studies...">
                        </div>
                        <div class="col-md-3">
                            <select class="form-select" name="status">
                                <option value="all" <?php echo $status === 'all' ? 'selected' : ''; ?>>All Status</option>
                                <option value="draft" <?php echo $status === 'draft' ? 'selected' : ''; ?>>Draft</option>
                                <option value="active" <?php echo $status === 'active' ? 'selected' : ''; ?>>Active</option>
                                <option value="completed" <?php echo $status === 'completed' ? 'selected' : ''; ?>>Completed</option>
                                <option value="archived" <?php echo $status === 'archived' ? 'selected' : ''; ?>>Archived</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <button type="submit" class="btn btn-primary w-100">
                                <i class="fas fa-search"></i> Filter
                            </button>
                        </div>
                        <div class="col-md-3">
                            <a href="studies.php" class="btn btn-outline-secondary w-100">
                                <i class="fas fa-redo"></i> Reset
                            </a>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Studies List -->
            <?php if (empty($studies)): ?>
                <div class="card shadow">
                    <div class="card-body text-center py-5">
                        <i class="fas fa-flask fa-4x text-muted mb-3"></i>
                        <h4>No Studies Found</h4>
                        <p class="text-muted">Start by creating your first research study.</p>
                        <a href="create-study.php" class="btn btn-primary">
                            <i class="fas fa-plus"></i> Create Study
                        </a>
                    </div>
                </div>
            <?php else: ?>
                <div class="row">
                    <?php foreach ($studies as $study): ?>
                    <div class="col-md-6 col-lg-4 mb-4">
                        <div class="card shadow h-100">
                            <div class="card-body">
                                <h5 class="card-title">
                                    <a href="edit-study.php?id=<?php echo $study['id']; ?>">
                                        <?php echo e($study['title']); ?>
                                    </a>
                                </h5>
                                <p class="card-text text-muted small">
                                    <?php echo e(substr($study['summary'] ?? 'No summary', 0, 100)); ?>...
                                </p>
                                <div class="mb-2">
                                    <?php
                                    $statusColors = [
                                        'draft' => 'secondary',
                                        'active' => 'success',
                                        'completed' => 'info',
                                        'archived' => 'dark'
                                    ];
                                    ?>
                                    <span class="badge bg-<?php echo $statusColors[$study['status']] ?? 'secondary'; ?>">
                                        <?php echo ucfirst($study['status']); ?>
                                    </span>
                                    <span class="badge bg-primary"><?php echo ucfirst($study['type']); ?></span>
                                </div>
                                <div class="d-flex justify-content-between align-items-center">
                                    <small class="text-muted">
                                        <i class="fas fa-users"></i> <?php echo $study['collaborators_count']; ?> |
                                        <i class="fas fa-file"></i> <?php echo $study['documents_count']; ?>
                                    </small>
                                    <small class="text-muted">
                                        <?php echo timeAgo($study['updated_at']); ?>
                                    </small>
                                </div>
                            </div>
                            <div class="card-footer bg-white">
                                <a href="edit-study.php?id=<?php echo $study['id']; ?>" class="btn btn-sm btn-primary">
                                    <i class="fas fa-edit"></i> Edit
                                </a>
                                <a href="#" class="btn btn-sm btn-outline-danger" 
                                   onclick="return confirm('Are you sure?')">
                                    <i class="fas fa-trash"></i> Delete
                                </a>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>

                <!-- Pagination -->
                <?php if ($totalPages > 1): ?>
                <nav aria-label="Page navigation">
                    <ul class="pagination justify-content-center">
                        <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                        <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                            <a class="page-link" href="?page=<?php echo $i; ?>&status=<?php echo $status; ?>&search=<?php echo urlencode($search); ?>">
                                <?php echo $i; ?>
                            </a>
                        </li>
                        <?php endfor; ?>
                    </ul>
                </nav>
                <?php endif; ?>
            <?php endif; ?>
        </main>
    </div>
</div>

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