<?php
/**
 * View Survey Page
 * Research Survey Management System
 */

define('PAGE_TITLE', 'View Survey');
require_once __DIR__ . '/../includes/functions.php';
requireAuth();

$surveyId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$survey = getSurveyWithQuestions($surveyId);

if (!$survey) {
    $_SESSION['flash_message'] = 'Survey not found.';
    $_SESSION['flash_type'] = 'danger';
    header('Location: ' . BASE_URL . '/pages/surveys.php');
    exit;
}

$pdo = getDBConnection();

// Get analytics
$analytics = getSurveyAnalytics($surveyId);

// Get responses
$stmt = $pdo->prepare("
    SELECT COUNT(*) as total,
           SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed,
           SUM(CASE WHEN status = 'in_progress' THEN 1 ELSE 0 END) as in_progress
    FROM survey_responses 
    WHERE survey_id = :sid
");
$stmt->execute(['sid' => $surveyId]);
$responseStats = $stmt->fetch();

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

<div class="dashboard-header">
    <div>
        <a href="<?php echo BASE_URL; ?>/pages/surveys.php" class="text-decoration-none text-muted small">
            <i class="fas fa-arrow-left me-1"></i> Back to Surveys
        </a>
        <h1 class="mt-1"><?php echo htmlspecialchars($survey['title']); ?></h1>
        <p>
            <?php echo getStatusBadge($survey['status']); ?>
            <span class="ms-2 badge bg-info text-capitalize"><?php echo $survey['survey_type']; ?></span>
            <?php if ($survey['is_anonymous']): ?>
            <span class="ms-2 badge bg-secondary"><i class="fas fa-user-secret me-1"></i>Anonymous</span>
            <?php endif; ?>
        </p>
    </div>
    <div>
        <a href="<?php echo BASE_URL; ?>/pages/edit_survey.php?id=<?php echo $surveyId; ?>" class="btn btn-outline-primary">
            <i class="fas fa-edit me-1"></i> Edit
        </a>
        <a href="<?php echo BASE_URL; ?>/pages/analytics.php?survey_id=<?php echo $surveyId; ?>" class="btn btn-outline-success">
            <i class="fas fa-chart-bar me-1"></i> Analytics
        </a>
        <a href="<?php echo BASE_URL; ?>/pages/take_survey.php?id=<?php echo $surveyId; ?>" class="btn btn-primary" target="_blank">
            <i class="fas fa-external-link-alt me-1"></i> Preview
        </a>
    </div>
</div>

<div class="row g-3 mb-4">
    <div class="col-md-8">
        <!-- Survey Info -->
        <div class="card border-0 shadow-sm mb-3">
            <div class="card-header bg-white">
                <h5 class="mb-0"><i class="fas fa-info-circle me-2 text-primary"></i>Survey Information</h5>
            </div>
            <div class="card-body">
                <?php if ($survey['description']): ?>
                <p><?php echo nl2br(htmlspecialchars($survey['description'])); ?></p>
                <?php endif; ?>
                
                <div class="row g-3">
                    <?php if ($survey['project_id']): ?>
                    <div class="col-md-6">
                        <small class="text-muted d-block">Project</small>
                        <strong><?php echo htmlspecialchars($survey['project_name'] ?? 'N/A'); ?></strong>
                    </div>
                    <?php endif; ?>
                    <div class="col-md-6">
                        <small class="text-muted d-block">Created By</small>
                        <strong><?php echo htmlspecialchars($survey['creator_name'] ?? 'N/A'); ?></strong>
                    </div>
                    <div class="col-md-6">
                        <small class="text-muted d-block">Created</small>
                        <strong><?php echo formatDate($survey['created_at']); ?></strong>
                    </div>
                    <div class="col-md-6">
                        <small class="text-muted d-block">Last Updated</small>
                        <strong><?php echo formatDate($survey['updated_at']); ?></strong>
                    </div>
                </div>
                
                <?php if ($survey['welcome_message']): ?>
                <div class="mt-3 p-3 bg-light rounded">
                    <small class="text-muted d-block mb-1"><i class="fas fa-hand-peace me-1"></i>Welcome Message</small>
                    <?php echo nl2br(htmlspecialchars($survey['welcome_message'])); ?>
                </div>
                <?php endif; ?>
                
                <?php if ($survey['thank_you_message']): ?>
                <div class="mt-2 p-3 bg-light rounded">
                    <small class="text-muted d-block mb-1"><i class="fas fa-check-circle me-1"></i>Thank You Message</small>
                    <?php echo nl2br(htmlspecialchars($survey['thank_you_message'])); ?>
                </div>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Questions List -->
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white">
                <h5 class="mb-0">
                    <i class="fas fa-list me-2 text-primary"></i>Questions (<?php echo count($survey['questions']); ?>)
                </h5>
            </div>
            <div class="card-body p-0">
                <?php foreach ($survey['questions'] as $index => $question): ?>
                <div class="p-3 border-bottom <?php echo $index === 0 ? '' : ''; ?>">
                    <div class="d-flex justify-content-between">
                        <h6 class="mb-1">
                            <span class="badge bg-primary me-2"><?php echo $index + 1; ?></span>
                            <?php echo htmlspecialchars($question['question_text']); ?>
                            <?php if ($question['is_required']): ?>
                            <span class="text-danger">*</span>
                            <?php endif; ?>
                        </h6>
                        <small class="text-muted text-capitalize"><?php echo str_replace('_', ' ', $question['question_type']); ?></small>
                    </div>
                    
                    <?php if ($question['help_text']): ?>
                    <small class="text-muted d-block mb-2"><?php echo htmlspecialchars($question['help_text']); ?></small>
                    <?php endif; ?>
                    
                    <?php if (!empty($question['options'])): ?>
                    <div class="mt-2">
                        <?php foreach ($question['options'] as $option): ?>
                        <span class="badge bg-light text-dark me-1 mb-1">
                            <?php echo htmlspecialchars($option['option_text'] ?? ''); ?>
                        </span>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
    
    <div class="col-md-4">
        <!-- Response Stats -->
        <div class="card border-0 shadow-sm mb-3">
            <div class="card-header bg-white">
                <h5 class="mb-0"><i class="fas fa-chart-simple me-2 text-success"></i>Response Statistics</h5>
            </div>
            <div class="card-body">
                <div class="text-center mb-3">
                    <h2 class="mb-0 text-success"><?php echo $responseStats['total']; ?></h2>
                    <small class="text-muted">Total Responses</small>
                </div>
                <div class="row text-center">
                    <div class="col-6">
                        <h5 class="text-primary mb-0"><?php echo $responseStats['completed']; ?></h5>
                        <small class="text-muted">Completed</small>
                    </div>
                    <div class="col-6">
                        <h5 class="text-warning mb-0"><?php echo $responseStats['in_progress']; ?></h5>
                        <small class="text-muted">In Progress</small>
                    </div>
                </div>
                <?php if ($analytics): ?>
                <hr>
                <div class="small">
                    <div class="d-flex justify-content-between mb-1">
                        <span class="text-muted">Completion Rate</span>
                        <strong><?php echo number_format($analytics['completion_rate'], 1); ?>%</strong>
                    </div>
                    <div class="d-flex justify-content-between mb-1">
                        <span class="text-muted">Avg. Time</span>
                        <strong><?php echo formatDuration($analytics['average_time_spent']); ?></strong>
                    </div>
                    <div class="d-flex justify-content-between">
                        <span class="text-muted">Last Response</span>
                        <strong><?php echo $analytics['last_response_date'] ? formatDate($analytics['last_response_date'], 'M d') : 'N/A'; ?></strong>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Quick Actions -->
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white">
                <h5 class="mb-0"><i class="fas fa-bolt me-2 text-warning"></i>Quick Actions</h5>
            </div>
            <div class="card-body">
                <div class="d-grid gap-2">
                    <a href="<?php echo BASE_URL; ?>/pages/take_survey.php?id=<?php echo $surveyId; ?>" class="btn btn-primary" target="_blank">
                        <i class="fas fa-external-link-alt me-1"></i> Preview Survey
                    </a>
                    <a href="<?php echo BASE_URL; ?>/pages/analytics.php?survey_id=<?php echo $surveyId; ?>" class="btn btn-success">
                        <i class="fas fa-chart-bar me-1"></i> View Analytics
                    </a>
                    <a href="<?php echo BASE_URL; ?>/api/export_survey.php?id=<?php echo $surveyId; ?>&format=csv" class="btn btn-outline-secondary">
                        <i class="fas fa-file-csv me-1"></i> Export CSV
                    </a>
                    <a href="<?php echo BASE_URL; ?>/api/export_survey.php?id=<?php echo $surveyId; ?>&format=excel" class="btn btn-outline-secondary">
                        <i class="fas fa-file-excel me-1"></i> Export Excel
                    </a>
                    <button class="btn btn-outline-info" onclick="copySurveyLink(<?php echo $surveyId; ?>)">
                        <i class="fas fa-link me-1"></i> Copy Survey Link
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function copySurveyLink(id) {
    const url = `<?php echo BASE_URL; ?>/pages/take_survey.php?id=${id}`;
    navigator.clipboard.writeText(url).then(() => {
        alert('Survey link copied to clipboard!');
    });
}
</script>

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