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

requireLogin();

$pdo = getDB();
$success = '';
$error = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add':
                $title = trim($_POST['title'] ?? '');
                $description = trim($_POST['description'] ?? '');
                $status = $_POST['status'] ?? 'inactive';

                if ($title) {
                    $stmt = $pdo->prepare("INSERT INTO surveys (title, description, status, created_by) VALUES (?, ?, ?, ?)");
                    if ($stmt->execute([$title, $description, $status, $_SESSION['user_id']])) {
                        $success = 'Survey added successfully!';
                    } else {
                        $error = 'Error adding survey.';
                    }
                } else {
                    $error = 'Survey title is required.';
                }
                break;

            case 'edit':
                $id = (int)($_POST['id'] ?? 0);
                $title = trim($_POST['title'] ?? '');
                $description = trim($_POST['description'] ?? '');
                $status = $_POST['status'] ?? 'inactive';

                if ($id && $title) {
                    $stmt = $pdo->prepare("UPDATE surveys SET title = ?, description = ?, status = ? WHERE id = ?");
                    if ($stmt->execute([$title, $description, $status, $id])) {
                        $success = 'Survey updated successfully!';
                    } else {
                        $error = 'Error updating survey.';
                    }
                } else {
                    $error = 'Survey title is required.';
                }
                break;

            case 'add_question':
                $survey_id = (int)($_POST['survey_id'] ?? 0);
                $question_text = trim($_POST['question_text'] ?? '');
                $question_type = $_POST['question_type'] ?? 'text';
                $options = trim($_POST['options'] ?? '');

                if ($survey_id && $question_text) {
                    $options_json = null;
                    if (in_array($question_type, ['radio', 'checkbox']) && $options) {
                        $options_array = array_filter(array_map('trim', explode("\n", $options)));
                        $options_json = json_encode($options_array);
                    }

                    $stmt = $pdo->prepare("INSERT INTO survey_questions (survey_id, question_text, question_type, options) VALUES (?, ?, ?, ?)");
                    if ($stmt->execute([$survey_id, $question_text, $question_type, $options_json])) {
                        $success = 'Question added successfully!';
                    } else {
                        $error = 'Error adding question.';
                    }
                } else {
                    $error = 'Question text is required.';
                }
                break;
        }
    }
}

// Handle delete action
if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['id'])) {
    $id = (int)$_GET['id'];

    // Check if survey has responses
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM survey_responses WHERE survey_id = ?");
    $stmt->execute([$id]);
    $response_count = $stmt->fetchColumn();

    if ($response_count > 0) {
        $error = "Cannot delete survey. It has {$response_count} response(s).";
    } else {
        $stmt = $pdo->prepare("DELETE FROM surveys WHERE id = ?");
        if ($stmt->execute([$id])) {
            $success = 'Survey deleted successfully!';
        } else {
            $error = 'Error deleting survey.';
        }
    }
}

// Handle delete question
if (isset($_GET['delete_question']) && isset($_GET['edit'])) {
    $question_id = (int)$_GET['delete_question'];
    $survey_id = (int)$_GET['edit'];

    $stmt = $pdo->prepare("DELETE FROM survey_questions WHERE id = ? AND survey_id = ?");
    if ($stmt->execute([$question_id, $survey_id])) {
        $success = 'Question deleted successfully!';
    } else {
        $error = 'Error deleting question.';
    }
}

