<?php
/**
 * Project Detail Page
 * Research Survey Management System
 */

define('PAGE_TITLE', 'Project Detail');
require_once __DIR__ . '/../includes/functions.php';
requireAuth();

$projectId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$pdo = getDBConnection();

$stmt = $pdo->prepare("SELECT * FROM research_projects WHERE project_id = :id");
$stmt->execute(['id' => $projectId]);
$project = $stmt->fetch();

if (!$project || !hasProjectAccess($projectId)) {
    $_SESSION['flash_message'] = 'Project not found or insufficient permissions.';
    $_SESSION['flash_type'] = 'danger';
    header('Location: ' . BASE_URL . '/pages/projects.php');
    exit;
}

$isOwner = hasProjectAccess($projectId, 'owner');

// Handle member addition
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_member' && $isOwner) {
    $userId = isset($_POST['user_id']) ? (int)$_POST['user_id'] : 0;
    $role = $_POST['role'] ?? 'viewer';
    
    if ($userId) {
        addProjectMember($projectId, $userId, $role);
        logAudit('update', 'project_member', $projectId, null, ['user_id' => $userId, 'role' => $role]);
        $_SESSION['flash_message'] = 'Member added successfully!';
        $_SESSION['flash_type'] = 'success';
        header('Location: ' . BASE_URL . '/pages/project_detail.php?id=' . $projectId);
        exit;
    }
}

