<?php
// Detect AJAX requests FIRST before anything else
$is_ajax = isset($_POST['action']) || isset($_GET['action']);

// If AJAX request, suppress ALL errors and start output buffering
if ($is_ajax) {
    error_reporting(0);
    ini_set('display_errors', '0');
    ini_set('log_errors', '1');
    ob_start();
}

session_start();
require_once 'config.php';

// Check if user is Super Admin
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || $_SESSION["role"] !== 0) {
    if ($is_ajax) {
        if (ob_get_level()) ob_clean();
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
        exit;
    }
    header("location: login.php");
    exit;
}

// Helper function to send JSON response and exit cleanly
function sendJSON($data) {
    // Clear any previous output
    if (ob_get_level()) ob_clean();
    header('Content-Type: application/json');
    echo json_encode($data);
    exit;
}

// Handle AJAX requests
if ($is_ajax) {
    try {
        $action = $_POST['action'] ?? $_GET['action'] ?? '';
    
    // Test endpoint
    if ($action === 'test') {
        sendJSON(['success' => true, 'message' => 'AJAX endpoint is working!']);
    }
    
    if ($action === 'create_survey') {
        $title = $_POST['title'] ?? '';
        $description = $_POST['description'] ?? '';
        $target_schools = $_POST['target_schools'] ?? 'all';
        $deadline = $_POST['deadline'] ?? '';
        
        if (empty($title) || empty($deadline)) {
            sendJSON(['success' => false, 'message' => 'Title and deadline are required']);
        }
        
        // Check database connection
        if (!isset($conn) || !($conn instanceof mysqli)) {
            sendJSON(['success' => false, 'message' => 'Database connection error']);
        }
        
        $sql = "INSERT INTO surveys (title, description, target_schools, deadline, status, created_by, created_at) 
                VALUES (?, ?, ?, ?, 'active', ?, NOW())";
        
        if ($stmt = $conn->prepare($sql)) {
            $stmt->bind_param("ssssi", $title, $description, $target_schools, $deadline, $_SESSION['id']);
            
            if ($stmt->execute()) {
                $survey_id = $conn->insert_id;
                sendJSON([
                    'success' => true, 
                    'message' => 'Survey created successfully',
                    'survey_id' => $survey_id
                ]);
            } else {
                sendJSON(['success' => false, 'message' => 'Failed to create survey: ' . $stmt->error]);
            }
            $stmt->close();
        } else {
            sendJSON(['success' => false, 'message' => 'Database prepare error: ' . $conn->error]);
        }
        
    } elseif ($action === 'add_question') {
        $survey_id = $_POST['survey_id'] ?? 0;
        $question_text = $_POST['question_text'] ?? '';
        $question_type = $_POST['question_type'] ?? 'text';
        $options = $_POST['options'] ?? '';
        $required = isset($_POST['required']) ? 1 : 0;
        
        if (empty($survey_id) || empty($question_text)) {
            sendJSON(['success' => false, 'message' => 'Survey ID and question text are required']);
        }
        
        // Check database connection
        if (!isset($conn) || !($conn instanceof mysqli)) {
            sendJSON(['success' => false, 'message' => 'Database connection error']);
        }
        
        $sql = "INSERT INTO survey_questions (survey_id, question_text, question_type, options, required, created_at) 
                VALUES (?, ?, ?, ?, ?, NOW())";
        
        if ($stmt = $conn->prepare($sql)) {
            $stmt->bind_param("isssi", $survey_id, $question_text, $question_type, $options, $required);
            
            if ($stmt->execute()) {
                sendJSON(['success' => true, 'message' => 'Question added successfully']);
            } else {
                sendJSON(['success' => false, 'message' => 'Failed to add question: ' . $stmt->error]);
            }
            $stmt->close();
        } else {
            sendJSON(['success' => false, 'message' => 'Database prepare error: ' . $conn->error]);
        }
        
    } elseif ($action === 'get_surveys') {
        $sql = "SELECT 
                    s.*,
                    COUNT(DISTINCT sq.question_id) as total_questions,
                    COUNT(DISTINCT sr.response_id) as total_responses
                FROM surveys s
                LEFT JOIN survey_questions sq ON s.survey_id = sq.survey_id
                LEFT JOIN survey_responses sr ON s.survey_id = sr.survey_id
                GROUP BY s.survey_id
                ORDER BY s.created_at DESC";
        
        $surveys = [];
        if ($result = $conn->query($sql)) {
            while ($row = $result->fetch_assoc()) {
                $surveys[] = $row;
            }
            $result->free();
        }
        
        sendJSON(['success' => true, 'surveys' => $surveys]);
        
    } elseif ($action === 'get_questions') {
        $survey_id = $_GET['survey_id'] ?? 0;
        
        $sql = "SELECT * FROM survey_questions WHERE survey_id = ? ORDER BY created_at ASC";
        
        $questions = [];
        if ($stmt = $conn->prepare($sql)) {
            $stmt->bind_param("i", $survey_id);
            $stmt->execute();
            $result = $stmt->get_result();
            
            while ($row = $result->fetch_assoc()) {
                $questions[] = $row;
            }
            $stmt->close();
        }
        
        sendJSON(['success' => true, 'questions' => $questions]);
    }
    } catch (Exception $e) {
        sendJSON(['success' => false, 'message' => 'Server error: ' . $e->getMessage()]);
    } catch (Error $e) {
        sendJSON(['success' => false, 'message' => 'Fatal error: ' . $e->getMessage()]);
    }
}

