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

define('PAGE_TITLE', 'Create Survey');
require_once __DIR__ . '/../includes/functions.php';
requireRole(['admin', 'researcher']);

$pdo = getDBConnection();
$projects = getProjects();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $error = 'Invalid security token. Please try again.';
    } else {
    try {
        $pdo->beginTransaction();
        
        // Create survey
        $stmt = $pdo->prepare("INSERT INTO surveys (project_id, title, description, survey_type, status, 
                                is_anonymous, requires_login, created_by, welcome_message, thank_you_message) 
                               VALUES (:project_id, :title, :description, :type, 'draft', 
                                       :anonymous, :login, :user_id, :welcome, :thanks)");
        $stmt->execute([
            'project_id' => !empty($_POST['project_id']) ? $_POST['project_id'] : null,
            'title' => sanitize($_POST['title']),
            'description' => sanitize($_POST['description'] ?? ''),
            'type' => $_POST['survey_type'],
            'anonymous' => isset($_POST['is_anonymous']) ? 1 : 0,
            'login' => isset($_POST['requires_login']) ? 1 : 0,
            'user_id' => $_SESSION['user_id'],
            'welcome' => sanitize($_POST['welcome_message'] ?? ''),
            'thanks' => sanitize($_POST['thank_you_message'] ?? '')
        ]);
        
        $surveyId = $pdo->lastInsertId();
        
        // Add questions
        if (isset($_POST['questions']) && is_array($_POST['questions'])) {
            foreach ($_POST['questions'] as $order => $question) {
                $stmt = $pdo->prepare("INSERT INTO survey_questions (survey_id, question_text, question_type, question_order, is_required, help_text)
                                       VALUES (:survey_id, :text, :type, :order, :required, :help)");
                $stmt->execute([
                    'survey_id' => $surveyId,
                    'text' => sanitize($question['text']),
                    'type' => $question['type'],
                    'order' => $order + 1,
                    'required' => isset($question['required']) ? 1 : 0,
                    'help' => sanitize($question['help'] ?? '')
                ]);
                
                $questionId = $pdo->lastInsertId();
                
                // Add options for choice-based questions
                if (in_array($question['type'], ['multiple_choice_single', 'multiple_choice_multiple', 'dropdown', 'ranking']) 
                    && isset($question['options'])) {
                    foreach ($question['options'] as $optOrder => $option) {
                        if (!empty(trim($option['text']))) {
                            $stmt = $pdo->prepare("INSERT INTO question_options (question_id, option_text, option_value, option_order, score_value)
                                                   VALUES (:qid, :text, :val, :order, :score)");
                            $stmt->execute([
                                'qid' => $questionId,
                                'text' => sanitize($option['text']),
                                'val' => sanitize($option['value'] ?? ''),
                                'order' => $optOrder + 1,
                                'score' => !empty($option['score']) ? $option['score'] : null
                            ]);
                        }
                    }
                }
            }
        }
        
        logAudit('create', 'survey', $surveyId);
        
        $pdo->commit();
        
        $_SESSION['flash_message'] = 'Survey created successfully!';
        $_SESSION['flash_type'] = 'success';
        header('Location: ' . BASE_URL . '/pages/view_survey.php?id=' . $surveyId);
        exit;
        
    } catch (Exception $e) {
        $pdo->rollBack();
        $error = 'Failed to create survey: ' . $e->getMessage();
    }
    }
}

$questionTypes = [
    'rating_scale' => 'Rating Scale',
    'likert_scale' => 'Likert Scale',
    'multiple_choice_single' => 'Multiple Choice (Single)',
    'multiple_choice_multiple' => 'Multiple Choice (Multiple)',
    'dropdown' => 'Dropdown',
    'ranking' => 'Ranking',
    'yes_no' => 'Yes/No',
    'date' => 'Date',
    'time' => 'Time',
    'numerical' => 'Numerical Input',
    'text_short' => 'Short Text',
    'text_long' => 'Long Text',
    'rich_text' => 'Rich Text',
    'file_upload' => 'File Upload'
];

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

<div class="dashboard-header">
    <div>
        <h1><i class="fas fa-plus-circle me-2 text-primary"></i>Create Survey</h1>
        <p>Design your research survey with multiple question types</p>
    </div>
</div>

<?php if (isset($error)): ?>
<div class="alert alert-danger"><?php echo $error; ?></div>
<?php endif; ?>

<form method="POST" id="surveyForm">
    <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
    <!-- Survey Settings -->
    <div class="card border-0 shadow-sm mb-4">
        <div class="card-header bg-white">
            <h5 class="mb-0"><i class="fas fa-cog me-2 text-primary"></i>Survey Settings</h5>
        </div>
        <div class="card-body">
            <div class="row g-3">
                <div class="col-md-8">
                    <label class="form-label">Survey Title <span class="text-danger">*</span></label>
                    <input type="text" class="form-control form-control-lg" name="title" required
                           placeholder="Enter a descriptive title for your survey">
                </div>
                <div class="col-md-4">
                    <label class="form-label">Project (Optional)</label>
                    <select class="form-select" name="project_id">
                        <option value="">No Project</option>
                        <?php foreach ($projects as $project): ?>
                        <option value="<?php echo $project['project_id']; ?>">
                            <?php echo htmlspecialchars($project['project_name']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-4">
                    <label class="form-label">Survey Type <span class="text-danger">*</span></label>
                    <select class="form-select" name="survey_type" required>
                        <option value="quantitative">Quantitative</option>
                        <option value="qualitative">Qualitative</option>
                        <option value="mixed">Mixed Methods</option>
                    </select>
                </div>
                <div class="col-md-8">
                    <label class="form-label">Description</label>
                    <textarea class="form-control" name="description" rows="2" 
                              placeholder="Brief description of the survey purpose"></textarea>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Welcome Message</label>
                    <textarea class="form-control" name="welcome_message" rows="2"
                              placeholder="Message shown to participants before starting"></textarea>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Thank You Message</label>
                    <textarea class="form-control" name="thank_you_message" rows="2"
                              placeholder="Message shown after survey completion"></textarea>
                </div>
                <div class="col-12">
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="checkbox" name="is_anonymous" id="isAnonymous">
                        <label class="form-check-label" for="isAnonymous">
                            <i class="fas fa-user-secret me-1"></i> Anonymous Responses
                        </label>
                    </div>
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="checkbox" name="requires_login" id="requiresLogin" checked>
                        <label class="form-check-label" for="requiresLogin">
                            <i class="fas fa-lock me-1"></i> Requires Login
                        </label>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Questions Builder -->
    <div class="card border-0 shadow-sm mb-4">
        <div class="card-header bg-white d-flex justify-content-between align-items-center">
            <h5 class="mb-0"><i class="fas fa-list me-2 text-primary"></i>Questions</h5>
            <button type="button" class="btn btn-primary btn-sm" onclick="addQuestion()">
                <i class="fas fa-plus me-1"></i> Add Question
            </button>
        </div>
        <div class="card-body" id="questionsContainer">
            <div class="text-center py-5 text-muted" id="emptyState">
                <i class="fas fa-plus-circle fa-4x mb-3 d-block"></i>
                <h5>No Questions Yet</h5>
                <p>Click the "Add Question" button to start building your survey</p>
            </div>
        </div>
    </div>
    
    <!-- Submit -->
    <div class="d-flex justify-content-between mb-5">
        <a href="<?php echo BASE_URL; ?>/pages/surveys.php" class="btn btn-secondary">
            <i class="fas fa-arrow-left me-1"></i> Cancel
        </a>
        <button type="submit" class="btn btn-success btn-lg">
            <i class="fas fa-save me-1"></i> Create Survey
        </button>
    </div>
</form>

<!-- Question Template (hidden) -->
<template id="questionTemplate">
    <div class="question-item card bg-light mb-3">
        <div class="card-body">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h6 class="mb-0 question-number">Question 1</h6>
                <div>
                    <button type="button" class="btn btn-outline-secondary btn-sm" onclick="moveQuestion(this, -1)" title="Move Up">
                        <i class="fas fa-chevron-up"></i>
                    </button>
                    <button type="button" class="btn btn-outline-secondary btn-sm" onclick="moveQuestion(this, 1)" title="Move Down">
                        <i class="fas fa-chevron-down"></i>
                    </button>
                    <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeQuestion(this)" title="Remove">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
            <div class="row g-3">
                <div class="col-md-8">
                    <label class="form-label">Question Text <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" name="questions[0][text]" required
                           placeholder="Enter your question">
                </div>
                <div class="col-md-4">
                    <label class="form-label">Question Type</label>
                    <select class="form-select question-type" name="questions[0][type]" onchange="toggleOptions(this)">
                        <?php foreach ($questionTypes as $key => $label): ?>
                        <option value="<?php echo $key; ?>"><?php echo $label; ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-8">
                    <label class="form-label">Help Text (Optional)</label>
                    <input type="text" class="form-control" name="questions[0][help]" 
                           placeholder="Additional guidance for respondents">
                </div>
                <div class="col-md-4 d-flex align-items-end">
                    <div class="form-check mb-2">
                        <input class="form-check-input" type="checkbox" name="questions[0][required]" checked>
                        <label class="form-check-label">Required</label>
                    </div>
                </div>
            </div>
            <div class="question-options mt-3" style="display:none;">
                <label class="form-label">Options</label>
                <div class="options-container">
                    <div class="input-group mb-2">
                        <input type="text" class="form-control" name="questions[0][options][0][text]" 
                               placeholder="Option text">
                        <input type="text" class="form-control" name="questions[0][options][0][value]" 
                               placeholder="Value (optional)" style="max-width:150px">
                        <button type="button" class="btn btn-success btn-sm" onclick="addOption(this)">
                            <i class="fas fa-plus"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
let questionCount = 0;

function addQuestion() {
    const template = document.getElementById('questionTemplate');
    const clone = template.content.cloneNode(true);
    const questionDiv = clone.querySelector('.question-item');
    
    // Update indices
    const inputs = questionDiv.querySelectorAll('[name]');
    inputs.forEach(input => {
        input.name = input.name.replace('[0]', `[${questionCount}]`);
    });
    
    questionDiv.querySelector('.question-number').textContent = `Question ${questionCount + 1}`;
    
    const container = document.getElementById('questionsContainer');
    container.appendChild(questionDiv);
    
    // Hide empty state
    document.getElementById('emptyState').style.display = 'none';
    
    questionCount++;
    updateQuestionNumbers();
}

function removeQuestion(btn) {
    btn.closest('.question-item').remove();
    updateQuestionNumbers();
    
    if (document.querySelectorAll('.question-item').length === 0) {
        document.getElementById('emptyState').style.display = '';
        questionCount = 0;
    }
}

function moveQuestion(btn, direction) {
    const item = btn.closest('.question-item');
    const container = document.getElementById('questionsContainer');
    const items = [...container.querySelectorAll('.question-item')];
    const index = items.indexOf(item);
    
    if (direction === -1 && index > 0) {
        container.insertBefore(item, items[index - 1]);
    } else if (direction === 1 && index < items.length - 1) {
        container.insertBefore(items[index + 1], item);
    }
    
    updateQuestionNumbers();
}

function updateQuestionNumbers() {
    const items = document.querySelectorAll('.question-item');
    items.forEach((item, index) => {
        item.querySelector('.question-number').textContent = `Question ${index + 1}`;
    });
}

function toggleOptions(select) {
    const optionsDiv = select.closest('.question-item').querySelector('.question-options');
    const type = select.value;
    const typesWithOptions = ['multiple_choice_single', 'multiple_choice_multiple', 'dropdown', 'ranking'];
    
    optionsDiv.style.display = typesWithOptions.includes(type) ? 'block' : 'none';
}

function addOption(btn) {
    const container = btn.closest('.options-container');
    const questionItem = btn.closest('.question-item');
    const questionIndex = [...document.querySelectorAll('.question-item')].indexOf(questionItem);
    const optionCount = container.querySelectorAll('.input-group').length;
    
    const div = document.createElement('div');
    div.className = 'input-group mb-2';
    div.innerHTML = `
        <input type="text" class="form-control" name="questions[${questionIndex}][options][${optionCount}][text]" 
               placeholder="Option text">
        <input type="text" class="form-control" name="questions[${questionIndex}][options][${optionCount}][value]" 
               placeholder="Value (optional)" style="max-width:150px">
        <button type="button" class="btn btn-danger btn-sm" onclick="this.parentElement.remove()">
            <i class="fas fa-times"></i>
        </button>
    `;
    
    container.appendChild(div);
}
</script>

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