<?php
session_start();
require "../user/db.php";

/* ======================
   SECURITY - CSRF TOKEN
====================== */
if(empty($_SESSION['csrf_token'])){
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

/* ======================
   FETCH COURSES
====================== */
$courses = [];
$res = $conn->query("SELECT id, title FROM courses");
while($row = $res->fetch_assoc()){
    $courses[] = $row;
}

/* ======================
   HANDLE QUIZ CREATION
====================== */
if(isset($_POST['create_quiz'])){
    if(!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])){
        die("CSRF validation failed!");
    }

    $title = htmlspecialchars($_POST['title']);
    $course_id = (int)$_POST['course_id'];
    $instructions = htmlspecialchars($_POST['instructions']);
    $duration = (int)$_POST['duration'];
    $total_marks = (int)$_POST['total_marks'];

    $stmt = $conn->prepare("
        INSERT INTO quizzes (course_id, title, instructions, duration, total_marks)
        VALUES (?, ?, ?, ?, ?)
    ");
    $stmt->bind_param("issii", $course_id, $title, $instructions, $duration, $total_marks);
    if($stmt->execute()){
        $success = "Quiz created! Now you can add questions.";
        $quiz_id = $stmt->insert_id;
    }else{
        $error = "Error creating quiz: ".$stmt->error;
    }
}

/* ======================
   HANDLE ADD QUESTION
====================== */
if(isset($_POST['add_question'])){
    if(!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])){
        die("CSRF validation failed!");
    }

    $quiz_id = (int)$_POST['quiz_id'];
    $question_text = htmlspecialchars($_POST['question_text']);
    $question_type = $_POST['question_type'];

    $stmt = $conn->prepare("
        INSERT INTO quiz_questions (quiz_id, question_text, question_type)
        VALUES (?, ?, ?)
    ");
    $stmt->bind_param("iss", $quiz_id, $question_text, $question_type);
    $stmt->execute();
    $question_id = $stmt->insert_id;

    if($question_type == 'mcq' && !empty($_POST['options'])){
        foreach($_POST['options'] as $opt){
            $opt = htmlspecialchars($opt);
            $stmt2 = $conn->prepare("
                INSERT INTO quiz_options (question_id, option_text)
                VALUES (?, ?)
            ");
            $stmt2->bind_param("is", $question_id, $opt);
            $stmt2->execute();
        }
    }
    $success = "Question added successfully!";
}

/* ======================
   FETCH EXISTING QUIZZES
====================== */
$quizzes = $conn->query("SELECT q.*, c.title as course_title FROM quizzes q JOIN courses c ON c.id=q.course_id ORDER BY q.created_at DESC");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin | Quiz Management</title>
<style>
body {font-family:"Segoe UI",sans-serif; margin:0; background:#f4f6f9; display:flex;}
.sidebar{width:240px; background:#0f172a; color:#fff; height:100vh; padding:20px;}
.sidebar h2{font-size:18px;margin-bottom:20px;}
.sidebar a{display:block; color:#cbd5e1; text-decoration:none; padding:10px 0;}
.sidebar a:hover{color:#fff;}
.main{flex:1; padding:20px;}
.card{background:#fff; padding:20px; border-radius:10px; margin-bottom:20px; box-shadow:0 3px 8px rgba(0,0,0,0.1);}
input, select, textarea{width:100%; padding:10px; border-radius:6px; border:1px solid #cbd5e1; margin-bottom:15px;}
button{padding:12px 25px; border:none; background:#2563eb; color:#fff; border-radius:8px; cursor:pointer;}
button:hover{background:#1d4ed8;}
.grid{display:grid; grid-template-columns:repeat(auto-fit,minmax(220px,1fr)); gap:15px;}
.success{color:green;}
.error{color:red;}
</style>
</head>
<body>

<div class="sidebar">
<h2>Admin Panel</h2>
<a href="#">Dashboard</a>
<a href="#">Courses</a>
<a href="#">Quizzes</a>
<a href="#">Submissions</a>
<a href="#">Logout</a>
</div>

<div class="main">
<h1>Quiz Management</h1>

<?php if(isset($success)) echo "<p class='success'>$success</p>"; ?>
<?php if(isset($error)) echo "<p class='error'>$error</p>"; ?>

<!-- CREATE QUIZ -->
<div class="card">
<h3>Create New Quiz</h3>
<form method="POST">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<label>Quiz Title</label>
<input type="text" name="title" required>

<label>Course</label>
<select name="course_id" required>
<option value="">Select Course</option>
<?php foreach($courses as $course): ?>
<option value="<?= $course['id'] ?>"><?= htmlspecialchars($course['title']) ?></option>
<?php endforeach; ?>
</select>

<label>Duration (minutes)</label>
<input type="number" name="duration" min="1" required>

<label>Total Marks</label>
<input type="number" name="total_marks" min="1" required>

<label>Instructions</label>
<textarea name="instructions"></textarea>

<button type="submit" name="create_quiz">Create Quiz</button>
</form>
</div>

<!-- ADD QUESTION TO LAST CREATED QUIZ -->
<?php if(isset($quiz_id)): ?>
<div class="card">
<h3>Add Questions to Quiz</h3>
<form method="POST">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="quiz_id" value="<?= $quiz_id ?>">

<label>Question Text</label>
<textarea name="question_text" required></textarea>

<label>Question Type</label>
<select name="question_type" id="q_type" onchange="showOptions()">
<option value="short_answer">Short Answer</option>
<option value="mcq">Multiple Choice (MCQ)</option>
</select>

<div id="mcq_options" style="display:none;">
<label>Options (one per line)</label>
<textarea name="options[]"></textarea>
<textarea name="options[]"></textarea>
<textarea name="options[]"></textarea>
<textarea name="options[]"></textarea>
</div>

<button type="submit" name="add_question">Add Question</button>
</form>
</div>
<script>
function showOptions(){
    const type = document.getElementById('q_type').value;
    document.getElementById('mcq_options').style.display = (type=='mcq')?'block':'none';
}
</script>
<?php endif; ?>

<!-- EXISTING QUIZZES -->
<div class="card">
<h3>Existing Quizzes</h3>
<table border="1" cellpadding="10" cellspacing="0">
<tr><th>ID</th><th>Title</th><th>Course</th><th>Duration</th><th>Total Marks</th><th>Actions</th></tr>
<?php while($q = $quizzes->fetch_assoc()): ?>
<tr>
<td><?= $q['id'] ?></td>
<td><?= htmlspecialchars($q['title']) ?></td>
<td><?= htmlspecialchars($q['course_title']) ?></td>
<td><?= $q['duration'] ?> min</td>
<td><?= $q['total_marks'] ?></td>
<td><a href="view_submissions.php?quiz_id=<?= $q['id'] ?>">View Submissions</a></td>
</tr>
<?php endwhile; ?>
</table>
</div>

</div>
</body>
</html>
