<?php
require_once 'config/database.php';
require_once 'config/auth.php';
require_once 'includes/functions.php';

$pdo = getDB();
$survey = null;
$questions = [];
$error = '';
$success = '';

$survey_id = (int)($_GET['id'] ?? 0);

if ($survey_id) {
    // Get survey
    $stmt = $pdo->prepare("SELECT * FROM surveys WHERE id = ? AND status = 'active'");
    $stmt->execute([$survey_id]);
    $survey = $stmt->fetch();

    if ($survey) {
        // Get questions
        $stmt = $pdo->prepare("SELECT * FROM survey_questions WHERE survey_id = ? ORDER BY sort_order");
        $stmt->execute([$survey_id]);
        $questions = $stmt->fetchAll();
    }
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $survey) {
    $answers = [];

    foreach ($questions as $question) {
        $answer = $_POST['question_' . $question['id']] ?? '';
        if ($question['question_type'] == 'checkbox') {
            $answer = isset($_POST['question_' . $question['id']]) ? implode(', ', $_POST['question_' . $question['id']]) : '';
        }
        $answers[$question['id']] = $answer;
    }

    // Save response
    $stmt = $pdo->prepare("INSERT INTO survey_responses (survey_id, answers, ip_address) VALUES (?, ?, ?)");
    if ($stmt->execute([$survey_id, json_encode($answers), $_SERVER['REMOTE_ADDR']])) {
        $success = 'Thank you for your response!';
    } else {
        $error = 'Error submitting response.';
    }
}

if (!$survey) {
    header('Location: surveys.php');
    exit;
}

$page_title = htmlspecialchars($survey['title']);
include 'includes/header.php';
?>

<div class="container">
    <div class="survey-page">
        <div class="survey-header">
            <h1><?php echo htmlspecialchars($survey['title']); ?></h1>
            <?php if ($survey['description']): ?>
                <p class="survey-description"><?php echo htmlspecialchars($survey['description']); ?></p>
            <?php endif; ?>
        </div>

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

        <?php if ($success): ?>
            <div class="alert alert-success">
                <?php echo htmlspecialchars($success); ?>
            </div>
        <?php else: ?>
            <?php if (!empty($questions)): ?>
                <form method="POST" class="survey-form">
                    <?php foreach ($questions as $question): ?>
                        <div class="question">
                            <label><?php echo htmlspecialchars($question['question_text']); ?></label>
                            <?php if ($question['question_type'] == 'text'): ?>
                                <textarea name="question_<?php echo $question['id']; ?>" rows="3" required></textarea>
                            <?php elseif ($question['question_type'] == 'radio'): ?>
                                <?php $options = json_decode($question['options'], true) ?: []; ?>
                                <?php foreach ($options as $option): ?>
                                    <label class="radio-option">
                                        <input type="radio" name="question_<?php echo $question['id']; ?>" value="<?php echo htmlspecialchars($option); ?>" required>
                                        <?php echo htmlspecialchars($option); ?>
                                    </label>
                                <?php endforeach; ?>
                            <?php elseif ($question['question_type'] == 'checkbox'): ?>
                                <?php $options = json_decode($question['options'], true) ?: []; ?>
                                <?php foreach ($options as $option): ?>
                                    <label class="checkbox-option">
                                        <input type="checkbox" name="question_<?php echo $question['id']; ?>[]" value="<?php echo htmlspecialchars($option); ?>">
                                        <?php echo htmlspecialchars($option); ?>
                                    </label>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>

                    <div class="form-actions">
                        <button type="submit" class="btn btn-primary">Submit Survey</button>
                    </div>
                </form>
            <?php else: ?>
                <div class="no-questions">
                    <p>No questions available for this survey.</p>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>
</div>

<?php include 'includes/footer.php'; ?>