<?php
/**
 * Take Survey - Public-facing survey page
 * Research Survey Management System
 */

define('PAGE_TITLE', 'Take Survey');
require_once __DIR__ . '/../config/app.php';
require_once __DIR__ . '/../includes/functions.php';

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

// Get survey (public access may be allowed)
$pdo = getDBConnection();
$stmt = $pdo->prepare("SELECT * FROM surveys WHERE survey_id = :id AND (status = 'active' OR status = 'draft')");
$stmt->execute(['id' => $surveyId]);
$survey = $stmt->fetch();

if (!$survey) {
    die('Survey not found or not available.');
}

// Get questions
$stmt = $pdo->prepare("
    SELECT q.*, 
           GROUP_CONCAT(
               JSON_OBJECT('option_id', o.option_id, 'option_text', o.option_text, 
                          'option_value', o.option_value, 'option_order', o.option_order)
               ORDER BY o.option_order
           ) as options
    FROM survey_questions q
    LEFT JOIN question_options o ON q.question_id = o.question_id
    WHERE q.survey_id = :survey_id
    GROUP BY q.question_id
    ORDER BY q.question_order
");
$stmt->execute(['survey_id' => $surveyId]);
$questions = $stmt->fetchAll();

// Parse options
foreach ($questions as &$q) {
    if ($q['options']) {
        $optionsArray = json_decode('[' . str_replace('}{', '},{', $q['options']) . ']', true);
        $q['options'] = $optionsArray ?: [];
    } else {
        $q['options'] = [];
    }
}

// Handle submission
$submitted = false;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $answers = [];
    foreach ($_POST as $key => $value) {
        if (strpos($key, 'question_') === 0) {
            $qid = str_replace('question_', '', $key);
            $answers[$qid] = $value;
        }
    }
    
    $responseId = saveSurveyResponse($surveyId, $answers);
    
    if ($responseId) {
        // Mark response as completed
        $stmt = $pdo->prepare("UPDATE survey_responses SET status = 'completed', completed_at = NOW(), 
                                time_spent_seconds = :time WHERE response_id = :id");
        $stmt->execute([
            'time' => $_POST['time_spent'] ?? 0,
            'id' => $responseId
        ]);
        
        // Update participant
        $stmt = $pdo->prepare("UPDATE survey_participants SET status = 'completed', completed_at = NOW(), 
                                time_spent_seconds = :time WHERE participant_id = (
                                    SELECT participant_id FROM survey_responses WHERE response_id = :rid
                                )");
        $stmt->execute([
            'time' => $_POST['time_spent'] ?? 0,
            'rid' => $responseId
        ]);
        
        $submitted = true;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($survey['title']); ?> - <?php echo APP_NAME; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background: #f8f9fa;
            min-height: 100vh;
        }
        .survey-container {
            max-width: 800px;
            margin: 2rem auto;
        }
        .survey-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 2rem;
            border-radius: 15px 15px 0 0;
        }
        .survey-body {
            background: white;
            padding: 2rem;
            border-radius: 0 0 15px 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .question-card {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 10px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
        }
        .question-card:last-child {
            margin-bottom: 0;
        }
        .required-star {
            color: #dc3545;
        }
        .rating-option {
            cursor: pointer;
            transition: all 0.2s;
        }
        .rating-option:hover {
            transform: scale(1.1);
        }
        .rating-option input:checked + label {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }
        .rating-option label {
            display: inline-block;
            width: 45px;
            height: 45px;
            line-height: 45px;
            text-align: center;
            border: 2px solid #dee2e6;
            border-radius: 50%;
            margin: 0 3px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
        }
        .rating-option label:hover {
            background: #e9ecef;
        }
        .progress-bar-custom {
            height: 5px;
            background: #e9ecef;
            border-radius: 3px;
            margin-bottom: 1.5rem;
        }
        .progress-fill {
            height: 100%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 3px;
            transition: width 0.3s ease;
        }
    </style>
</head>
<body>
    <div class="container survey-container">
        <?php if ($submitted): ?>
        <!-- Thank You Message -->
        <div class="card border-0 shadow">
            <div class="card-body text-center py-5">
                <i class="fas fa-check-circle text-success fa-5x mb-3"></i>
                <h2><?php echo htmlspecialchars($survey['thank_you_message'] ?? 'Thank you for completing the survey!'); ?></h2>
                <p class="text-muted">Your responses have been recorded.</p>
                <a href="<?php echo BASE_URL; ?>" class="btn btn-primary mt-2">
                    <i class="fas fa-home me-1"></i> Return Home
                </a>
            </div>
        </div>
        <?php else: ?>
        
        <form method="POST" id="surveyForm" enctype="multipart/form-data">
            <input type="hidden" name="time_spent" id="timeSpent" value="0">
            
            <!-- Survey Header -->
            <div class="survey-header text-center">
                <i class="fas fa-poll fa-3x mb-3"></i>
                <h2><?php echo htmlspecialchars($survey['title']); ?></h2>
                <?php if ($survey['description']): ?>
                <p class="mb-0 opacity-75"><?php echo nl2br(htmlspecialchars($survey['description'])); ?></p>
                <?php endif; ?>
            </div>
            
            <!-- Survey Body -->
            <div class="survey-body">
                <?php if ($survey['welcome_message']): ?>
                <div class="alert alert-info">
                    <i class="fas fa-info-circle me-2"></i><?php echo nl2br(htmlspecialchars($survey['welcome_message'])); ?>
                </div>
                <?php endif; ?>
                
                <div class="progress-bar-custom">
                    <div class="progress-fill" id="progressFill" style="width: 0%"></div>
                </div>
                
                <?php foreach ($questions as $index => $q): ?>
                <div class="question-card" data-question-id="<?php echo $q['question_id']; ?>">
                    <h6 class="fw-bold mb-3">
                        <span class="badge bg-primary me-2"><?php echo $index + 1; ?></span>
                        <?php echo htmlspecialchars($q['question_text']); ?>
                        <?php if ($q['is_required']): ?>
                        <span class="required-star">*</span>
                        <?php endif; ?>
                    </h6>
                    
                    <?php if ($q['help_text']): ?>
                    <small class="text-muted d-block mb-2"><?php echo htmlspecialchars($q['help_text']); ?></small>
                    <?php endif; ?>
                    
                    <!-- Rating Scale -->
                    <?php if ($q['question_type'] === 'rating_scale'): ?>
                    <div class="text-center">
                        <div class="d-flex justify-content-center gap-1 rating-group">
                            <?php for ($i = 1; $i <= 10; $i++): ?>
                            <div class="rating-option">
                                <input type="radio" class="d-none" name="question_<?php echo $q['question_id']; ?>" 
                                       value="<?php echo $i; ?>" id="q<?php echo $q['question_id']; ?>_<?php echo $i; ?>"
                                       <?php echo $q['is_required'] ? 'required' : ''; ?>>
                                <label for="q<?php echo $q['question_id']; ?>_<?php echo $i; ?>"><?php echo $i; ?></label>
                            </div>
                            <?php endfor; ?>
                        </div>
                        <div class="d-flex justify-content-between small text-muted mt-1">
                            <span>Very Dissatisfied</span>
                            <span>Very Satisfied</span>
                        </div>
                    </div>
                    
                    <!-- Likert Scale -->
                    <?php elseif ($q['question_type'] === 'likert_scale'): ?>
                    <div class="table-responsive">
                        <table class="table table-sm table-borderless mb-0">
                            <thead class="text-center small text-muted">
                                <tr>
                                    <th style="width:20%">Strongly Disagree</th>
                                    <th style="width:20%">Disagree</th>
                                    <th style="width:20%">Neutral</th>
                                    <th style="width:20%">Agree</th>
                                    <th style="width:20%">Strongly Agree</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr class="text-center">
                                    <?php for ($i = 1; $i <= 5; $i++): ?>
                                    <td>
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" 
                                                   name="question_<?php echo $q['question_id']; ?>" 
                                                   value="<?php echo $i; ?>" 
                                                   id="q<?php echo $q['question_id']; ?>_<?php echo $i; ?>"
                                                   <?php echo $q['is_required'] ? 'required' : ''; ?>>
                                        </div>
                                    </td>
                                    <?php endfor; ?>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- Yes/No -->
                    <?php elseif ($q['question_type'] === 'yes_no'): ?>
                    <div class="d-flex gap-3">
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="question_<?php echo $q['question_id']; ?>" 
                                   value="1" id="q<?php echo $q['question_id']; ?>_yes"
                                   <?php echo $q['is_required'] ? 'required' : ''; ?>>
                            <label class="form-check-label" for="q<?php echo $q['question_id']; ?>_yes">Yes</label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="question_<?php echo $q['question_id']; ?>" 
                                   value="0" id="q<?php echo $q['question_id']; ?>_no">
                            <label class="form-check-label" for="q<?php echo $q['question_id']; ?>_no">No</label>
                        </div>
                    </div>
                    
                    <!-- Multiple Choice Single -->
                    <?php elseif ($q['question_type'] === 'multiple_choice_single' || $q['question_type'] === 'dropdown'): ?>
                    <select class="form-select" name="question_<?php echo $q['question_id']; ?>" 
                            <?php echo $q['is_required'] ? 'required' : ''; ?>>
                        <option value="">-- Select an option --</option>
                        <?php foreach ($q['options'] as $opt): ?>
                        <option value="<?php echo htmlspecialchars($opt['option_value'] ?: $opt['option_text']); ?>">
                            <?php echo htmlspecialchars($opt['option_text']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                    
                    <!-- Multiple Choice Multiple -->
                    <?php elseif ($q['question_type'] === 'multiple_choice_multiple'): ?>
                    <?php foreach ($q['options'] as $opt): ?>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" 
                               name="question_<?php echo $q['question_id']; ?>[]" 
                               value="<?php echo htmlspecialchars($opt['option_value'] ?: $opt['option_text']); ?>"
                               id="q<?php echo $q['question_id']; ?>_opt<?php echo $opt['option_id']; ?>">
                        <label class="form-check-label" for="q<?php echo $q['question_id']; ?>_opt<?php echo $opt['option_id']; ?>">
                            <?php echo htmlspecialchars($opt['option_text']); ?>
                        </label>
                    </div>
                    <?php endforeach; ?>
                    
                    <!-- Numerical Input -->
                    <?php elseif ($q['question_type'] === 'numerical'): ?>
                    <input type="number" class="form-control" name="question_<?php echo $q['question_id']; ?>" 
                           placeholder="Enter a number" step="any"
                           <?php echo $q['is_required'] ? 'required' : ''; ?>>
                    
                    <!-- Date -->
                    <?php elseif ($q['question_type'] === 'date'): ?>
                    <input type="date" class="form-control" name="question_<?php echo $q['question_id']; ?>"
                           <?php echo $q['is_required'] ? 'required' : ''; ?>>
                    
                    <!-- Time -->
                    <?php elseif ($q['question_type'] === 'time'): ?>
                    <input type="time" class="form-control" name="question_<?php echo $q['question_id']; ?>"
                           <?php echo $q['is_required'] ? 'required' : ''; ?>>
                    
                    <!-- Short Text -->
                    <?php elseif ($q['question_type'] === 'text_short'): ?>
                    <input type="text" class="form-control" name="question_<?php echo $q['question_id']; ?>" 
                           placeholder="Enter your answer" maxlength="255"
                           <?php echo $q['is_required'] ? 'required' : ''; ?>>
                    
                    <!-- Long Text -->
                    <?php elseif ($q['question_type'] === 'text_long'): ?>
                    <textarea class="form-control" name="question_<?php echo $q['question_id']; ?>" 
                              rows="4" placeholder="Enter your detailed answer"
                              <?php echo $q['is_required'] ? 'required' : ''; ?>></textarea>
                    
                    <!-- Rich Text -->
                    <?php elseif ($q['question_type'] === 'rich_text'): ?>
                    <textarea class="form-control rich-text" name="question_<?php echo $q['question_id']; ?>" 
                              rows="4" placeholder="Enter your answer (rich text supported)"
                              <?php echo $q['is_required'] ? 'required' : ''; ?>></textarea>
                    
                    <!-- File Upload -->
                    <?php elseif ($q['question_type'] === 'file_upload'): ?>
                    <input type="file" class="form-control" name="question_<?php echo $q['question_id']; ?>"
                           <?php echo $q['is_required'] ? 'required' : ''; ?>>
                    <small class="text-muted">Allowed: JPG, PNG, PDF, DOC, MP3 (Max 10MB)</small>
                    
                    <!-- Ranking -->
                    <?php elseif ($q['question_type'] === 'ranking'): ?>
                    <div class="ranking-container">
                        <?php foreach ($q['options'] as $opt): ?>
                        <div class="input-group mb-2">
                            <span class="input-group-text"><i class="fas fa-grip-vertical"></i></span>
                            <span class="form-control"><?php echo htmlspecialchars($opt['option_text']); ?></span>
                            <select class="form-select" style="max-width:80px" 
                                    name="question_<?php echo $q['question_id']; ?>[<?php echo $opt['option_id']; ?>]">
                                <?php for ($r = 1; $r <= count($q['options']); $r++): ?>
                                <option value="<?php echo $r; ?>"><?php echo $r; ?></option>
                                <?php endfor; ?>
                            </select>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>
                </div>
                <?php endforeach; ?>
                
                <div class="text-center mt-4">
                    <button type="submit" class="btn btn-primary btn-lg px-5">
                        <i class="fas fa-paper-plane me-2"></i>Submit Survey
                    </button>
                </div>
            </div>
        </form>
        <?php endif; ?>
    </div>
    
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const form = document.getElementById('surveyForm');
        const startTime = Date.now();
        const questions = document.querySelectorAll('.question-card');
        const progressFill = document.getElementById('progressFill');
        
        // Track time
        setInterval(() => {
            document.getElementById('timeSpent').value = Math.floor((Date.now() - startTime) / 1000);
        }, 1000);
        
        // Update progress
        function updateProgress() {
            let answered = 0;
            const required = form.querySelectorAll('[required]');
            
            required.forEach(input => {
                if (input.type === 'radio') {
                    const name = input.name;
                    if (form.querySelector(`input[name="${name}"]:checked`)) {
                        answered++;
                    }
                } else if (input.type === 'checkbox') {
                    const name = input.name;
                    if (form.querySelector(`input[name="${name}"]:checked`)) {
                        answered++;
                    }
                } else if (input.value) {
                    answered++;
                }
            });
            
            const totalRequired = [...new Set([...required].map(r => r.name))].length;
            const progress = totalRequired > 0 ? (answered / totalRequired) * 100 : 0;
            progressFill.style.width = Math.min(progress, 100) + '%';
        }
        
        form.addEventListener('change', updateProgress);
        form.addEventListener('input', updateProgress);
    });
    </script>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>