// Get all surveys
$surveys = $pdo->query("SELECT s.*, COUNT(sr.id) as response_count
                        FROM surveys s
                        LEFT JOIN survey_responses sr ON s.id = sr.survey_id
                        GROUP BY s.id
                        ORDER BY s.created_at DESC")->fetchAll();

// Get survey for editing
$edit_survey = null;
$questions = [];
if (isset($_GET['edit']) && $_GET['edit']) {
    $edit_id = (int)$_GET['edit'];
    $stmt = $pdo->prepare("SELECT * FROM surveys WHERE id = ?");
    $stmt->execute([$edit_id]);
    $edit_survey = $stmt->fetch();

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

$page_title = 'Manage Surveys';
include 'includes/admin_header.php';
?>

<?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 endif; ?>

<div class="surveys-management">
    <div class="surveys-form-section">
        <div class="form-card">
            <div class="form-header">
                <h2>
                    <i class="fas fa-<?php echo $edit_survey ? 'edit' : 'plus'; ?>"></i>
                    <?php echo $edit_survey ? 'Edit Survey' : 'Add New Survey'; ?>
                </h2>
            </div>

            <form method="POST" class="survey-form">
                <input type="hidden" name="action" value="<?php echo $edit_survey ? 'edit' : 'add'; ?>">
                <?php if ($edit_survey): ?>
                    <input type="hidden" name="id" value="<?php echo $edit_survey['id']; ?>">
                <?php endif; ?>

                <div class="form-group">
                    <label for="title">Survey Title *</label>
                    <input type="text" id="title" name="title" required
                           value="<?php echo htmlspecialchars($edit_survey['title'] ?? ''); ?>"
                           placeholder="Enter survey title">
                </div>

                <div class="form-group">
                    <label for="description">Description</label>
                    <textarea id="description" name="description" rows="3"
                              placeholder="Enter survey description (optional)"><?php echo htmlspecialchars($edit_survey['description'] ?? ''); ?></textarea>
                </div>

                <div class="form-group">
                    <label for="status">Status</label>
                    <select id="status" name="status">
                        <option value="inactive" <?php echo ($edit_survey['status'] ?? 'inactive') == 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                        <option value="active" <?php echo ($edit_survey['status'] ?? 'inactive') == 'active' ? 'selected' : ''; ?>>Active</option>
                    </select>
                </div>

                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i>
                        <?php echo $edit_survey ? 'Update Survey' : 'Add Survey'; ?>
                    </button>
                    <?php if ($edit_survey): ?>
                        <a href="surveys.php" class="btn btn-secondary">Cancel</a>
                    <?php endif; ?>
                </div>
            </form>

            <?php if ($edit_survey): ?>
                <div class="questions-section">
                    <h3>Survey Questions</h3>

                    <div class="questions-list">
                        <?php foreach ($questions as $question): ?>
                            <div class="question-item">
                                <div class="question-info">
                                    <strong><?php echo htmlspecialchars($question['question_text']); ?></strong>
                                    <span class="question-type">(<?php echo ucfirst($question['question_type']); ?>)</span>
                                </div>
                                <div class="question-actions">
                                    <a href="?edit=<?php echo $edit_survey['id']; ?>&delete_question=<?php echo $question['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Delete this question?')">Delete</a>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>

                    <form method="POST" class="add-question-form">
                        <input type="hidden" name="action" value="add_question">
                        <input type="hidden" name="survey_id" value="<?php echo $edit_survey['id']; ?>">

                        <div class="form-group">
                            <label for="question_text">Question Text</label>
                            <input type="text" id="question_text" name="question_text" required placeholder="Enter question">
                        </div>

                        <div class="form-group">
                            <label for="question_type">Question Type</label>
                            <select id="question_type" name="question_type">
                                <option value="text">Text</option>
                                <option value="radio">Radio (Single Choice)</option>
                                <option value="checkbox">Checkbox (Multiple Choice)</option>
                            </select>
                        </div>

                        <div class="form-group options-group" style="display: none;">
                            <label for="options">Options (one per line)</label>
                            <textarea id="options" name="options" rows="3" placeholder="Option 1&#10;Option 2&#10;Option 3"></textarea>
                        </div>

                        <button type="submit" class="btn btn-secondary">Add Question</button>
                    </form>

                    <script>
                    document.getElementById('question_type').addEventListener('change', function() {
                        const optionsGroup = document.querySelector('.options-group');
                        if (this.value === 'radio' || this.value === 'checkbox') {
                            optionsGroup.style.display = 'block';
                        } else {
                            optionsGroup.style.display = 'none';
                        }
                    });
                    </script>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <div class="surveys-list-section">
        <div class="surveys-header">
            <h2>All Surveys</h2>
            <span class="surveys-count"><?php echo count($surveys); ?> surveys</span>
        </div>

        <div class="surveys-table-wrapper">
            <table class="surveys-table">
                <thead>
                    <tr>
                        <th>Title</th>
                        <th>Description</th>
                        <th>Status</th>
                        <th>Responses</th>
                        <th>Created</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($surveys as $survey): ?>
                        <tr class="<?php echo $edit_survey && $edit_survey['id'] == $survey['id'] ? 'editing' : ''; ?>">
                            <td>
                                <strong><?php echo htmlspecialchars($survey['title']); ?></strong>
                            </td>
                            <td>
                                <span class="survey-description">
                                    <?php echo htmlspecialchars($survey['description'] ?: 'No description'); ?>
                                </span>
                            </td>
                            <td>
                                <span class="status-badge status-<?php echo $survey['status']; ?>">
                                    <?php echo ucfirst($survey['status']); ?>
                                </span>
                            </td>
                            <td>
                                <span class="response-count-badge">
                                    <?php echo $survey['response_count']; ?> responses
                                </span>
                            </td>
                            <td><?php echo formatDate($survey['created_at']); ?></td>
                            <td class="actions">
                                <a href="?edit=<?php echo $survey['id']; ?>" class="btn btn-sm">
                                    <i class="fas fa-edit"></i> Edit
                                </a>
                                <a href="../survey.php?id=<?php echo $survey['id']; ?>" class="btn btn-sm btn-secondary" target="_blank">
                                    <i class="fas fa-eye"></i> View
                                </a>
                                <?php if ($survey['response_count'] == 0): ?>
                                    <a href="?action=delete&id=<?php echo $survey['id']; ?>"
                                       class="btn btn-sm btn-danger"
                                       onclick="return confirm('Are you sure you want to delete this survey?')">
                                        <i class="fas fa-trash"></i> Delete
                                    </a>
                                <?php else: ?>
                                    <span class="btn btn-sm btn-disabled" title="Cannot delete survey with responses">
                                        <i class="fas fa-trash"></i> Delete
                                    </span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <?php if (empty($surveys)): ?>
            <div class="no-surveys">
                <i class="fas fa-poll"></i>
                <p>No surveys found. Create your first survey above.</p>
            </div>
        <?php endif; ?>
    </div>
</div>

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