// Fetch user details for page display
$user_id = $_SESSION["id"];
$username = htmlspecialchars($_SESSION["username"]);
$phone_number = $photo = "";

if (isset($conn) && $conn instanceof mysqli) {
    $sql = "SELECT phone_number, photo FROM users WHERE id = ?";
    if ($stmt = $conn->prepare($sql)) {
        $stmt->bind_param("i", $user_id);
        if ($stmt->execute()) {
            $stmt->bind_result($phone_number_db, $photo_db);
            $stmt->fetch();
            $phone_number = htmlspecialchars($phone_number_db ?? 'N/A');
            $photo = !empty($photo_db) ? htmlspecialchars($photo_db) : 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="80" height="80"%3E%3Crect width="80" height="80" fill="%234f46e5"/%3E%3Ctext x="50%25" y="50%25" dominant-baseline="middle" text-anchor="middle" font-family="Arial, sans-serif" font-size="32" font-weight="bold" fill="white"%3ESA%3C/text%3E%3C/svg%3E';
        }
        $stmt->close();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Surveys - Super Admin</title>
    <link rel="stylesheet" href="super_admin_layout.css">
    <link rel="icon" href="images/logo.png" type="image/png">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        .surveys-container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .survey-card {
            background: white;
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 6px 15px rgba(0, 0, 0, 0.08);
            margin-bottom: 30px;
        }

        .survey-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .survey-item {
            background: #f9fafb;
            padding: 20px;
            border-radius: 10px;
            border-left: 4px solid #4f46e5;
            transition: all 0.3s;
            position: relative;
        }

        .survey-item:hover {
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            transform: translateY(-2px);
        }

        .survey-item h4 {
            margin: 0 0 10px 0;
            color: #333;
            padding-right: 100px;
        }

        .survey-item p {
            color: #666;
            margin: 5px 0;
            font-size: 0.9em;
        }

        .survey-actions {
            position: absolute;
            top: 15px;
            right: 15px;
            display: flex;
            gap: 8px;
        }

        .btn-icon {
            padding: 8px 12px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 0.9em;
            transition: all 0.2s;
        }

        .btn-questions {
            background-color: #4f46e5;
            color: white;
        }

        .btn-questions:hover {
            background-color: #4338ca;
        }

        .btn-create {
            background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
            color: white;
            padding: 14px 30px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            text-decoration: none;
            display: inline-block;
        }

        .btn-create:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(79, 70, 229, 0.3);
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #999;
        }

        .empty-state i {
            font-size: 5em;
            margin-bottom: 20px;
            opacity: 0.3;
        }

        .empty-state h3 {
            color: #666;
            margin: 20px 0 10px 0;
        }

        .empty-state p {
            color: #999;
            margin-bottom: 30px;
        }

        /* Modal Styles */
        .modal {
            display: none;
            position: fixed;
            z-index: 9999;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.5);
            animation: fadeIn 0.3s;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        .modal-content {
            background-color: #fefefe;
            margin: 3% auto;
            padding: 30px;
            border: 1px solid #888;
            border-radius: 12px;
            width: 90%;
            max-width: 700px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
            animation: slideDown 0.3s;
        }

        @keyframes slideDown {
            from {
                transform: translateY(-50px);
                opacity: 0;
            }
            to {
                transform: translateY(0);
                opacity: 1;
            }
        }

        .modal-header {
            display: flex;
            align-items: center;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 2px solid #e5e7eb;
        }

        .modal-header i {
            font-size: 2.5em;
            margin-right: 15px;
            color: #4f46e5;
        }

        .modal-header h3 {
            margin: 0;
            color: #333;
        }

        .modal-body {
            margin-bottom: 25px;
        }

        .modal-footer {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            padding-top: 15px;
            border-top: 2px solid #e5e7eb;
        }

        .btn-modal {
            padding: 10px 24px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 15px;
            font-weight: 600;
            transition: all 0.2s;
        }

        .btn-cancel {
            background-color: #e5e7eb;
            color: #333;
        }

        .btn-cancel:hover {
            background-color: #d1d5db;
        }

        .btn-submit {
            background-color: #4f46e5;
            color: white;
        }

        .btn-submit:hover {
            background-color: #4338ca;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
            font-family: inherit;
        }

        .form-group textarea {
            resize: vertical;
            min-height: 100px;
        }

        .question-list {
            max-height: 400px;
            overflow-y: auto;
            margin-bottom: 20px;
        }

        .question-card {
            background: #f9fafb;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 10px;
            border-left: 3px solid #4f46e5;
        }

        .question-card h5 {
            margin: 0 0 8px 0;
            color: #333;
        }

        .question-meta {
            font-size: 0.85em;
            color: #666;
        }

        .badge {
            display: inline-block;
            padding: 3px 8px;
            border-radius: 4px;
            font-size: 0.75em;
            font-weight: 600;
            margin-left: 8px;
        }

        .badge-required {
            background: #fee2e2;
            color: #991b1b;
        }

        .badge-optional {
            background: #e0e7ff;
            color: #3730a3;
        }

        /* Notification Box */
        .notification-box {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 20px 25px;
            border-radius: 8px;
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.2);
            z-index: 10000;
            display: none;
            align-items: center;
            gap: 15px;
            max-width: 400px;
            animation: slideInRight 0.3s;
        }

        @keyframes slideInRight {
            from {
                transform: translateX(400px);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }

        .notification-success {
            background-color: #d1fae5;
            color: #065f46;
            border-left: 4px solid #10b981;
        }

        .notification-box i {
            font-size: 1.5em;
        }

        .notification-close {
            background: none;
            border: none;
            font-size: 1.2em;
            cursor: pointer;
            color: inherit;
            opacity: 0.7;
            margin-left: auto;
        }

        .notification-close:hover {
            opacity: 1;
        }
    </style>
</head>
<body>
    <div class="dashboard-container" id="dashboardContainer">
        <?php include 'includes/super_admin_sidebar.php'; ?>
        
        <div class="main-content">
            <?php include 'includes/super_admin_header.php'; ?>
            
            <div class="dashboard-content">
                <div class="surveys-container">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px;">
                        <h2><i class="fas fa-poll"></i> Survey Management</h2>
                        <button class="btn-create" onclick="createNewSurvey()">
                            <i class="fas fa-plus-circle"></i> Create New Survey
                        </button>
                    </div>

                    <div class="survey-card">
                        <h3><i class="fas fa-clipboard-list"></i> Active Surveys</h3>
                        
                        <div id="surveysList">
                            <div class="empty-state" id="emptyState">
                                <i class="fas fa-poll"></i>
                                <h3>No Surveys Created Yet</h3>
                                <p>Create your first survey to collect feedback from schools.</p>
                                <button class="btn-create" onclick="createNewSurvey()">
                                    <i class="fas fa-plus"></i> Create Your First Survey
                                </button>
                            </div>
                            <div class="survey-grid" id="surveysGrid" style="display: none;"></div>
                        </div>
                    </div>

                    <div class="survey-card">
                        <h3><i class="fas fa-chart-pie"></i> Survey Statistics</h3>
                        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-top: 20px;">
                            <div style="background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%); color: white; padding: 25px; border-radius: 10px; text-align: center;">
                                <i class="fas fa-list" style="font-size: 2em; margin-bottom: 10px;"></i>
                                <h2 style="margin: 10px 0;" id="totalSurveysCount">0</h2>
                                <p style="margin: 0; opacity: 0.9;">Total Surveys</p>
                            </div>
                            <div style="background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: white; padding: 25px; border-radius: 10px; text-align: center;">
                                <i class="fas fa-check-circle" style="font-size: 2em; margin-bottom: 10px;"></i>
                                <h2 style="margin: 10px 0;" id="completedCount">0</h2>
                                <p style="margin: 0; opacity: 0.9;">Completed</p>
                            </div>
                            <div style="background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); color: white; padding: 25px; border-radius: 10px; text-align: center;">
                                <i class="fas fa-users" style="font-size: 2em; margin-bottom: 10px;"></i>
                                <h2 style="margin: 10px 0;" id="responsesCount">0</h2>
                                <p style="margin: 0; opacity: 0.9;">Total Responses</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <?php include 'includes/super_admin_mobile_nav.php'; ?>
    </div>

    <!-- Create Survey Modal -->
    <div id="surveyModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <i class="fas fa-poll"></i>
                <h3>Create New Survey</h3>
            </div>
            <form id="surveyForm" onsubmit="event.preventDefault(); createSurvey();">
                <div class="modal-body">
                    <div class="form-group">
                        <label for="survey_title">Survey Title <span style="color: red;">*</span></label>
                        <input type="text" id="survey_title" name="survey_title" placeholder="Enter survey title" required>
                    </div>
                    <div class="form-group">
                        <label for="survey_description">Description</label>
                        <textarea id="survey_description" name="survey_description" placeholder="Describe the purpose of this survey"></textarea>
                    </div>
                    <div class="form-group">
                        <label for="target_schools">Target Schools <span style="color: red;">*</span></label>
                        <select id="target_schools" name="target_schools" required>
                            <option value="all">All Schools</option>
                            <option value="active">Active Schools Only</option>
                            <option value="suspended">Suspended Schools Only</option>
                            <option value="custom">Select Specific Schools</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="deadline">Response Deadline <span style="color: red;">*</span></label>
                        <input type="date" id="deadline" name="deadline" required>
                    </div>
                    <div style="background: #f0f9ff; padding: 15px; border-radius: 6px; margin-top: 15px;">
                        <p style="margin: 0; color: #0c4a6e; font-size: 0.9em;"><i class="fas fa-info-circle"></i> After creating the survey, you'll be able to add questions and configure response types.</p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" onclick="closeModal('surveyModal')" class="btn-modal btn-cancel">
                        <i class="fas fa-times"></i> Cancel
                    </button>
                    <button type="submit" class="btn-modal btn-submit">
                        <i class="fas fa-plus"></i> Create Survey
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Manage Questions Modal -->
    <div id="questionsModal" class="modal">
        <div class="modal-content" style="max-width: 800px;">
            <div class="modal-header">
                <i class="fas fa-question-circle"></i>
                <h3 id="questionModalTitle">Manage Survey Questions</h3>
            </div>
            <div class="modal-body">
                <div class="question-list" id="questionsList">
                    <p style="text-align: center; color: #999; padding: 20px;">No questions added yet.</p>
                </div>
                
                <div style="background: #f0f9ff; padding: 20px; border-radius: 8px; margin-top: 20px;">
                    <h4 style="margin: 0 0 15px 0; color: #0c4a6e;"><i class="fas fa-plus-circle"></i> Add New Question</h4>
                    <form id="addQuestionForm" onsubmit="event.preventDefault(); addQuestion();">
                        <div class="form-group">
                            <label for="question_text">Question Text <span style="color: red;">*</span></label>
                            <textarea id="question_text" name="question_text" placeholder="Enter your question" required style="min-height: 60px;"></textarea>
                        </div>
                        <div style="display: grid; grid-template-columns: 2fr 1fr; gap: 15px;">
                            <div class="form-group">
                                <label for="question_type">Question Type</label>
                                <select id="question_type" name="question_type" onchange="toggleOptionsField()">
                                    <option value="text">Text Answer</option>
                                    <option value="textarea">Long Text</option>
                                    <option value="multiple_choice">Multiple Choice</option>
                                    <option value="checkboxes">Checkboxes</option>
                                    <option value="rating">Rating (1-5)</option>
                                    <option value="yes_no">Yes/No</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label>&nbsp;</label>
                                <label style="display: flex; align-items: center; padding: 10px; background: white; border-radius: 6px; cursor: pointer;">
                                    <input type="checkbox" id="required" name="required" style="margin-right: 8px;">
                                    <span>Required</span>
                                </label>
                            </div>
                        </div>
                        <div class="form-group" id="optionsGroup" style="display: none;">
                            <label for="options">Options (comma-separated)</label>
                            <input type="text" id="options" name="options" placeholder="e.g., Option 1, Option 2, Option 3">
                        </div>
                        <button type="submit" class="btn-modal btn-submit" style="width: 100%;">
                            <i class="fas fa-plus"></i> Add Question
                        </button>
                    </form>
                </div>
            </div>
            <div class="modal-footer">
                <button onclick="closeModal('questionsModal')" class="btn-modal btn-close">
                    <i class="fas fa-check"></i> Done
                </button>
            </div>
        </div>
    </div>

    <!-- Notification Box -->
    <div id="notificationBox" class="notification-box notification-success" style="display: none;">
        <i class="fas fa-check-circle"></i>
        <span id="notificationMessage"></span>
        <button onclick="closeNotification()" class="notification-close"><i class="fas fa-times"></i></button>
    </div>

    <script>
        // Store current survey ID for question management
        let currentSurveyId = null;

        // Load surveys on page load
        document.addEventListener('DOMContentLoaded', function() {
            loadSurveys();
        });

        // Load surveys from database
        async function loadSurveys() {
            try {
                const response = await fetch('super_admin_surveys.php?action=get_surveys');
                const data = await response.json();
                
                if (data.success && data.surveys) {
                    displaySurveys(data.surveys);
                }
            } catch (error) {
                console.error('Error loading surveys:', error);
            }
        }

        // Create new survey function
        function createNewSurvey() {
            // Set minimum date to today
            const today = new Date().toISOString().split('T')[0];
            document.getElementById('deadline').setAttribute('min', today);
            
            document.getElementById('surveyModal').style.display = 'block';
        }

        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
            if (modalId === 'surveyModal') {
                document.getElementById('surveyForm').reset();
            } else if (modalId === 'questionsModal') {
                document.getElementById('addQuestionForm').reset();
                currentSurveyId = null;
            }
        }

        async function createSurvey() {
            const formData = new FormData();
            formData.append('action', 'create_survey');
            formData.append('title', document.getElementById('survey_title').value);
            formData.append('description', document.getElementById('survey_description').value);
            formData.append('target_schools', document.getElementById('target_schools').value);
            formData.append('deadline', document.getElementById('deadline').value);

            try {
                const response = await fetch('super_admin_surveys.php', {
                    method: 'POST',
                    body: formData
                });
                const data = await response.json();
                
                if (data.success) {
                    closeModal('surveyModal');
                    showNotification(data.message);
                    
                    // Reload surveys
                    await loadSurveys();
                    
                    // Ask if user wants to add questions
                    setTimeout(() => {
                        if (confirm('Survey created! Would you like to add questions now?')) {
                            currentSurveyId = data.survey_id;
                            openQuestionsModal(data.survey_id, document.getElementById('survey_title').value);
                        }
                    }, 500);
                } else {
                    showNotification(data.message || 'Failed to create survey');
                }
            } catch (error) {
                console.error('Error creating survey:', error);
                showNotification('Error creating survey');
            }
        }

        function displaySurveys(surveys) {
            const surveysGrid = document.getElementById('surveysGrid');
            const emptyState = document.getElementById('emptyState');
            
            if (surveys.length === 0) {
                emptyState.style.display = 'block';
                surveysGrid.style.display = 'none';
            } else {
                emptyState.style.display = 'none';
                surveysGrid.style.display = 'grid';
                
                // Clear existing content
                surveysGrid.innerHTML = '';
                
                // Add each survey
                surveys.forEach(survey => {
                    const surveyCard = document.createElement('div');
                    surveyCard.className = 'survey-item';
                    const deadlineDate = new Date(survey.deadline);
                    const statusBadge = survey.status === 'active' ? 'status-paid' : 'status-pending';
                    
                    surveyCard.innerHTML = `
                        <div class="survey-actions">
                            <button class="btn-icon btn-questions" onclick="openQuestionsModal(${survey.survey_id}, '${survey.title.replace(/'/g, "\\'")}')" 
                                title="Manage Questions">
                                <i class="fas fa-question-circle"></i> ${survey.total_questions || 0}
                            </button>
                        </div>
                        <h4><i class="fas fa-poll"></i> ${survey.title}</h4>
                        <p><i class="fas fa-align-left"></i> ${survey.description || 'No description'}</p>
                        <p><i class="fas fa-school"></i> <strong>Target:</strong> ${survey.target_schools.charAt(0).toUpperCase() + survey.target_schools.slice(1)}</p>
                        <p><i class="fas fa-calendar"></i> <strong>Deadline:</strong> ${deadlineDate.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}</p>
                        <p><i class="fas fa-chart-bar"></i> <strong>Responses:</strong> ${survey.total_responses || 0}</p>
                        <p><span class="status-badge ${statusBadge}" style="background: #d1fae5; color: #065f46; padding: 4px 10px; border-radius: 10px;">${survey.status.charAt(0).toUpperCase() + survey.status.slice(1)}</span></p>
                    `;
                    surveysGrid.appendChild(surveyCard);
                });
                
                // Update statistics
                const activeCount = surveys.filter(s => s.status === 'active').length;
                const completedCount = surveys.filter(s => s.status === 'completed').length;
                const totalResponses = surveys.reduce((sum, s) => sum + parseInt(s.total_responses || 0), 0);
                
                document.getElementById('totalSurveysCount').textContent = surveys.length;
                document.getElementById('completedCount').textContent = completedCount;
                document.getElementById('responsesCount').textContent = totalResponses;
            }
        }

        async function openQuestionsModal(surveyId, surveyTitle) {
            currentSurveyId = surveyId;
            document.getElementById('questionModalTitle').textContent = `Questions: ${surveyTitle}`;
            
            // Load existing questions
            await loadQuestions(surveyId);
            
            document.getElementById('questionsModal').style.display = 'block';
        }

        async function loadQuestions(surveyId) {
            try {
                const response = await fetch(`super_admin_surveys.php?action=get_questions&survey_id=${surveyId}`);
                const data = await response.json();
                
                const questionsList = document.getElementById('questionsList');
                
                if (data.success && data.questions && data.questions.length > 0) {
                    questionsList.innerHTML = '';
                    
                    data.questions.forEach((q, index) => {
                        const questionCard = document.createElement('div');
                        questionCard.className = 'question-card';
                        
                        const typeLabels = {
                            'text': 'Text Answer',
                            'textarea': 'Long Text',
                            'multiple_choice': 'Multiple Choice',
                            'checkboxes': 'Checkboxes',
                            'rating': 'Rating (1-5)',
                            'yes_no': 'Yes/No'
                        };
                        
                        let optionsHtml = '';
                        if (q.options) {
                            optionsHtml = `<p class="question-meta"><strong>Options:</strong> ${q.options}</p>`;
                        }
                        
                        questionCard.innerHTML = `
                            <h5>Q${index + 1}. ${q.question_text}
                                <span class="badge ${q.required ? 'badge-required' : 'badge-optional'}">
                                    ${q.required ? 'Required' : 'Optional'}
                                </span>
                            </h5>
                            <p class="question-meta"><strong>Type:</strong> ${typeLabels[q.question_type] || q.question_type}</p>
                            ${optionsHtml}
                        `;
                        questionsList.appendChild(questionCard);
                    });
                } else {
                    questionsList.innerHTML = '<p style="text-align: center; color: #999; padding: 20px;">No questions added yet.</p>';
                }
            } catch (error) {
                console.error('Error loading questions:', error);
            }
        }

        function toggleOptionsField() {
            const questionType = document.getElementById('question_type').value;
            const optionsGroup = document.getElementById('optionsGroup');
            
            if (questionType === 'multiple_choice' || questionType === 'checkboxes') {
                optionsGroup.style.display = 'block';
                document.getElementById('options').required = true;
            } else {
                optionsGroup.style.display = 'none';
                document.getElementById('options').required = false;
                document.getElementById('options').value = '';
            }
        }

        async function addQuestion() {
            if (!currentSurveyId) {
                showNotification('Error: No survey selected');
                return;
            }
            
            const formData = new FormData();
            formData.append('action', 'add_question');
            formData.append('survey_id', currentSurveyId);
            formData.append('question_text', document.getElementById('question_text').value);
            formData.append('question_type', document.getElementById('question_type').value);
            formData.append('options', document.getElementById('options').value);
            if (document.getElementById('required').checked) {
                formData.append('required', '1');
            }
            
            try {
                const response = await fetch('super_admin_surveys.php', {
                    method: 'POST',
                    body: formData
                });
                const data = await response.json();
                
                if (data.success) {
                    showNotification(data.message);
                    document.getElementById('addQuestionForm').reset();
                    toggleOptionsField();
                    
                    // Reload questions
                    await loadQuestions(currentSurveyId);
                    
                    // Reload surveys to update question count
                    await loadSurveys();
                } else {
                    showNotification(data.message || 'Failed to add question');
                }
            } catch (error) {
                console.error('Error adding question:', error);
                showNotification('Error adding question');
            }
        }

        function showNotification(message) {
            const notification = document.getElementById('notificationBox');
            document.getElementById('notificationMessage').textContent = message;
            notification.style.display = 'flex';
            
            setTimeout(() => {
                notification.style.opacity = '0';
                setTimeout(() => {
                    notification.style.display = 'none';
                    notification.style.opacity = '1';
                }, 500);
            }, 5000);
        }

        function closeNotification() {
            const notification = document.getElementById('notificationBox');
            notification.style.opacity = '0';
            setTimeout(() => {
                notification.style.display = 'none';
                notification.style.opacity = '1';
            }, 500);
        }

        const menuToggle = document.getElementById('menuToggle');
        const sidebar = document.getElementById('sidebar');
        const dashboardContainer = document.getElementById('dashboardContainer');
        
        if (menuToggle) {
            menuToggle.addEventListener('click', function() {
                sidebar.classList.toggle('collapsed');
                dashboardContainer.classList.toggle('sidebar-collapsed');
            });
        }
        window.onclick = function(event) {
            if (event.target.classList.contains('modal')) {
                event.target.style.display = 'none';
            }
        }
    </script>
</body>
</html>
<?php
if (isset($conn) && $conn instanceof mysqli && $conn->ping()) {
    $conn->close();
}
?>