// Handle member removal
if (isset($_GET['remove_member']) && $isOwner) {
    $removeId = (int)$_GET['remove_member'];
    $stmt = $pdo->prepare("DELETE FROM project_members WHERE project_member_id = :mid AND project_id = :pid 
                           AND user_id != :owner");
    $stmt->execute(['mid' => $removeId, 'pid' => $projectId, 'owner' => $project['created_by']]);
    logAudit('delete', 'project_member', $removeId);
    $_SESSION['flash_message'] = 'Member removed successfully!';
    $_SESSION['flash_type'] = 'success';
    header('Location: ' . BASE_URL . '/pages/project_detail.php?id=' . $projectId);
    exit;
}

// Get project members
$members = getProjectMembers($projectId);

// Get all users for adding members
$stmt = $pdo->prepare("SELECT user_id, username, email, full_name, role FROM users WHERE is_active = 1 AND user_id != :owner");
$stmt->execute(['owner' => $_SESSION['user_id']]);
$allUsers = $stmt->fetchAll();

// Get project surveys
$stmt = $pdo->prepare("SELECT s.*, u.full_name as creator_name,
                       COUNT(DISTINCT sr.response_id) as response_count
                       FROM surveys s
                       JOIN users u ON s.created_by = u.user_id
                       LEFT JOIN survey_responses sr ON s.survey_id = sr.survey_id
                       WHERE s.project_id = :pid
                       GROUP BY s.survey_id
                       ORDER BY s.created_at DESC");
$stmt->execute(['pid' => $projectId]);
$surveys = $stmt->fetchAll();

require_once __DIR__ . '/../includes/header.php';
?>

<div class="dashboard-header">
    <div>
        <a href="<?php echo BASE_URL; ?>/pages/projects.php" class="text-decoration-none text-muted small">
            <i class="fas fa-arrow-left me-1"></i> Back to Projects
        </a>
        <h1 class="mt-1"><?php echo htmlspecialchars($project['project_name']); ?></h1>
        <p><?php echo getStatusBadge($project['status']); ?>
           <span class="ms-2 text-muted"><?php echo htmlspecialchars($project['description'] ?? 'No description'); ?></span>
        </p>
    </div>
    <div>
        <a href="<?php echo BASE_URL; ?>/pages/surveys.php?project_id=<?php echo $projectId; ?>" class="btn btn-primary">
            <i class="fas fa-poll me-1"></i> View Surveys
        </a>
    </div>
</div>

<div class="row g-3 mb-4">
    <!-- Project Info -->
    <div class="col-md-4">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-header bg-white">
                <h5 class="mb-0"><i class="fas fa-info-circle me-2 text-primary"></i>Project Information</h5>
            </div>
            <div class="card-body">
                <div class="mb-2">
                    <small class="text-muted d-block">Created By</small>
                    <strong><?php echo htmlspecialchars($project['created_by_name'] ?? 'N/A'); ?></strong>
                </div>
                <div class="mb-2">
                    <small class="text-muted d-block">Created</small>
                    <strong><?php echo formatDate($project['created_at']); ?></strong>
                </div>
                <?php if ($project['start_date']): ?>
                <div class="mb-2">
                    <small class="text-muted d-block">Start Date</small>
                    <strong><?php echo formatDate($project['start_date'], 'M d, Y'); ?></strong>
                </div>
                <?php endif; ?>
                <?php if ($project['end_date']): ?>
                <div class="mb-2">
                    <small class="text-muted d-block">End Date</small>
                    <strong><?php echo formatDate($project['end_date'], 'M d, Y'); ?></strong>
                </div>
                <?php endif; ?>
                <?php if ($project['methodology_notes']): ?>
                <div class="mt-3 p-3 bg-light rounded">
                    <small class="text-muted d-block mb-1"><i class="fas fa-flask me-1"></i>Methodology</small>
                    <?php echo nl2br(htmlspecialchars($project['methodology_notes'])); ?>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <!-- Members -->
    <div class="col-md-4">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-header bg-white d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="fas fa-users me-2 text-success"></i>Members (<?php echo count($members); ?>)</h5>
                <?php if ($isOwner): ?>
                <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#addMemberModal">
                    <i class="fas fa-plus me-1"></i> Add
                </button>
                <?php endif; ?>
            </div>
            <div class="card-body p-0">
                <div class="list-group list-group-flush">
                    <?php foreach ($members as $member): ?>
                    <div class="list-group-item d-flex justify-content-between align-items-center">
                        <div>
                            <strong><?php echo htmlspecialchars($member['full_name']); ?></strong>
                            <br><small class="text-muted"><?php echo htmlspecialchars($member['email']); ?></small>
                        </div>
                        <div class="text-end">
                            <span class="badge bg-<?php echo $member['role_in_project'] === 'owner' ? 'warning' : 'info'; ?>">
                                <?php echo ucfirst($member['role_in_project']); ?>
                            </span>
                            <?php if ($isOwner && $member['role_in_project'] !== 'owner'): ?>
                            <br><a href="?id=<?php echo $projectId; ?>&remove_member=<?php echo $member['project_member_id']; ?>" 
                                   class="small text-danger text-decoration-none"
                                   onclick="return confirm('Remove this member?')">Remove</a>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Stats -->
    <div class="col-md-4">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-header bg-white">
                <h5 class="mb-0"><i class="fas fa-chart-bar me-2 text-warning"></i>Project Statistics</h5>
            </div>
            <div class="card-body text-center">
                <div class="row g-2">
                    <div class="col-6">
                        <h3 class="text-primary mb-0"><?php echo count($surveys); ?></h3>
                        <small class="text-muted">Surveys</small>
                    </div>
                    <div class="col-6">
                        <h3 class="text-success mb-0">
                            <?php echo array_sum(array_column($surveys, 'response_count')); ?>
                        </h3>
                        <small class="text-muted">Responses</small>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Surveys -->
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white">
        <h5 class="mb-0"><i class="fas fa-poll me-2 text-primary"></i>Surveys in this Project</h5>
    </div>
    <div class="card-body p-0">
        <?php if (empty($surveys)): ?>
        <div class="text-center py-5 text-muted">
            <i class="fas fa-inbox fa-3x mb-3 d-block"></i>
            <p class="mb-0">No surveys in this project yet</p>
            <a href="<?php echo BASE_URL; ?>/pages/create_survey.php?project_id=<?php echo $projectId; ?>" 
               class="btn btn-sm btn-primary mt-2">Create Survey</a>
        </div>
        <?php else: ?>
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead class="table-light">
                    <tr>
                        <th>Title</th>
                        <th>Type</th>
                        <th>Status</th>
                        <th>Responses</th>
                        <th>Created</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($surveys as $s): ?>
                    <tr>
                        <td><a href="<?php echo BASE_URL; ?>/pages/view_survey.php?id=<?php echo $s['survey_id']; ?>" 
                               class="text-decoration-none"><?php echo htmlspecialchars($s['title']); ?></a></td>
                        <td><span class="badge bg-info text-capitalize"><?php echo $s['survey_type']; ?></span></td>
                        <td><?php echo getStatusBadge($s['status']); ?></td>
                        <td><?php echo $s['response_count']; ?></td>
                        <td><small><?php echo formatDate($s['created_at'], 'M d, Y'); ?></small></td>
                        <td>
                            <a href="<?php echo BASE_URL; ?>/pages/analytics.php?survey_id=<?php echo $s['survey_id']; ?>" 
                               class="btn btn-sm btn-outline-success"><i class="fas fa-chart-bar"></i></a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Add Member Modal -->
<?php if ($isOwner): ?>
<div class="modal fade" id="addMemberModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="action" value="add_member">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-user-plus me-2 text-primary"></i>Add Team Member</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Select User</label>
                        <select class="form-select" name="user_id" required>
                            <option value="">-- Choose a user --</option>
                            <?php foreach ($allUsers as $user): ?>
                            <option value="<?php echo $user['user_id']; ?>">
                                <?php echo htmlspecialchars($user['full_name']); ?> (<?php echo htmlspecialchars($user['email']); ?>)
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Role</label>
                        <select class="form-select" name="role">
                            <option value="researcher">Researcher</option>
                            <option value="analyst">Analyst</option>
                            <option value="viewer">Viewer</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-user-plus me-1"></i> Add Member
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php endif; ?>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
