<?php
session_start();
if (!isset($_SESSION['admin'])) {
    header('Location: login.php');
    exit();
}
include 'db.php';
include 'upload_helper.php';

$quiz_id = isset($_GET['quiz_id']) ? (int) $_GET['quiz_id'] : 0;
if (!$quiz_id) {
    header('Location: manage_quizzes.php');
    exit();
}

// Fetch quiz details
$quizStmt = $conn->prepare("SELECT quiz_name FROM quiz_games WHERE quiz_id = ?");
$quizStmt->bind_param("i", $quiz_id);
$quizStmt->execute();
$quizName = $quizStmt->get_result()->fetch_assoc()['quiz_name'] ?? 'Unknown Quiz';
$quizStmt->close();

$message = '';

// Handle adding a new question
if (isset($_POST['add_question'])) {
    $question_text = $_POST['question'];
    $type = $_POST['type'];
    $media_type = $_POST['media_type'] ?? 'none';
    $answer = $_POST['answer'];
    $hint_text = $_POST['hint_text'] ?? '';

    // Handle Options (Stored as JSON)
    $optionsArr = [
        $_POST['option1'] ?? '',
        $_POST['option2'] ?? '',
        $_POST['option3'] ?? '',
        $_POST['option4'] ?? ''
    ];
    $options = json_encode($optionsArr);

    $media_url = '';
    if ($media_type !== 'none' && isset($_FILES['media_file']) && $_FILES['media_file']['error'] === UPLOAD_ERR_OK) {
        $targetDir = '../../assets/quiz_media/';
        if (!is_dir($targetDir))
            mkdir($targetDir, 0777, true);

        $upload = handleFileUpload($_FILES['media_file'], $targetDir, ['mp3', 'mp4', 'webm', 'jpg', 'jpeg', 'png', 'webp']);
        if ($upload['status'] === 'success') {
            $media_url = 'assets/quiz_media/' . $upload['fileName'];
        } else {
            $message = "<div class='alert alert-danger'>Upload Error: " . $upload['message'] . "</div>";
        }
    }

    if (empty($message)) {
        if ($stmt = $conn->prepare("INSERT INTO quiz_questions (quiz_id, question, options, answer, type, media_type, media_url, hint_text) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")) {
            $stmt->bind_param("isssssss", $quiz_id, $question_text, $options, $answer, $type, $media_type, $media_url, $hint_text);
            if ($stmt->execute()) {
                $message = "<div class='alert alert-success'>Question added successfully!</div>";
            } else {
                $message = "<div class='alert alert-danger'>Error: " . $stmt->error . "</div>";
            }
            $stmt->close();
        }
    }
}

// Fetch existing questions
$questionsStmt = $conn->prepare("SELECT * FROM quiz_questions WHERE quiz_id = ? ORDER BY question_id DESC");
$questionsStmt->bind_param("i", $quiz_id);
$questionsStmt->execute();
$questionsResult = $questionsStmt->get_result();
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Questions -
        <?php echo htmlspecialchars($quizName); ?>
    </title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body {
            background-color: #f0f4f8;
        }

        .sidebar {
            height: 100vh;
            background: #2c3e50;
            color: white;
            padding-top: 20px;
            position: fixed;
            width: 250px;
        }

        .sidebar a {
            color: #bdc3c7;
            text-decoration: none;
            display: block;
            padding: 10px 20px;
        }

        .sidebar a:hover,
        .sidebar a.active {
            background: #34495e;
            color: white;
        }

        .main-content {
            margin-left: 250px;
            padding: 40px;
        }

        .card {
            border: none;
            border-radius: 12px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
        }

        .media-preview {
            max-width: 100px;
            max-height: 100px;
            border-radius: 5px;
        }
    </style>
</head>

