<?php 

include('includes/config.php');


?>


<?php
include('includes/user_data.php');

?>
<?php


$teacher_id = $_SESSION['teacher_id'] ?? null;
if (!$teacher_id) {
    echo "You must be logged in as a teacher.";
    exit;
}

// Load dropdown data
$sessions = $dbh->query("SELECT id, session_year FROM sessions ORDER BY session_year DESC")->fetchAll(PDO::FETCH_ASSOC);
$terms    = $dbh->query("SELECT id, term_name FROM terms ORDER BY id")->fetchAll(PDO::FETCH_ASSOC);
$classes  = $dbh->query("SELECT id, name FROM classes ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
$subjects = $dbh->query("SELECT id, name FROM Subjects ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
?>


<!doctype html>
<html lang="en">


<!-- Mirrored from codervent.com/rocker/demo/vertical/user-profile.html by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 26 Aug 2022 06:47:36 GMT -->
<head>
	<!-- Required meta tags -->
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<!--favicon-->
	<link rel="icon" href="assets/images/favicon-32x32.png" type="image/png" />
	<!--plugins-->
	<link href="assets/plugins/simplebar/css/simplebar.css" rel="stylesheet" />
	<link href="assets/plugins/perfect-scrollbar/css/perfect-scrollbar.css" rel="stylesheet" />
	<link href="assets/plugins/metismenu/css/metisMenu.min.css" rel="stylesheet" />
	<!-- loader-->
	<link href="assets/css/pace.min.css" rel="stylesheet" />
	<script src="assets/js/pace.min.js"></script>
	<!-- Bootstrap CSS -->
	<link href="assets/css/bootstrap.min.css" rel="stylesheet">
	<link href="assets/css/bootstrap-extended.css" rel="stylesheet">
	<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&amp;display=swap" rel="stylesheet">
	<link href="assets/css/app.css" rel="stylesheet">
	<link href="assets/css/icons.css" rel="stylesheet">
	<!-- Theme Style CSS -->
	<link rel="stylesheet" href="assets/css/dark-theme.css" />
	<link rel="stylesheet" href="assets/css/semi-dark.css" />
	<link rel="stylesheet" href="assets/css/header-colors.css" />

<title>Create Exam</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>

<body> 
	<!--wrapper-->
	<div class="wrapper">
		<!--sidebar wrapper -->
		<?php include 'includes/side.php'; ?>
		<!--end sidebar wrapper -->
		<!--start header -->
		<?php include 'includes/head.php'; ?>
		<!--end header -->
		<!--start page wrapper -->
		<div class="page-wrapper">
			<div class="page-content">
				<!--breadcrumb-->
				<div class="page-breadcrumb d-none d-sm-flex align-items-center mb-3">
					<div class="breadcrumb-title pe-3"></div>
					<div class="ps-3">
						<nav aria-label="breadcrumb">
							<ol class="breadcrumb mb-0 p-0">
								<li class="breadcrumb-item"><a href="javascript:;"><i class="bx bx-home-alt"></i></a>
								</li>
								<li class="breadcrumb-item active" aria-current="page"></li>
							</ol>
						</nav>
					</div>
					
				</div>
				<!--end breadcrumb-->
				<div class="container">
					<div class="main-body">
						<div class="row">
						
							<div class="col-lg-12">
								<div class="card">
									<div class="card-body">
<?php

if (!isset($_SESSION['teacher_id'])) { echo "Login as teacher."; exit; }
$teacher_id = $_SESSION['teacher_id'];

// load selects
$sessions = $dbh->query("SELECT id, session_year FROM sessions ORDER BY session_year DESC")->fetchAll(PDO::FETCH_ASSOC);
$terms = $dbh->query("SELECT id, term_name FROM terms")->fetchAll(PDO::FETCH_ASSOC);
$classes = $dbh->query("SELECT id, name FROM classes")->fetchAll(PDO::FETCH_ASSOC);
$subjects = $dbh->query("SELECT id, name FROM Subjects")->fetchAll(PDO::FETCH_ASSOC);

// handle POST to create exam
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? '');
    $session_id = (int)($_POST['session_id'] ?? 0);
    $term_id = (int)($_POST['term_id'] ?? 0);
    $class_id = (int)($_POST['class_id'] ?? 0);
    $subject_id = (int)($_POST['subject_id'] ?? 0);
    $duration = (int)($_POST['duration'] ?? 30);
    $start_time = $_POST['start_time'] ?: null;
    $end_time = $_POST['end_time'] ?: null;
    $status = $_POST['status'] ?? 'draft'; // draft or published
    $question_ids = $_POST['questions'] ?? [];

    if (!$title || !$session_id || !$term_id || !$class_id || !$subject_id || !$question_ids) {
        $error = "Please fill all and select at least one question.";
    } else {
        $dbh->beginTransaction();
        $stmt = $dbh->prepare("INSERT INTO exams (teacher_id, title, session_id, term_id, class_id, subject_id, duration_minutes, start_time, end_time, status) VALUES
            (:t, :title, :session, :term, :class, :subject, :dur, :st, :en, :status)");
        $stmt->execute([
            ':t'=>$teacher_id, ':title'=>$title, ':session'=>$session_id, ':term'=>$term_id,
            ':class'=>$class_id, ':subject'=>$subject_id, ':dur'=>$duration, ':st'=>$start_time, ':en'=>$end_time, ':status'=>$status
        ]);
        $exams_id = $dbh->lastInsertId();

        $stmt = $dbh->prepare("INSERT INTO exam_questions (exam_id, question_id, q_order) VALUES (:exam, :qid, :ord)");
        $order = 1;
        foreach ($question_ids as $qid) {
            $stmt->execute([':exam'=>$exams_id, ':qid'=>$qid, ':ord'=>$order++]);
        }
        $dbh->commit();
        //header("Location: teacher_manage_exams.php");
        	echo "<script type='text/javascript'> document.location = 'teacher_manage_exams.php'; </script>";
        exit;
    }
}
?>

  <div class="max-w-6xl mx-auto bg-white p-6 rounded shadow">
    <h1 class="text-xl mb-4">Create Exam</h1>
    <?php if(!empty($error)): ?><div class="text-red-600 mb-3"><?=htmlspecialchars($error)?></div><?php endif;?>
    <form method="post">
      <div class="grid grid-cols-2 gap-4 mb-4">
        <input name="title" placeholder="Exam title" class="border p-2 rounded" />
        <input name="duration" type="number" placeholder="Duration (minutes)" class="border p-2 rounded" value="30"/>
        <select name="session_id" id="session" class="border p-2 rounded">
          <option value="">Session</option><?php foreach($sessions as $s): ?><option value="<?=$s['id']?>"><?=$s['session_year']?></option><?php endforeach; ?>
        </select>
        <select name="term_id" id="term" class="border p-2 rounded">
          <option value="">Term</option><?php foreach($terms as $t): ?><option value="<?=$t['id']?>"><?=$t['term_name']?></option><?php endforeach; ?>
        </select>
        <select name="class_id" id="class" class="border p-2 rounded">
          <option value="">Class</option><?php foreach($classes as $c): ?><option value="<?=$c['id']?>"><?=$c['name']?></option><?php endforeach; ?>
        </select>
        <select name="subject_id" id="subject" class="border p-2 rounded">
          <option value="">Subject</option><?php foreach($subjects as $s): ?><option value="<?=$s['id']?>"><?=$s['name']?></option><?php endforeach; ?>
        </select>
      </div>

      <div class="flex gap-2 mb-4">
        <input type="datetime-local" name="start_time" class="border p-2 rounded" />
        <input type="datetime-local" name="end_time" class="border p-2 rounded" />
        <select name="status" class="border p-2 rounded"><option value="draft">Draft</option><option value="published">Publish</option></select>
      </div>

      <div class="mb-4">
        <div class="flex items-center justify-between mb-2">
          <div class="font-semibold">Select questions (from questions table)</div>
          <div><button id="filterBtn" type="button" class="bg-sky-600 text-white px-3 py-1 rounded text-sm">Filter</button></div>
        </div>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-2">
          <div>
            <label>Filter by Type</label>
            <select id="qtypeFilter" class="border p-2 rounded w-full">
              <option value="">Any</option><option value="objective">Objective</option><option value="fill">Fill</option><option value="theory">Theory</option>
            </select>
          </div>
          <div>
            <label>Search text</label>
            <input id="qsearch" class="border p-2 rounded w-full" placeholder="Search question text"/>
          </div>
        </div>

        <div id="questionsList" class="mt-3 border rounded p-3 max-h-64 overflow-auto bg-gray-50">
          <!-- loaded by AJAX -->
          <div class="text-sm text-gray-500">Choose session/class/term/subject then click Filter</div>
        </div>
      </div>

      <div>
        <button class="bg-green-600 text-white px-4 py-2 rounded">Create Exam</button>
        <a href="teacher_manage_exams.php" class="ml-3 text-sm text-gray-600">Manage Exams</a>
      </div>
    </form>
  </div>

<script>
function loadQuestions() {
  let data = {
    session_id: $("#session").val(),
    term_id: $("#term").val(),
    class_id: $("#class").val(),
    subject_id: $("#subject").val(),
    type: $("#qtypeFilter").val(),
    qsearch: $("#qsearch").val()
  };
  $.get('teacher_load_questions_ajax.php', data, function(html){
    $("#questionsList").html(html);
  });
}

$("#filterBtn").click(loadQuestions);
</script>


							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
		<!--end page wrapper -->
		<!--start overlay-->
		<div class="overlay toggle-icon"></div>
		<!--end overlay-->
		<!--Start Back To Top Button--> <a href="javaScript:;" class="back-to-top"><i class='bx bxs-up-arrow-alt'></i></a>
		<!--End Back To Top Button-->
		<footer class="page-footer">
			<p class="mb-0">Copyright © 2025. All right reserved.</p>
		</footer>
	</div>
	<!--end wrapper-->
	<!--start switcher-->
	<?php include 'includes/customiser.php'; ?>

	<!--end switcher-->
	<!-- Bootstrap JS -->
	<script src="assets/js/bootstrap.bundle.min.js"></script>
	<!--plugins-->
	<script src="assets/js/jquery.min.js"></script>
	<script src="assets/plugins/simplebar/js/simplebar.min.js"></script>
	<script src="assets/plugins/metismenu/js/metisMenu.min.js"></script>
	<script src="assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
	<!--app JS-->
	<script src="assets/js/app.js"></script>
</body>


</html>




