<?php
/**
 * Researcher Dashboard
 * OBGYN Research & Collaboration Platform
 */

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

// Check if user is logged in
requireLogin();

// Check if user is a researcher
if (!isResearcher()) {
    redirect(SITE_URL . '/index.php');
}

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

// Get researcher profile
$db = getDB();
$stmt = $db->prepare("
    SELECT rp.*, u.first_name, u.last_name, u.email, i.name as institution_name
    FROM researcher_profiles rp
    JOIN users u ON rp.user_id = u.id
    LEFT JOIN institutions i ON rp.institution_id = i.id
    WHERE rp.user_id = ?
");
$stmt->execute([$userId]);
$profile = $stmt->fetch();

// Get statistics
$stmt = $db->prepare("SELECT COUNT(*) FROM studies WHERE creator_id = ?");
$stmt->execute([$userId]);
$studiesCount = $stmt->fetchColumn();

$stmt = $db->prepare("
    SELECT COUNT(*) FROM study_collaborators 
    WHERE user_id = ? AND status = 'active'
");
$stmt->execute([$userId]);
$collaborationsCount = $stmt->fetchColumn();

$stmt = $db->prepare("SELECT COUNT(*) FROM publications WHERE user_id = ?");
$stmt->execute([$userId]);
$publicationsCount = $stmt->fetchColumn();

$stmt = $db->prepare("
    SELECT COUNT(*) FROM connections 
    WHERE (requester_id = ? OR receiver_id = ?) AND status = 'accepted'
");
$stmt->execute([$userId, $userId]);
$connectionsCount = $stmt->fetchColumn();

// Get unread notifications count
$stmt = $db->prepare("
    SELECT COUNT(*) FROM notifications 
    WHERE user_id = ? AND is_read = 0
");
$stmt->execute([$userId]);
$unreadNotifications = $stmt->fetchColumn();

// Get pending collaboration invitations
$stmt = $db->prepare("
    SELECT COUNT(*) FROM study_collaborators 
    WHERE user_id = ? AND status = 'pending'
");
$stmt->execute([$userId]);
$pendingInvitations = $stmt->fetchColumn();

// Get recent studies
$stmt = $db->prepare("
    SELECT s.*, 
           (SELECT COUNT(*) FROM study_collaborators WHERE study_id = s.id AND status = 'active') as collaborators_count
    FROM studies s
    WHERE s.creator_id = ?
    ORDER BY s.updated_at DESC
    LIMIT 5
");
$stmt->execute([$userId]);
$recentStudies = $stmt->fetchAll();

// Get recent notifications
$stmt = $db->prepare("
    SELECT * FROM notifications 
    WHERE user_id = ? 
    ORDER BY created_at DESC 
    LIMIT 5
");
$stmt->execute([$userId]);
$recentNotifications = $stmt->fetchAll();

// Calculate profile completion
$profileFields = [
    'photo', 'title', 'specialization', 'bio', 'research_interests',
    'orcid_id', 'institution_id', 'department', 'country', 'city'
];
$completedFields = 0;
foreach ($profileFields as $field) {
    if (!empty($profile[$field])) {
        $completedFields++;
    }
}
$profileCompletion = round(($completedFields / count($profileFields)) * 100);

// 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-home"></i> Dashboard
                </h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <a href="create-study.php" class="btn btn-primary">
                        <i class="fas fa-plus"></i> Create New Study
                    </a>
                </div>
            </div>

            <!-- Welcome Message -->
            <div class="alert alert-info alert-dismissible fade show" role="alert">
                <i class="fas fa-info-circle"></i>
                <strong>Welcome back, <?php echo e($profile['first_name']); ?>!</strong>
                <?php if ($profileCompletion < 100): ?>
                    Your profile is <?php echo $profileCompletion; ?>% complete. 
                    <a href="edit-profile.php" class="alert-link">Complete your profile</a> to increase visibility.
                <?php else: ?>
                    Your profile is complete. Great job!
                <?php endif; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>

            <!-- Statistics Cards -->
            <div class="row mb-4">
                <div class="col-xl-3 col-md-6 mb-4">
                    <div class="card border-left-primary shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                        My Studies
                                    </div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $studiesCount; ?></div>
                                </div>
                                <div class="col-auto">
                                    <i class="fas fa-flask fa-2x text-gray-300"></i>
                                </div>
                            </div>
                            <a href="studies.php" class="stretched-link"></a>
                        </div>
                    </div>
                </div>

                <div class="col-xl-3 col-md-6 mb-4">
                    <div class="card border-left-success shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                        Collaborations
                                    </div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $collaborationsCount; ?></div>
                                </div>
                                <div class="col-auto">
                                    <i class="fas fa-users fa-2x text-gray-300"></i>
                                </div>
                            </div>
                            <a href="collaborations.php" class="stretched-link"></a>
                        </div>
                    </div>
                </div>

                <div class="col-xl-3 col-md-6 mb-4">
                    <div class="card border-left-info shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                                        Publications
                                    </div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $publicationsCount; ?></div>
                                </div>
                                <div class="col-auto">
                                    <i class="fas fa-book fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-xl-3 col-md-6 mb-4">
                    <div class="card border-left-warning shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                                        Connections
                                    </div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $connectionsCount; ?></div>
                                </div>
                                <div class="col-auto">
                                    <i class="fas fa-network-wired fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Profile Completion -->
            <?php if ($profileCompletion < 100): ?>
            <div class="card mb-4">
                <div class="card-header">
                    <i class="fas fa-tasks"></i> Profile Completion
                </div>
                <div class="card-body">
                    <div class="d-flex justify-content-between mb-2">
                        <span>Complete your profile to increase visibility</span>
                        <span class="fw-bold"><?php echo $profileCompletion; ?>%</span>
                    </div>
                    <div class="progress" style="height: 25px;">
                        <div class="progress-bar <?php echo $profileCompletion >= 75 ? 'bg-success' : ($profileCompletion >= 50 ? 'bg-info' : 'bg-warning'); ?>" 
                             role="progressbar" 
                             style="width: <?php echo $profileCompletion; ?>%"
                             aria-valuenow="<?php echo $profileCompletion; ?>" 
                             aria-valuemin="0" 
                             aria-valuemax="100">
                            <?php echo $profileCompletion; ?>%
                        </div>
                    </div>
                    <div class="mt-3">
                        <a href="edit-profile.php" class="btn btn-sm btn-primary">
                            <i class="fas fa-edit"></i> Complete Profile
                        </a>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <div class="row">
                <!-- Recent Studies -->
                <div class="col-lg-8 mb-4">
                    <div class="card shadow">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h6 class="m-0 font-weight-bold text-primary">
                                <i class="fas fa-flask"></i> Recent Studies
                            </h6>
                            <a href="studies.php" class="btn btn-sm btn-outline-primary">View All</a>
                        </div>
                        <div class="card-body">
                            <?php if (empty($recentStudies)): ?>
                                <div class="text-center py-4">
                                    <i class="fas fa-flask fa-3x text-muted mb-3"></i>
                                    <p class="text-muted">No studies yet. Create your first study!</p>
                                    <a href="create-study.php" class="btn btn-primary">
                                        <i class="fas fa-plus"></i> Create Study
                                    </a>
                                </div>
                            <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-hover">
                                        <thead>
                                            <tr>
                                                <th>Title</th>
                                                <th>Type</th>
                                                <th>Status</th>
                                                <th>Collaborators</th>
                                                <th>Updated</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($recentStudies as $study): ?>
                                            <tr>
                                                <td>
                                                    <a href="edit-study.php?id=<?php echo $study['id']; ?>">
                                                        <?php echo e(substr($study['title'], 0, 50)); ?>
                                                        <?php echo strlen($study['title']) > 50 ? '...' : ''; ?>
                                                    </a>
                                                </td>
                                                <td>
                                                    <span class="badge bg-secondary">
                                                        <?php echo ucfirst($study['type']); ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <?php
                                                    $statusColors = [
                                                        'draft' => 'secondary',
                                                        'active' => 'success',
                                                        'completed' => 'info',
                                                        'archived' => 'dark',
                                                        'pending_approval' => 'warning'
                                                    ];
                                                    $color = $statusColors[$study['status']] ?? 'secondary';
                                                    ?>
                                                    <span class="badge bg-<?php echo $color; ?>">
                                                        <?php echo ucfirst(str_replace('_', ' ', $study['status'])); ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <i class="fas fa-users"></i> <?php echo $study['collaborators_count']; ?>
                                                </td>
                                                <td>
                                                    <small class="text-muted">
                                                        <?php echo timeAgo($study['updated_at']); ?>
                                                    </small>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <!-- Recent Notifications -->
                <div class="col-lg-4 mb-4">
                    <div class="card shadow">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h6 class="m-0 font-weight-bold text-primary">
                                <i class="fas fa-bell"></i> Notifications
                            </h6>
                            <a href="notifications.php" class="btn btn-sm btn-outline-primary">View All</a>
                        </div>
                        <div class="card-body">
                            <?php if (empty($recentNotifications)): ?>
                                <div class="text-center py-4">
                                    <i class="fas fa-bell-slash fa-2x text-muted mb-2"></i>
                                    <p class="text-muted mb-0">No notifications</p>
                                </div>
                            <?php else: ?>
                                <div class="list-group list-group-flush">
                                    <?php foreach ($recentNotifications as $notification): ?>
                                    <a href="<?php echo $notification['link'] ?? 'notifications.php'; ?>" 
                                       class="list-group-item list-group-item-action <?php echo $notification['is_read'] ? '' : 'bg-light'; ?>">
                                        <div class="d-flex w-100 justify-content-between">
                                            <h6 class="mb-1"><?php echo e($notification['title']); ?></h6>
                                            <small class="text-muted"><?php echo timeAgo($notification['created_at']); ?></small>
                                        </div>
                                        <p class="mb-1 small"><?php echo e(substr($notification['message'], 0, 80)); ?>...</p>
                                    </a>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Quick Actions -->
                    <div class="card shadow mt-4">
                        <div class="card-header">
                            <h6 class="m-0 font-weight-bold text-primary">
                                <i class="fas fa-bolt"></i> Quick Actions
                            </h6>
                        </div>
                        <div class="card-body">
                            <div class="d-grid gap-2">
                                <a href="create-study.php" class="btn btn-primary">
                                    <i class="fas fa-plus"></i> Create New Study
                                </a>
                                <a href="edit-profile.php" class="btn btn-outline-primary">
                                    <i class="fas fa-user-edit"></i> Edit Profile
                                </a>
                                <a href="messages.php" class="btn btn-outline-primary">
                                    <i class="fas fa-envelope"></i> Send Message
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>



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