<body>
    <div class="sidebar">
        <h3 class="text-center mb-4">GameHub Admin</h3>
        <a href="admin.php"><i class="fas fa-home me-2"></i> Dashboard</a>
        <a href="games.php"><i class="fas fa-gamepad me-2"></i> Games</a>
        <a href="manage_quizzes.php" class="active"><i class="fas fa-lightbulb me-2"></i> Quizzes</a>
        <a href="manage_videos.php"><i class="fas fa-video me-2"></i> Video Feed</a>
        <a href="logout.php"><i class="fas fa-sign-out-alt me-2"></i> Logout</a>
    </div>

    <div class="main-content">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a href="manage_quizzes.php">Quizzes</a></li>
                        <li class="breadcrumb-item active">
                            <?php echo htmlspecialchars($quizName); ?>
                        </li>
                    </ol>
                </nav>
                <h2>Manage Questions</h2>
            </div>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addQuestionModal">
                <i class="fas fa-plus me-2"></i> Add Question
            </button>
        </div>

        <?php echo $message; ?>

        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>Type</th>
                                <th>Question</th>
                                <th>Media</th>
                                <th>Answer</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($questionsResult->num_rows > 0): ?>
                                <?php while ($row = $questionsResult->fetch_assoc()): ?>
                                    <tr>
                                        <td><span class="badge bg-secondary">
                                                <?php echo strtoupper($row['type']); ?>
                                            </span></td>
                                        <td>
                                            <?php echo htmlspecialchars($row['question']); ?>
                                        </td>
                                        <td>
                                            <?php if ($row['media_url']): ?>
                                                <i class="fas fa-paperclip text-info"></i>
                                            <?php else: ?>
                                                <span class="text-muted">None</span>
                                            <?php endif; ?>
                                        </td>
                                        <td><span class="text-success fw-bold">
                                                <?php echo htmlspecialchars($row['answer']); ?>
                                            </span></td>
                                        <td>
                                            <a href="delete_question.php?id=<?php echo $row['question_id']; ?>&quiz_id=<?php echo $quiz_id; ?>"
                                                class="btn btn-sm btn-outline-danger" onclick="return confirm('Are you sure?')">
                                                <i class="fas fa-trash"></i>
                                            </a>
                                        </td>
                                    </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="5" class="text-center py-4 text-muted">No questions added yet.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Add Question Modal -->
    <div class="modal fade" id="addQuestionModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <form method="POST" enctype="multipart/form-data">
                    <div class="modal-header">
                        <h5 class="modal-title">Add New Question</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Quiz Type</label>
                                <select name="type" class="form-select" id="quizType" required
                                    onchange="toggleOptions()">
                                    <option value="multiple-choice">Multiple Choice</option>
                                    <option value="true-false">True / False</option>
                                    <option value="voice">Voice Quiz (Audio)</option>
                                    <option value="video">Video Quiz</option>
                                    <option value="emoji">Emoji Quiz</option>
                                    <option value="blur">Blurred Reveal</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Media Type</label>
                                <select name="media_type" class="form-select">
                                    <option value="none">None</option>
                                    <option value="image">Image</option>
                                    <option value="audio">Audio (MP3)</option>
                                    <option value="video">Video (MP4)</option>
                                </select>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Question Text / Hint</label>
                            <textarea name="question" class="form-control" rows="2" required
                                placeholder="e.g. Which game is this theme from?"></textarea>
                        </div>

                        <div class="mb-3" id="mediaUploadField">
                            <label class="form-label">Upload Media File</label>
                            <input type="file" name="media_file" class="form-control">
                        </div>

                        <div id="optionsContainer">
                            <div class="row">
                                <div class="col-md-6 mb-2">
                                    <input type="text" name="option1" class="form-control" placeholder="Option A"
                                        required>
                                </div>
                                <div class="col-md-6 mb-2">
                                    <input type="text" name="option2" class="form-control" placeholder="Option B"
                                        required>
                                </div>
                                <div class="col-md-6 mb-2">
                                    <input type="text" name="option3" class="form-control" placeholder="Option C">
                                </div>
                                <div class="col-md-6 mb-2">
                                    <input type="text" name="option4" class="form-control" placeholder="Option D">
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Correct Answer</label>
                                <input type="text" name="answer" class="form-control" required
                                    placeholder="Exact match of correct option">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Hint (Optional)</label>
                                <input type="text" name="hint_text" class="form-control"
                                    placeholder="e.g. It was released in 1985">
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        <button type="submit" name="add_question" class="btn btn-primary">Save Question</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        function toggleOptions() {
            const type = document.getElementById('quizType').value;
            const container = document.getElementById('optionsContainer');
            if (type === 'true-false') {
                container.style.display = 'none';
            } else {
                container.style.display = 'block';
            }
        }
    </script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
</body>

</html>