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

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

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

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

$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();
        
        $stmt = $pdo->prepare("UPDATE surveys SET 
            project_id = :project_id,
            title = :title,
            description = :description,
            survey_type = :type,
            is_anonymous = :anonymous,
            requires_login = :login,
            welcome_message = :welcome,
            thank_you_message = :thanks,
            start_date = :start,
            end_date = :end
            WHERE survey_id = :id");
        $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,
            'welcome' => sanitize($_POST['welcome_message'] ?? ''),
            'thanks' => sanitize($_POST['thank_you_message'] ?? ''),
            'start' => !empty($_POST['start_date']) ? $_POST['start_date'] : null,
            'end' => !empty($_POST['end_date']) ? $_POST['end_date'] : null,
            'id' => $surveyId
        ]);
        
        if (isset($_POST['delete_questions']) && is_array($_POST['delete_questions'])) {
            foreach ($_POST['delete_questions'] as $qid) {
                $stmt = $pdo->prepare("DELETE FROM survey_questions WHERE question_id = :qid AND survey_id = :sid");
                $stmt->execute(['qid' => $qid, 'sid' => $surveyId]);
            }
        }
        
        if (isset($_POST['questions']) && is_array($_POST['questions'])) {
            foreach ($_POST['questions'] as $order => $question) {
                if (isset($question['id']) && !empty($question['id'])) {
                    $stmt = $pdo->prepare("UPDATE survey_questions SET 
                        question_text = :text, question_type = :type, question_order = :order, 
                        is_required = :required, help_text = :help 
                        WHERE question_id = :qid AND survey_id = :sid");
                    $stmt->execute([
                        'text' => sanitize($question['text']),
                        'type' => $question['type'],
                        'order' => $order + 1,
                        'required' => isset($question['required']) ? 1 : 0,
                        'help' => sanitize($question['help'] ?? ''),
                        'qid' => $question['id'],
                        'sid' => $surveyId
                    ]);
                    $questionId = $question['id'];
                } else {
                    $stmt = $pdo->prepare("INSERT INTO survey_questions (survey_id, question_text, question_type, question_order, is_required, help_text)
                                           VALUES (:sid, :text, :type, :order, :required, :help)");
                    $stmt->execute([
                        'sid' => $surveyId,
                        'text' => sanitize($question['text']),
                        'type' => $question['type'],
                        'order' => $order + 1,
                        'required' => isset($question['required']) ? 1 : 0,
                        'help' => sanitize($question['help'] ?? '')
                    ]);
                    $questionId = $pdo->lastInsertId();
                }
                
                if (isset($question['options']) && is_array($question['options'])) {
                    if (isset($question['delete_options']) && is_array($question['delete_options'])) {
                        foreach ($question['delete_options'] as $oid) {
                            $stmt = $pdo->prepare("DELETE FROM question_options WHERE option_id = :oid AND question_id = :qid");
                            $stmt->execute(['oid' => $oid, 'qid' => $questionId]);
                        }
                    }
                    
                    $stmt = $pdo->prepare("DELETE FROM question_options WHERE question_id = :qid");
                    $stmt->execute(['qid' => $questionId]);
                    
                    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('update', 'survey', $surveyId);
        $pdo->commit();
        
        $_SESSION['flash_message'] = 'Survey updated successfully!';
        $_SESSION['flash_type'] = 'success';
        header('Location: ' . BASE_URL . '/pages/view_survey.php?id=' . $surveyId);
        exit;
        
    } catch (Exception $e) {
        $pdo->rollBack();
        $error = 'Failed to update 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>
        <a href="<?php echo BASE_URL; ?>/pages/view_survey.php?id=<?php echo $surveyId; ?>" class="text-decoration-none text-muted small">
            <i class="fas fa-arrow-left me-1"></i> Back to Survey
        </a>
        <h1 class="mt-1">Edit: <?php echo htmlspecialchars($survey['title']); ?></h1>
        <p>Modify survey settings, questions, and options</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
                           value="<?php echo htmlspecialchars($survey['title']); ?>">
                </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 $survey['project_id'] == $project['project_id'] ? 'selected' : ''; ?>>
                            <?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" <?php echo $survey['survey_type'] === 'quantitative' ? 'selected' : ''; ?>>Quantitative</option>
                        <option value="qualitative" <?php echo $survey['survey_type'] === 'qualitative' ? 'selected' : ''; ?>>Qualitative</option>
                        <option value="mixed" <?php echo $survey['survey_type'] === 'mixed' ? 'selected' : ''; ?>>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"><?php echo htmlspecialchars($survey['description']); ?></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"><?php echo htmlspecialchars($survey['welcome_message']); ?></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"><?php echo htmlspecialchars($survey['thank_you_message']); ?></textarea>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Start Date</label>
                    <input type="datetime-local" class="form-control" name="start_date" 
                           value="<?php echo $survey['start_date'] ? date('Y-m-d\TH:i', strtotime($survey['start_date'])) : ''; ?>">
                </div>
                <div class="col-md-6">
                    <label class="form-label">End Date</label>
                    <input type="datetime-local" class="form-control" name="end_date"
                           value="<?php echo $survey['end_date'] ? date('Y-m-d\TH:i', strtotime($survey['end_date'])) : ''; ?>">
                </div>
                <div class="col-12">
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="checkbox" name="is_anonymous" id="isAnonymous" 
                               <?php echo $survey['is_anonymous'] ? 'checked' : ''; ?>>
                        <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"
                               <?php echo $survey['requires_login'] ? '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 (<?php echo count($survey['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">
            <?php foreach ($survey['questions'] as $index => $question): ?>
            <div class="question-item card bg-light mb-3" data-question-id="<?php echo $question['question_id']; ?>">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h6 class="mb-0 question-number">Question <?php echo $index + 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[<?php echo $index; ?>][text]" required
                                   value="<?php echo htmlspecialchars($question['question_text']); ?>">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Question Type</label>
                            <select class="form-select question-type" name="questions[<?php echo $index; ?>][type]" onchange="toggleOptions(this)">
                                <?php foreach ($questionTypes as $key => $label): ?>
                                <option value="<?php echo $key; ?>" <?php echo $question['question_type'] === $key ? 'selected' : ''; ?>>
                                    <?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[<?php echo $index; ?>][help]" 
                                   value="<?php echo htmlspecialchars($question['help_text'] ?? ''); ?>">
                        </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[<?php echo $index; ?>][required]" 
                                       <?php echo $question['is_required'] ? 'checked' : ''; ?>>
                                <label class="form-check-label">Required</label>
                            </div>
                        </div>
                        <input type="hidden" name="questions[<?php echo $index; ?>][id]" value="<?php echo $question['question_id']; ?>">
                    </div>
                    <div class="question-options mt-3" style="display:<?php echo in_array($question['question_type'], ['multiple_choice_single', 'multiple_choice_multiple', 'dropdown', 'ranking']) ? 'block' : 'none'; ?>;">
                        <label class="form-label">Options</label>
                        <div class="options-container">
                            <?php 
                            $optIndex = 0;
                            foreach ($question['options'] as $option): 
                            ?>
                            <div class="input-group mb-2">
                                <input type="text" class="form-control" name="questions[<?php echo $index; ?>][options][<?php echo $optIndex; ?>][text]" 
                                       value="<?php echo htmlspecialchars($option['option_text'] ?? ''); ?>">
                                <input type="text" class="form-control" name="questions[<?php echo $index; ?>][options][<?php echo $optIndex; ?>][value]" 
                                       value="<?php echo htmlspecialchars($option['option_value'] ?? ''); ?>" style="max-width:150px">
                                <input type="hidden" name="questions[<?php echo $index; ?>][options][<?php echo $optIndex; ?>][id]" value="<?php echo $option['option_id']; ?>">
                                <button type="button" class="btn btn-danger btn-sm" onclick="this.parentElement.remove()">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>
                            <?php 
                            $optIndex++;
                            endforeach; 
                            ?>
                        </div>
                        <button type="button" class="btn btn-success btn-sm mt-2" onclick="addOption(this)">
                            <i class="fas fa-plus me-1"></i> Add Option
                        </button>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
            <div id="emptyState" class="text-center py-5 text-muted" style="display:none;">
                <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>
    
    <div class="d-flex justify-content-between mb-5">
        <a href="<?php echo BASE_URL; ?>/pages/view_survey.php?id=<?php echo $surveyId; ?>" 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> Update 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 = <?php echo count($survey['questions']); ?>;

function addQuestion() {
    const template = document.getElementById('questionTemplate');
    const clone = template.content.cloneNode(true);
    const questionDiv = clone.querySelector('.question-item');
    
    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);
    
    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'; ?>
