0% found this document useful (0 votes)
0 views

Web Project

The document outlines a project proposal for a Digital Quiz Management System tailored for Diffun National High School, aiming to modernize assessment processes and improve student performance tracking. It includes requirements elicitation from administrators, teachers, and students, highlighting their specific needs and preferences. The system will feature comprehensive management tools, real-time analytics, and a user-friendly interface to enhance the educational experience.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Web Project

The document outlines a project proposal for a Digital Quiz Management System tailored for Diffun National High School, aiming to modernize assessment processes and improve student performance tracking. It includes requirements elicitation from administrators, teachers, and students, highlighting their specific needs and preferences. The system will feature comprehensive management tools, real-time analytics, and a user-friendly interface to enhance the educational experience.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

QUIRINO STATE UNIVERSITY

COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES


Diffun Campus

DIGITAL QUIZ MANAGEMENT SYSTEM


FOR DIFFUN NATIONAL HIGH SCHOOL

A Midterm Project Presented to the Faculty of


Bachelor of Science in Information Technology
College of Information Technology and Computing Sciences

In Partial Fulfillment of the Requirements in


System Integration and Architecture 1, Web System and
Technology 2, and Advance Database System

Submitted By:
YONARD ALIGGOY

ALDRIN TAPAYA

JEREMY NEIL PUNZALAN

HASPER DHAN BUCAHAN

MARK NEIL CONSOLACION

Project Adviser:
MS. GAZELLE NAZARO
MR. WILLIAM SABUG JR.
MS. DIVINE GRACE OLAÑO

Date: May 16, 2025


QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

*Requirements Elicitation

This questionnaire will help us understand your needs for our Quiz Management System. Please select the option
that best represents your preferences.

For Administrator

1. What administrative features would be most valuable in a quiz management system?

 Comprehensive account management for teachers and students.


 Subject and curriculum oversight tools.
 System usage statistics and performance analytics.
 Security controls and access management.
2. What security features would you require in an online assessment system?

 Role-based access controls for different user types.


 Data encryption for sensitive information.
 Audit logging of all system activities.
 Compliance with educational data protection standards.

For Teachers

1. What quiz creation tools would improve your assessment process?

 Variety of question types (multiple-choice, true/false, essay, etc.).


 Question bank for storing and reusing questions.
 Media integration capabilities (images, diagrams, formulas).
 Customizable grading and feedback options.
2. What assessment management features do you need?

 Flexible scheduling with automatic open/close times.


 Options for time limits and attempt restrictions.
 Automated grading for objective questions.
 Detailed analytics on question performance.
3. How do you prefer to manage student assessments?

 Schedule quizzes with specific open/close times.


 Provide immediate automated feedback for objective questions.
 Manually grade subjective questions with detailed feedback.
 Generate performance analytics to identify learning gaps.
4. What materials management capabilities would enhance your course delivery?

 Upload various document types and provide web resource links.


 Track which students have accessed materials.
 Organize materials by topic and relate them to specific quizzes.
 Schedule material availability based on course progression.
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

For Students

1. What features would most improve your quiz-taking experience?

 Clear navigation with ability to flag questions for review.


 Visible timer with automatic submission when time expires.
 Stable performance that saves answers as you progress.
 Mobile-friendly interface for taking quizzes on any device.
2. How do you prefer to access and review your quiz results?

 Immediate feedback showing correct/incorrect answers.


 Detailed explanations for incorrect answers.
 Performance comparison with class averages (anonymized).
 Cumulative progress tracking across all assessments.
3. What would make accessing learning materials most convenient?

 All materials organized by topic with clear relevance to quizzes.


 Mobile-friendly formats for studying on any device.
 Ability to mark materials as “completed” to track progress.
 Notification when new materials are available.
4. How would you prefer to enroll in and manage your subjects?

 Simple enrollment using teacher-provided class codes.


 Dashboard showing all enrolled subjects with upcoming deadlines.
 Easy access to teacher contact information for questions.
 Calendar integration showing all quiz schedules
*Result

Response of the Administrator


Question Response
1. What administrative features would be most Comprehensive account management for teachers and
valuable in a quiz management system? students.

2. What security features would you require in an Compliance with educational data protection standards.
online assessment system?

Responses of the Teacher


Questions
1. What quiz creation 2. What assessment 3. How do you prefer to 4. What materials
tools would improve management features manage student management capabilities
your assessment do you need? assessments? would enhance your
process? course delivery?

Responses
Teacher Variety of question Detailed analytics on Schedule quizzes with Track which students
1 types (multiple- question performance. specific open/close have accessed materials.
choice, true/false, times.
essay, etc.).

Teacher Variety of question Detailed analytics on Schedule quizzes with Upload various document
2 types (multiple- question performance. specific open/close types and provide web
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

choice, true/false, times. resource links.


essay, etc.).

Teacher Variety of question Options for time limits Provide immediate Upload various document
3 types (multiple- and attempt automated feedback types and provide web
choice, true/false, restrictions. for objective questions. resource links.
essay, etc.).

Teacher Variety of question Flexible scheduling Manually grade Organize materials by


4 types (multiple- with automatic subjective questions topic and relate them to
choice, true/false, open/close times. with detailed feedback. specific quizzes.
essay, etc.).

Teacher Variety of question Automated grading for Generate performance Organize materials by
5 types (multiple- objective questions. analytics to identify topic and relate them to
choice, true/false, learning gaps. specific quizzes.
essay, etc.).

Teacher Variety of question Detailed analytics on Schedule quizzes with Upload various document
6 types (multiple- question performance. specific open/close types and provide web
choice, true/false, times. resource links.
essay, etc.).

Teacher Variety of question Options for time limits Schedule quizzes with Schedule material
7 types (multiple- and attempt specific open/close availability based on
choice, true/false, restrictions. times. course progression.
essay, etc.).

Responses of the Students


Questions
1. What features would 2. How do you prefer to 3. What would make 4. How would you
most improve your access and review your accessing learning prefer to enroll in and
quiz-taking experience? quiz results? materials most manage your
convenient? subjects?

Responses
Student 1 Visible timer with Immediate feedback Mobile-friendly Dashboard showing
automatic submission showing formats for studying all enrolled subjects
when time expires. correct/incorrect on any device. with upcoming
answers. deadlines.

Student 2 Visible timer with Immediate feedback Ability to mark Simple enrollment
automatic submission showing materials as using teacher-
when time expires. correct/incorrect “completed” to track provided class codes.
answers. progress.

Student 3 Clear navigation with Detailed explanations Ability to mark Easy access to teacher
ability to flag questions for incorrect answers. materials as contact information
for review. “completed” to track for questions.
progress.
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

Student 4 Visible timer with Performance All materials Calendar integration


automatic submission comparison with class organized by topic showing all quiz
when time expires. averages (anonymized). with clear relevance schedules
to quizzes.

Student 5 Stable performance Cumulative progress Mobile-friendly Dashboard showing


that saves answers as tracking across all formats for studying all enrolled subjects
you progress. assessments. on any device. with upcoming
deadlines.

Student 6 Visible timer with Immediate feedback Ability to mark Dashboard showing
automatic submission showing materials as all enrolled subjects
when time expires. correct/incorrect “completed” to track with upcoming
answers. progress. deadlines.
Student 7 Mobile-friendly Immediate feedback All materials Simple enrollment
interface for taking showing organized by topic using teacher-
quizzes on any device. correct/incorrect with clear relevance provided class codes.
answers. to quizzes.

-Summary of Findings

The interview data reveals clear priorities for each stakeholder group in a quiz management system:

For Administrators

 Primary focus on comprehensive account management

 Strong concern for educational data protection compliance

For Teachers

 Universal need for diverse question types

 High demand for detailed analytics capabilities

 Preference for scheduled quizzes with defined timeframes

 Interest in tracking student engagement with materials

For Students

 Critical need for visible timers with automatic submission

 Strong preference for immediate feedback on answers

 Desire to track their own progress through materials

 Need for centralized dashboards showing all enrolled subjects

These findings highlight the importance of developing a system that balances administrative control, teaching
flexibility, and student-centered features.
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

-Requiurement Elicitation Process

Student

Teacher

Admin
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

*Purpose

The Diffun National High School Quiz Management System is a specialized web-based platform designed to
modernize and streamline the assessment process within the school. This system serves as a digital solution for
managing quizzes, distributing educational materials, and tracking student performance, specifically tailored to
meet the academic needs of Diffun National High School.

Problems/Challenges
 Manual Quiz Administration
Teachers spend significant time preparing, distributing, and checking quizzes, which leads to inefficiencies
and increases the risk of errors.Inefficient and time-consuming assessment processes: Teachers rely on
manual methods for creating quizzes, distributing materials, and grading assessments.
 Limited Performance Tracking
There is no centralized or real-time system for monitoring and analyzing student performance, making it
hard to identify learning gaps and trends.
 Scalability of Quiz Management
Managing quizzes across multiple classes, subjects, and student groups becomes increasingly complex and
disorganized without a digital solution.
 Lack of Immediate Feedback for Students
In manual setups, students often wait a long time to receive their quiz results, delaying opportunities to
reflect and improve on their mistakes.

*Objectives:

 General Objective: develop a digital quiz management system that provides a centralized platform for
efficient assessment processes, improved access to learning resources, and effective student progress
tracking.
 Specific Objectives:
1. Streamline the assessment process by enabling teachers to create, manage, and distribute quizzes
electronically.
2. Provide a platform for teachers to upload and share learning materials with students, enhancing their
access to resources.
3. Develop a system that allows teachers to track student performance on quizzes and generate
comprehensive reports for monitoring progress.

*Features

The system offers comprehensive features including:


 Admin Features: Manage teacher and student accounts, including creating teacher profiles with assigned
class codes and subjects, editing teacher and student information, resetting student passwords, deleting
accounts, and handling password recovery.
 Role-based access control: Distinct access for students, teachers, and administrators.
 Quiz creation and management tools: Teachers can create and customize quizzes with various question
types.
 Educational material distribution system: Teachers can upload and distribute learning materials to specific
classes.
 Real-time performance tracking and analytics: The system tracks student responses and calculates scores.
It also provides detailed performance analytics for individual students.
 Automated score calculation and reporting: The system automatically calculates scores and generates
reports.
 Subject-based organization of content: Materials and quizzes can be categorized by subject.
 Class-specific access controls: Students can access only materials and quizzes relevant to their classes.
 Academic performance visualization: Interactive graphs for visual representation of performance metrics.
 Multiple question type support: System handles multiple choice, true/false, identification, enumeration,
and essay questions.
 Time-limited quiz taking: Students have specific time limits for completing quizzes.
 Student progress monitoring: Teacher can track individual student progress and performance.
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

* Scope and Deliverables

-Scope:
The Quiz Management System is a web-based application designed to facilitate the creation, administration, and
taking of quizzes in an educational setting. The system supports three user roles: Admin, Teacher, and Student.
Admins can manage users and system settings, Teachers can create and manage quizzes with various question types
(Multiple Choice, True/False, Identification, Enumeration, and Essay), upload learning materials, and view student
performance analytics. Students can take quizzes, view their results, and access learning materials. The system
includes features for class enrollment, quiz scheduling, automatic grading for objective questions, manual grading
for essays, and comprehensive analytics for tracking student performance.

-Deliverable:
The project deliverables include a fully functional web application built with PHP and MySQL, designed to run on a
local XAMPP server environment. The system will include complete documentation covering local installation steps,
user guides for each role, and technical documentation. The source code will be delivered with proper comments
and structure, along with the database schema and sample data. The project will also include test cases and results
to ensure system reliability and security. A comprehensive deployment package will be included, containing all
necessary files and configuration settings for seamless installation on a local XAMPP server environment.

-Limitations and Alternative Solutions


While the system does not include a self-service forgot password functionality for Teacher and Student logins due
to implementation challenges, an alternative solution has been implemented where the Admin dashboard includes
a feature to reset passwords for Teachers and Students as needed. This approach maintains security while providing
a practical password recovery solution administered by system administrators.

The system currently does not implement functionality to detect or prevent students from switching windows/tabs
(using Alt+Tab) or leaving the quiz to search for answers in other browser windows during an assessment. This
monitoring and prevention capability will be considered for future implementation. In the current version, the
system cannot track if a student navigates away from the quiz page or opens additional tabs/windows to search for
answers. Teachers administering quizzes should be aware of this limitation and may need to implement traditional
proctoring methods for high-stakes assessments.

*Review of Related Literature or Studies

Ibrahim et al. (2022) conducted a study that demonstrated how implementing an online management system
significantly streamlined the process of assessing student outcomes. Their research highlighted that such systems
not only enhanced efficiency but also provided administrators with valuable reports and visual data, facilitating
more informed decision-making. This suggests that technology integration in educational assessments can optimize
administrative tasks and improve overall assessment quality.

Barahona et al. (2024) explored the impact of early alert systems embedded within quiz-based activities. Their
findings revealed that these systems contributed to improvements in student academic performance by providing
timely notifications and feedback. Teachers also responded positively to this innovation, indicating that early
intervention tools integrated with assessments can play a crucial role in supporting student success.

In the context of modular distance learning, Taza et al. (2024) emphasized the importance of improved tracking
tools. Their study found that enhanced monitoring mechanisms allowed educators to provide more effective
feedback and closely follow students’ academic development despite remote learning challenges. This points to the
growing need for reliable tracking solutions in distance education environments to ensure sustained student
engagement and progress.

The LiquiZ Study (2023) investigated the implementation of adaptive quizzes featuring real-time feedback. This
adaptive quizzing approach enabled educators to detect learning issues early, allowing for immediate instructional
adjustments and student support. The study concluded that such dynamic assessment methods foster timely
intervention, which can lead to more effective learning outcomes.

Santos et al. (2023) focused on game-based digital quizzes, such as those offered by platforms like Quizizz. Their
research demonstrated that these interactive tools significantly increased student participation and engagement
during assessments. Additionally, game-based quizzes proved effective for subject-specific evaluations, suggesting
that incorporating gamification in assessments can motivate students and enhance learning experiences.
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

Mauricio et al. (2017) examined the role of centralized learning platforms in simplifying the distribution of
educational content and assessments. Their findings indicated that centralization improved the efficiency of lesson
management, reducing administrative burdens for educators and creating a more organized learning environment.

Al-Anqoudi et al. (2023) surveyed teacher perceptions regarding digital assessment tools, particularly during periods
of remote instruction. The results showed that teachers found these tools beneficial not only for engaging students
but also for supporting learning continuity in challenging circumstances, such as during the COVID-19 pandemic.

Lastly, the Springer Study (2024) provided an overview of Learning Management System (LMS) implementations.
While LMSs have proven useful for organizing assessments and course content, the study noted that their full
potential is sometimes underutilized. This suggests that further development and training may be needed to
maximize the effectiveness of these systems in educational institutions.

*Timeline

 Project Duration: April 12, 2024 - May 12, 2024 (1 Month)

*Key Milestones:

April 7 – Requirements and design documentation complete


April 21: Core functionality implemented
May 12: Testing complete
May 16: Project delivery (localhost version)
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

*System Architecture Diagram

User

Student Portal Teacher Portal Admin Portal

Frontend Backend
( HTML 5, CSS, (PHP, MYSQL, and
JavaScript, Font Awesome 6.4 and APACHE(XAMPP))

Bootstrap 5.3 )
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

Architecture Overview
The Quiz Management System follows a three-tier client-server architecture with distinct presentation, application,
and data layers. The system is designed with role-based access control supporting three user types: students,
teachers, and administrators.

Frontend Architecture (Presentation Layer)


The frontend presentation layer is implemented using modern web technologies:
 HTML5: Provides the structural foundation for all user interfaces, implementing semantic markup for improved
accessibility and SEO.
 CSS3: Handles all styling aspects, including responsive design elements that ensure compatibility across various
device sizes.
 JavaScript: Implements client-side functionality for dynamic content rendering, form validation, and
asynchronous interactions with the backend.
 Bootstrap 5.3: Serves as the primary CSS framework, providing responsive grid systems, pre-styled components,
and utility classes that ensure a consistent user experience while reducing development time.
The system features three distinct login interfaces:
1. Student login portal
2. Teacher login portal
3. Administrator login portal
Each interface provides role-specific functionality and access controls appropriate to the user type.

Backend Architecture (Application & Data Layers)


The backend services are built using a traditional LAMP stack approach:
-PHP: Functions as the server-side scripting language that processes user requests, implements business logic, and
handles database interactions. PHP is used for session management, authentication, and generating dynamic content.
-MySQL: Serves as the relational database management system that stores all persistent data including:
 User credentials and profiles
 Quiz content and questions
 Student responses and scores
 Course/subject information
 Learning materials
-Apache (XAMPP): Provides the web server environment that hosts the application, handles HTTP requests, and
serves content to users. XAMPP bundles Apache, MySQL, PHP, and other components in a single portable package,
simplifying development and deployment.
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

*Database Design: ER diagram, schema, and tables.

-ER diagram

*schema and table:

CREATE TABLE `enrollments` (


`id` int(11) NOT NULL,
`student_id` int(11) NOT NULL,
`subject_id` int(11) NOT NULL,
`teacher_id` int(11) NOT NULL,
`class_code` varchar(255) NOT NULL,
`enrolled_at` timestamp NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

CREATE TABLE `materials` (


`id` int(11) NOT NULL,
`material_title` varchar(100) NOT NULL,
`material_type` enum('Document','Link') NOT NULL,
`material_link` text DEFAULT NULL,
`file_path` text DEFAULT NULL,
`instructor_id` int(11) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT current_timestamp(),
`class_code` varchar(255) NOT NULL,
`done` tinyint(1) DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci

CREATE TABLE `options` (


`id` int(11) NOT NULL,
`question_id` int(11) NOT NULL,
`option_text` varchar(255) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

CREATE TABLE `questions` (


`id` int(11) NOT NULL,
`quiz_id` int(11) NOT NULL,
`question_text` text NOT NULL,
`question_type` enum('multiple_choice','true_false','identification','enumeration','essay') NOT NULL,
`correct_answer` text NOT NULL,
`points` int(11) NOT NULL DEFAULT 1,
`created_at` timestamp NOT NULL DEFAULT current_timestamp(),
`essay_points` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

CREATE TABLE `quizzes` (


`id` int(11) NOT NULL,
`quiz_title` varchar(100) NOT NULL,
`quiz_type` enum('multiple_choice','true_false','identification','enumeration','essay','mixed') NOT NULL,
`closing_time` datetime DEFAULT NULL,
`teacher_id` int(11) NOT NULL,
`subject_id` int(11) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT current_timestamp(),
`open_time` datetime DEFAULT NULL,
`close_time` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

CREATE TABLE `results` (


`id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`quiz_id` int(11) NOT NULL,
`score` int(11) NOT NULL,
`essay_grade` int(11) DEFAULT NULL,
`total_questions` int(11) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT current_timestamp(),
`essay_answer` text DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

CREATE TABLE `student_material_status` (


`id` int(11) NOT NULL,
`student_id` int(11) NOT NULL,
`material_id` int(11) NOT NULL,
`done` tinyint(1) DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

CREATE TABLE `student_quiz_answers` (


`id` int(11) NOT NULL,
`quiz_id` int(11) NOT NULL,
`question_id` int(11) NOT NULL,
`student_id` int(11) NOT NULL,
`answer` text NOT NULL,
`created_at` datetime NOT NULL,
`points_earned` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

CREATE TABLE `student_quiz_status` (


`id` int(11) NOT NULL,
`student_id` int(11) NOT NULL,
`quiz_id` int(11) NOT NULL,
`done` tinyint(1) DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

CREATE TABLE `teachers` (


`id` int(11) NOT NULL,
`username` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`last_name` varchar(50) NOT NULL,
`first_name` varchar(50) NOT NULL,
`middle_name` varchar(50) DEFAULT NULL,
`subject` varchar(255) NOT NULL,
`class_code` varchar(255) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

CREATE TABLE `teacher_subjects` (


`id` int(11) NOT NULL,
`teacher_id` int(11) NOT NULL,
`subject` varchar(100) NOT NULL,
`class_code` varchar(50) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT current_timestamp(),
`is_active` tinyint(1) DEFAULT 1,
`updated_at` timestamp NULL DEFAULT NULL ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

CREATE TABLE `users` (


`id` int(11) NOT NULL,
`username` varchar(50) NOT NULL,
`email` varchar(100) NOT NULL,
`password` varchar(255) NOT NULL,
`role` enum('admin','teacher','student') NOT NULL,
`last_name` varchar(100) NOT NULL,
`first_name` varchar(100) NOT NULL,
`middle_name` varchar(100) DEFAULT NULL,
`created_at` timestamp NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

*php codes

-index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Diffun National High School - Quiz Management System</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<!-- Hero Section -->
<div class="hero-section">
<div class="container text-center">
<h1 class="display-4 fw-bold mb-3">Welcome to Diffun National High School Quiz Management System</h1>
<p class="lead mb-4">Manage and participate in quizzes with ease. Start your learning journey now!</p>
</div>
</div>

<!-- Login Cards Section -->


<div class="container">
<div class="row justify-content-center">
<div class="col-md-4">
<div class="card h-100 shadow">
<div class="card-body text-center">
<i class="fas fa-user-graduate text-primary mb-3 icon-large"></i>
<h3 class="card-title mb-4">Student Portal</h3>
<p class="card-text mb-4">Access your quizzes, assignments, and track your progress.</p>
<a href="student_login.php" class="btn btn-primary btn-lg w-100">Student Login</a>
</div>
</div>
</div>

<div class="col-md-4">
<div class="card h-100 shadow">
<div class="card-body text-center">
<i class="fas fa-chalkboard-teacher text-success mb-3 icon-large"></i>
<h3 class="card-title mb-4">Teacher Portal</h3>
<p class="card-text mb-4">Manage your classes, quizzes, and interact with students.</p>
<a href="teacher_login.php" class="btn btn-success btn-lg w-100">Teacher Login</a>
</div>
</div>
</div>

<div class="col-md-4">
<div class="card h-100 shadow">
<div class="card-body text-center">
<i class="fas fa-user-shield text-dark mb-3 icon-large"></i>
<h3 class="card-title mb-4">Admin Portal</h3>
<p class="card-text mb-4">Manage teacher accounts and students.</p>
<br>
<a href="admin_login.php" class="btn btn-dark btn-lg w-100">Admin Login</a>
</div>
</div>
</div>
</div>
</div>

<!-- Footer -->


<div class="footer text-center">
<div class="container">
<p class="mb-0">© 2025 Diffun National High School. All rights reserved.</p>
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

</div>
</div>

<!-- Bootstrap & Font Awesome JS -->


<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

-login.php
<?php
session_start();
include 'config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {


$username = htmlspecialchars(trim($_POST['username']));
$password = htmlspecialchars(trim($_POST['password']));
$role = htmlspecialchars(trim($_POST['role']));

if ($role === 'teacher') {


// Check if the user exists in the teachers table
$stmt = $conn->prepare("SELECT * FROM teachers WHERE username = ?");
} elseif ($role === 'student' || $role === 'admin') {
// Check if the user exists in the users table
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
} else {
$_SESSION['error'] = "Invalid role selected.";
header("Location: index.php");
exit();
}

$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 1) {
$user = $result->fetch_assoc();
// Debug: Check what's being fetched
error_log("User data: " . print_r($user, true));

// Verify password
if (password_verify($password, $user['password'])) {
$_SESSION['user_id'] = $user['id'];
$_SESSION['role'] = $role;
$_SESSION['username'] = $user['username'];
$_SESSION['first_name'] = $user['first_name'];

// Debug: Check session data


error_log("Session data: " . print_r($_SESSION, true));

// Redirect based on role


if ($role === 'teacher') {
header("Location: teacher_dashboard.php");
} elseif ($role === 'student') {
header("Location: student_dashboard.php");
} elseif ($role === 'admin') {
header("Location: admin_dashboard.php");
}
exit();
} else {
$_SESSION['error'] = "Invalid username or password.";
}
} else {
$_SESSION['error'] = "Invalid username or password.";
}
$stmt->close();
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

// Redirect back to the appropriate login page based on role


if ($role === 'teacher') {
header("Location: teacher_login.php");
} elseif ($role === 'student') {
header("Location: student_login.php");
} elseif ($role === 'admin') {
header("Location: admin_login.php");
}
exit();
}
?>

-config.php
<?php
$servername = "localhost";
$username = "root"; // Default username for XAMPP
$password = ""; // Default password for XAMPP
$dbname = "quiz_management_system";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Insert admin account if it doesn't exist


$admin_username = 'admin';
$admin_password = password_hash('admin_password', PASSWORD_BCRYPT);
$admin_email = '[email protected]';
$admin_role = 'admin';

$stmt = $conn->prepare("INSERT INTO users (username, email, password, role) VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE username=?, email=?, password=?, role=?");
$stmt->bind_param("ssssssss", $admin_username, $admin_email, $admin_password, $admin_role,
$admin_username, $admin_email, $admin_password, $admin_role);

if (!$stmt->execute()) {
error_log("Error creating admin account: " . $stmt->error);
die("Error creating admin account: " . $stmt->error);
}

$stmt->close();

// Function to prevent caching and back-button access


function preventBackButton() {
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
}
?>

-admin_dashboard.php
<?php
session_start();
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
header("Location: index.php");
exit();
}

include 'config.php';
preventBackButton();
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

// Check if there are any session messages (success or error)


$success_message = isset($_SESSION['success']) ? $_SESSION['success'] : null;
$error_message = isset($_SESSION['error']) ? $_SESSION['error'] : null;

// Fetch teachers
$stmt = $conn->prepare("
SELECT t.id, t.last_name, t.first_name, t.middle_name, t.username,
CONCAT(LEFT(t.email, 1), REPEAT('*', LENGTH(SUBSTRING_INDEX(t.email, '@', 1)) - 2),
RIGHT(SUBSTRING_INDEX(t.email, '@', 1), 1), '@', LEFT(SUBSTRING_INDEX(t.email, '@', -1), 1), REPEAT('*',
LENGTH(SUBSTRING_INDEX(SUBSTRING_INDEX(t.email, '@', -1), '.', 1)) - 1), '.com') as email,
GROUP_CONCAT(DISTINCT ts.subject) as subjects,
GROUP_CONCAT(DISTINCT ts.class_code) as class_codes,
t.created_at
FROM teachers t
LEFT JOIN teacher_subjects ts ON t.id = ts.teacher_id
GROUP BY t.id
ORDER BY t.last_name ASC, t.first_name ASC
");
$stmt->execute();
$teachers_result = $stmt->get_result();

// Fetch teacher's subjects


$stmt = $conn->prepare("SELECT DISTINCT subject FROM teacher_subjects WHERE teacher_id = ?");
$stmt->bind_param("i", $teacher_id);
$stmt->execute();
$subjects_result = $stmt->get_result();
$subjects = [];
while ($row = $subjects_result->fetch_assoc()) {
$subjects[] = $row['subject'];
}
$stmt->close();

// Get selected subject from URL parameter


$selected_subject = isset($_GET['subject']) ? $_GET['subject'] : '';

// Fetch quizzes based on selected subject


if (!empty($selected_subject)) {
$stmt = $conn->prepare("
SELECT q.id, q.quiz_title, q.quiz_type, q.created_at, ts.subject, ts.class_code
FROM quizzes q
JOIN teacher_subjects ts ON q.subject_id = ts.id
WHERE q.teacher_id = ? AND ts.subject = ?
ORDER BY q.created_at asc
");
$stmt->bind_param("is", $teacher_id, $selected_subject);
} else {
$stmt = $conn->prepare("
SELECT q.id, q.quiz_title, q.quiz_type, q.created_at, ts.subject, ts.class_code
FROM quizzes q
JOIN teacher_subjects ts ON q.subject_id = ts.id
WHERE q.teacher_id = ?
ORDER BY q.created_at asc
");
$stmt->bind_param("i", $teacher_id);
}
$stmt->execute();
$quizzes = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// Fetch materials based on selected subject


if (!empty($selected_subject)) {
$stmt = $conn->prepare("
SELECT m.*, ts.subject, ts.class_code
FROM materials m
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

JOIN teacher_subjects ts ON m.class_code = ts.class_code


WHERE m.instructor_id = ? AND ts.subject = ? AND ts.teacher_id = ?
");
$stmt->bind_param("isi", $teacher_id, $selected_subject, $teacher_id);
} else {
$stmt = $conn->prepare("
SELECT m.*, ts.subject, ts.class_code
FROM materials m
JOIN teacher_subjects ts ON m.class_code = ts.class_code
WHERE m.instructor_id = ? AND ts.teacher_id = ?
");
$stmt->bind_param("ii", $teacher_id, $teacher_id);
}
$stmt->execute();
$materials = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// Fetch enrolled students based on selected subject


if (!empty($selected_subject)) {
$stmt = $conn->prepare("
SELECT u.id as student_id, u.username, u.email, ts.class_code, e.enrolled_at
FROM enrollments e
JOIN users u ON e.student_id = u.id
JOIN teacher_subjects ts ON e.subject_id = ts.id
WHERE e.teacher_id = ? AND ts.subject = ?
ORDER BY e.enrolled_at asc
");
$stmt->bind_param("is", $teacher_id, $selected_subject);
} else {
$stmt = $conn->prepare("
SELECT u.id as student_id, u.username, u.email, ts.class_code, e.enrolled_at
FROM enrollments e
JOIN users u ON e.student_id = u.id
JOIN teacher_subjects ts ON e.subject_id = ts.id
WHERE e.teacher_id = ?
ORDER BY e.enrolled_at asc
");
$stmt->bind_param("i", $teacher_id);
}
$stmt->execute();
$students = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin Dashboard - Diffun National High School</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
.navbar {
background-color: #343a40;
}
.navbar-brand {
color: white !important;
}
.nav-link {
color: rgba(255,255,255,.75) !important;
}
.nav-link:hover {
color: white !important;
}
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

.password-toggle {
position: absolute;
right: 0;
top: 50%;
transform: translateY(-50%);
cursor: pointer;
color: #6c757d;
z-index: 999;
background: transparent;
border: none;
outline: none;
padding: 0 15px;
height: 100%;
display: flex;
align-items: center;
}
.password-container {
position: relative;
width: 100%;
}
.password-container .input-group {
position: relative;
width: 100%;
}
.password-container input {
padding-right: 45px;
width: 100%;
}
.password-container input.is-invalid {
padding-right: 45px;
background-image: none;
background-position: unset;
}
.input-group-text {
z-index: 1;
}
.alert {
position: fixed;
top: 20px;
left: 50%;
transform: translateX(-50%);
min-width: 300px;
max-width: 500px;
z-index: 9999;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
border-left: 4px solid;
animation: slideIn 0.3s ease-out;
text-align: center;
}
.alert-success {
background-color: #d4edda;
color: #155724;
border-left-color: #28a745;
}
.alert-danger {
background-color: #f8d7da;
color: #721c24;
border-left-color: #dc3545;
}
@keyframes slideIn {
from {
transform: translate(-50%, -100%);
opacity: 0;
}
to {
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

transform: translate(-50%, 0);


opacity: 1;
}
}
.invalid-feedback {
display: none;
opacity: 0;
transition: opacity 0.3s ease-in-out;
}
.invalid-feedback.show {
display: block;
opacity: 1;
}
.is-invalid {
border-color: #dc3545;
}
.is-invalid:focus {
border-color: #dc3545;
box-shadow: 0 0 0 0.25rem rgba(220, 53, 69, 0.25);
}
</style>
<script>
// JavaScript to toggle between sections
function showSection(sectionId) {
// Hide all sections
document.querySelectorAll('.section').forEach(section => {
section.style.display = 'none';
});

// Show the selected section


document.getElementById(sectionId).style.display = 'block';

// If going to home section, clear form data


if (sectionId === 'home') {
// Clear form fields
document.querySelectorAll('#create-account input').forEach(input => {
input.value = '';
});
// Clear any error messages
const errorAlert = document.querySelector('#create-account .alert');
if (errorAlert) {
errorAlert.remove();
}
}
}

// JavaScript to remove alert messages after 5 seconds


function removeAlertMessages() {
setTimeout(function() {
const alertMessages = document.querySelectorAll('.alert');
alertMessages.forEach(alert => {
alert.style.display = 'none';
});
}, 2500);
}

// Show the correct section on page load


document.addEventListener('DOMContentLoaded', function() {
removeAlertMessages();
const urlParams = new URLSearchParams(window.location.search);
const section = urlParams.get('section');
if (section) {
showSection(section);
}
});
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

// Function to toggle password visibility


function togglePassword(inputId) {
const passwordInput = document.getElementById(inputId);
const icon = passwordInput.nextElementSibling;

if (passwordInput.type === 'password') {


passwordInput.type = 'text';
icon.classList.remove('fa-eye');
icon.classList.add('fa-eye-slash');
} else {
passwordInput.type = 'password';
icon.classList.remove('fa-eye-slash');
icon.classList.add('fa-eye');
}
}

// Email validation
const emailInput = document.getElementById('email');
const emailError = document.getElementById('emailError');

emailInput.addEventListener('input', function() {
const email = this.value;
if (email) {
// Check if email exists
fetch('create_teacher_process.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: 'check_email=true&email=' + encodeURIComponent(email)
})
.then(response => response.json())
.then(data => {
if (data.exists) {
emailInput.classList.add('is-invalid');
emailError.style.display = 'block';
emailError.style.opacity = '1';
} else {
emailInput.classList.remove('is-invalid');
emailError.style.display = 'none';
emailError.style.opacity = '0';
}
})
.catch(error => {
console.error('Error:', error);
});
} else {
emailInput.classList.remove('is-invalid');
emailError.style.display = 'none';
emailError.style.opacity = '0';
}
});

// Password length validation


const passwordInput = document.getElementById('password');
const passwordLengthError = document.getElementById('passwordLengthError');

passwordInput.addEventListener('input', function() {
if (this.value.length < 8) {
this.classList.add('is-invalid');
passwordLengthError.classList.add('show');
} else {
this.classList.remove('is-invalid');
passwordLengthError.classList.remove('show');
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

}
});

// Password match validation


const confirmPassword = document.getElementById('confirm_password');
const passwordMatchError = document.getElementById('passwordMatchError');

confirmPassword.addEventListener('input', function() {
if (this.value !== passwordInput.value) {
this.classList.add('is-invalid');
passwordMatchError.classList.add('show');
} else {
this.classList.remove('is-invalid');
passwordMatchError.classList.remove('show');
}
});

// Form submission validation


document.getElementById('createTeacherForm').addEventListener('submit', function(e) {
const email = document.getElementById('email');
const password = document.getElementById('password');
const confirmPassword = document.getElementById('confirm_password');
const passwordMatchError = document.getElementById('passwordMatchError');

// Check if email is already in use


if (email.classList.contains('is-invalid')) {
e.preventDefault();
email.focus();
return false;
}

if (password.value.length < 8) {
e.preventDefault();
password.classList.add('is-invalid');
passwordLengthError.classList.add('show');
password.focus();
return false;
}

if (password.value !== confirmPassword.value) {


e.preventDefault();
confirmPassword.classList.add('is-invalid');
passwordMatchError.classList.add('show');
// Clear password fields
password.value = '';
confirmPassword.value = '';
// Focus on password field
password.focus();
return false;
}
return true;
});
</script>
</head>
<body class="bg-light">
<!-- Top Navigation -->
<nav class="navbar navbar-expand-lg navbar-dark mb-4">
<div class="container-fluid">
<a class="navbar-brand" href="#">Admin Dashboard</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav me-auto">
<li class="nav-item">
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

<a class="nav-link" href="#" onclick="showSection('home')">Home</a>


</li>
<li class="nav-item">
<a class="nav-link" href="#" onclick="showSection('created-accounts')">Created Teacher
Accounts</a>
</li>
<li class="nav-item">
<a class="nav-link" href="admin_manage_students.php">Manage Students</a>
</li>
</ul>
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link btn btn-outline-danger btn-sm ms-2" href="logout.php">
<i class="fas fa-sign-out-alt me-1"></i>Logout
</a>
</li>
</ul>
</div>
</div>
</nav>

<!-- Main Content -->


<div class="container mt-5">
<?php if (isset($_SESSION['success'])): ?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
<i class="fas fa-check-circle me-2"></i>
<?php
echo $_SESSION['success'];
unset($_SESSION['success']); // Clear the message after displaying
?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php endif; ?>
<?php if (isset($_SESSION['error'])): ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<i class="fas fa-exclamation-circle me-2"></i>
<?php
echo $_SESSION['error'];
unset($_SESSION['error']); // Clear the message after displaying
?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php endif; ?>
<!-- Home Section -->
<div id="home" class="section mt-5 text-center">
<h2 class="display-4 mb-4">Welcome to the Admin Dashboard</h2>
<p class="lead mb-4">Manage teacher accounts and other administrative tasks.</p>
<a href="create_teacher.php" class="btn btn-success text-white btn-lg">
<i class="fas fa-user-plus me-2"></i>Create Teacher Account
</a>
</div>

<!-- Created Teacher Accounts Section -->


<div id="created-accounts" class="section mt-5" style="display: none;">
<div class="card">
<div class="card-header bg-success text-white">
<h3 class="mb-0">Created Teacher Accounts</h3>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered table-hover">
<thead class="table-dark text-center">
<tr>
<th>ID</th>
<th>Name</th>
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

<th>Username</th>
<th>Email</th>
<th>Subject</th>
<th>Class Code</th>
<th>Created At</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php while ($teacher = $teachers_result->fetch_assoc()): ?>
<tr class="text-center">
<td><?php echo htmlspecialchars($teacher['id']); ?></td>
<td><?php echo htmlspecialchars($teacher['last_name'] . ", " . $teacher['first_name'] . " " .
($teacher['middle_name'] ? substr($teacher['middle_name'], 0, 1) . "." : "")); ?></td>
<td><?php echo htmlspecialchars($teacher['username']); ?></td>
<td><?php echo htmlspecialchars($teacher['email']); ?></td>
<td><?php echo htmlspecialchars($teacher['subjects']); ?></td>
<td><?php echo htmlspecialchars($teacher['class_codes']); ?></td>
<td><?php echo htmlspecialchars($teacher['created_at']); ?></td>
<td>
<div class="btn-group" role="group">
<a href="admin_view_teacher_subjects.php?id=<?php echo $teacher['id']; ?>" class="btn
btn-info btn-sm me-1">
<i class="fas fa-eye"></i>
</a>
<a href="admin_edit_teacher.php?id=<?php echo $teacher['id']; ?>" class="btn btn-
primary btn-sm me-1">
<i class="fas fa-edit"></i>
</a>
<a href="admin_delete_teacher.php?id=<?php echo $teacher['id']; ?>" class="btn btn-
danger btn-sm" onclick="return confirm('Are you sure you want to delete this teacher?');">
<i class="fas fa-trash"></i>
</a>
</div>
</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

-teacher_dashboard.php
<?php
session_start();
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'teacher') {
header("Location: index.php");
exit();
}

include 'config.php';
preventBackButton();

$teacher_id = $_SESSION['user_id'] ?? null;

// Fetch the teacher's name


$stmt = $conn->prepare("SELECT last_name, first_name, middle_name FROM teachers WHERE id = ?");
$stmt->bind_param("i", $_SESSION['user_id']);
$stmt->execute();
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

$result = $stmt->get_result();
$teacher = $result->fetch_assoc();

// Format the name


$teacher_name = $teacher['last_name'] . ", " . $teacher['first_name'];
if (!empty($teacher['middle_name'])) {
$teacher_name .= " " . substr($teacher['middle_name'], 0, 1) . ".";
}

// Get selected subject from URL parameter


$selected_subject = isset($_GET['subject']) ? $_GET['subject'] : '';

// Store the selected subject in session if it's provided


if (!empty($selected_subject)) {
$_SESSION['selected_subject'] = $selected_subject;
} else {
// If no subject is selected in URL, use the one from session
$selected_subject = $_SESSION['selected_subject'] ?? '';
}

// Fetch teacher's subjects


$stmt = $conn->prepare("SELECT DISTINCT subject FROM teacher_subjects WHERE teacher_id = ?");
$stmt->bind_param("i", $teacher_id);
$stmt->execute();
$subjects_result = $stmt->get_result();
$subjects = [];
while ($row = $subjects_result->fetch_assoc()) {
$subjects[] = $row['subject'];
}
$stmt->close();

// If no subject is selected and teacher has subjects, select the first one
if (empty($selected_subject) && !empty($subjects)) {
$selected_subject = $subjects[0];
$_SESSION['selected_subject'] = $selected_subject;
}

// Fetch quizzes based on selected subject


if (!empty($selected_subject)) {
$stmt = $conn->prepare("
SELECT q.id, q.quiz_title, q.quiz_type, q.created_at, ts.subject, ts.class_code
FROM quizzes q
JOIN teacher_subjects ts ON q.subject_id = ts.id
WHERE q.teacher_id = ? AND ts.subject = ?
ORDER BY q.created_at DESC
");
$stmt->bind_param("is", $teacher_id, $selected_subject);
} else {
$stmt = $conn->prepare("
SELECT q.id, q.quiz_title, q.quiz_type, q.created_at, ts.subject, ts.class_code
FROM quizzes q
JOIN teacher_subjects ts ON q.subject_id = ts.id
WHERE q.teacher_id = ?
ORDER BY q.created_at DESC
");
$stmt->bind_param("i", $teacher_id);
}
$stmt->execute();
$quizzes = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// Fetch materials based on selected subject


if (!empty($selected_subject)) {
$stmt = $conn->prepare("
SELECT m.*, ts.subject, ts.class_code
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

FROM materials m
JOIN teacher_subjects ts ON m.class_code = ts.class_code
WHERE m.instructor_id = ? AND ts.subject = ? AND ts.teacher_id = ?
");
$stmt->bind_param("isi", $teacher_id, $selected_subject, $teacher_id);
} else {
$stmt = $conn->prepare("
SELECT m.*, ts.subject, ts.class_code
FROM materials m
JOIN teacher_subjects ts ON m.class_code = ts.class_code
WHERE m.instructor_id = ? AND ts.teacher_id = ?
");
$stmt->bind_param("ii", $teacher_id, $teacher_id);
}
$stmt->execute();
$materials = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// Fetch enrolled students based on selected subject


if (!empty($selected_subject)) {
$stmt = $conn->prepare("
SELECT u.id as student_id, u.username, u.email, ts.class_code, e.enrolled_at
FROM enrollments e
JOIN users u ON e.student_id = u.id
JOIN teacher_subjects ts ON e.subject_id = ts.id
WHERE e.teacher_id = ? AND ts.subject = ?
ORDER BY e.enrolled_at DESC
");
$stmt->bind_param("is", $teacher_id, $selected_subject);
} else {
$stmt = $conn->prepare("
SELECT u.id as student_id, u.username, u.email, ts.class_code, e.enrolled_at
FROM enrollments e
JOIN users u ON e.student_id = u.id
JOIN teacher_subjects ts ON e.subject_id = ts.id
WHERE e.teacher_id = ?
ORDER BY e.enrolled_at DESC
");
$stmt->bind_param("i", $teacher_id);
}
$stmt->execute();
$students = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// Handle form submission to create a new material


if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['create_material'])) {
$material_title = htmlspecialchars(trim($_POST['material_title']));
$material_type = htmlspecialchars(trim($_POST['material_type']));
$material_link = !empty($_POST['material_link']) ? htmlspecialchars(trim($_POST['material_link'])) : null;
$file_path = !empty($_POST['file_path']) ? htmlspecialchars(trim($_POST['file_path'])) : null;
$class_code = htmlspecialchars(trim($_POST['class_code']));
$teacher_id = $_SESSION['user_id'];
$created_at = date('Y-m-d H:i:s');

// Insert the new material into the materials table


$stmt = $conn->prepare("INSERT INTO materials (material_title, material_type, material_link, file_path,
instructor_id, created_at, class_code) VALUES (?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssssiss", $material_title, $material_type, $material_link, $file_path, $teacher_id,
$created_at, $class_code);

if ($stmt->execute()) {
$_SESSION['success'] = "Material created successfully!";
} else {
$_SESSION['error'] = "Error creating material.";
}
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

$stmt->close();
header("Location: teacher_dashboard.php");
exit();
}

$class_code_for_home = '';
if (!empty($selected_subject)) {
$stmt = $conn->prepare("SELECT class_code FROM teacher_subjects WHERE teacher_id = ? AND subject = ?
LIMIT 1");
$stmt->bind_param("is", $teacher_id, $selected_subject);
$stmt->execute();
$result = $stmt->get_result();
if ($row = $result->fetch_assoc()) {
$class_code_for_home = $row['class_code'];
}
$stmt->close();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Teacher Dashboard - Diffun National High School</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="styles.css">
<style>
.section { display: none; } /* Hide all sections by default */
.section.active { display: block; } /* Show only the active section */
.alert-dismissible { display: block; }
.centered-alert {
position: fixed;
top: 10px;
left: 50%;
transform: translateX(-50%);
z-index: 9999;
width: 50%;
}
.quiz-card {
margin-bottom: 2rem;
border-radius: 10px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
overflow: hidden;
}
.quiz-header {
background-color: #f8f9fa;
padding: 1rem;
border-bottom: 1px solid #dee2e6;
}
.quiz-body {
padding: 1.5rem;
}
.stats-card {
transition: transform 0.2s;
}
.stats-card:hover {
transform: translateY(-5px);
}
.chart-container {
height: 300px;
margin-top: 1rem;
}
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

</style>
<script>
let charts = {};

// Function to show section and load analytics if needed


function showSection(sectionId) {
// Hide all sections
document.querySelectorAll('.section').forEach(section => {
section.classList.remove('active');
});

// Show the selected section


document.getElementById(sectionId).classList.add('active');

// If analytics section is opened, automatically load All Quizzes


if (sectionId === 'analytics-section') {
loadQuizAnalytics('all');
// Set the select value to 'all'
document.getElementById('quizSelect').value = 'all';
}

// Update URL without reloading the page


const url = new URL(window.location);
url.searchParams.set('section', sectionId);
window.history.pushState({}, '', url);
}

// Function to remove alerts after 5 seconds


function removeAlerts() {
const alerts = document.querySelectorAll('.alert');
alerts.forEach(alert => {
setTimeout(() => {
alert.remove();
}, 5000);
});
}

document.addEventListener('DOMContentLoaded', function () {
// Get section from URL parameter
const urlParams = new URLSearchParams(window.location.search);
const section = urlParams.get('section');

// Show the correct section on page load and load analytics if needed
if (section) {
showSection(section);
} else if (document.getElementById('analytics-section').classList.contains('active')) {
// If analytics section is active by default, load All Quizzes
loadQuizAnalytics('all');
document.getElementById('quizSelect').value = 'all';
}

// Remove alerts after 5 seconds


removeAlerts();

document.querySelectorAll('.delete-btn').forEach(button => {
button.addEventListener('click', function () {
const id = this.getAttribute('data-id');
const type = this.getAttribute('data-type');
const rowId = type === 'quiz' ? `quiz-${id}` : `material-${id}`;

fetch(`delete.php?${type}_id=${id}`, {
method: 'GET'
})
.then(response => response.json())
.then(data => {
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

if (data.success) {
document.getElementById(rowId).remove();
showCenteredAlert(data.message, 'success');
} else {
showCenteredAlert(data.message, 'danger');
}
})
.catch(error => console.error('Error:', error));
});
});
});

function showCenteredAlert(message, type) {


const alert = document.createElement('div');
alert.className = `alert alert-${type} alert-dismissible fade show centered-alert`;
alert.setAttribute('role', 'alert');
alert.innerHTML = `${message}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>`;
document.body.appendChild(alert);
setTimeout(() => {
alert.remove();
}, 5000);
}

function loadQuizAnalytics(quizId) {
// Show loading state
document.getElementById('statsCards').style.display = 'none';
document.getElementById('chartContainer').style.display = 'none';
document.getElementById('actionButtons').style.display = 'none';
document.getElementById('quizTitle').style.display = 'none';

// Add loading indicator


const chartsContainer = document.getElementById('chartContainer');
chartsContainer.innerHTML = `
<div class="text-center my-5">
<div class="spinner-border text-primary" role="status">
<span class="visually-hidden">Loading...</span>
</div>
<p class="mt-2">Loading quiz analytics...</p>
</div>
`;
chartsContainer.style.display = 'block';

// Get the selected subject from the dropdown


const subjectSelect = document.querySelector('select[onchange*="subject"]');
const selectedSubject = subjectSelect ? subjectSelect.value : '';

// Get the class code from the subject mapping


const classCode = subjectToClassCode[selectedSubject];

if (!classCode) {
// Clear loading indicator and show no quizzes message
chartsContainer.innerHTML = `
<div class="text-center my-5">
<div class="alert alert-info">
<i class="fas fa-info-circle me-2"></i>
No quizzes have been created for this subject yet.
<br>
<small class="text-muted">Create a quiz to see analytics here.</small>
</div>
</div>
`;
return;
}
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

const url = quizId === 'all' ? `get_all_quiz_analytics.php?class_code=${classCode}` :


`get_quiz_analytics.php?quiz_id=${quizId}`;

fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => {
if (data.error) {
throw new Error(data.details || data.error);
}

// Clear previous charts container


chartsContainer.innerHTML = '';

if (quizId === 'all') {


// Handle all quizzes view
if (!data.quiz_analytics || Object.keys(data.quiz_analytics).length === 0) {
chartsContainer.innerHTML = `
<div class="text-center my-5">
<div class="alert alert-info">
<i class="fas fa-info-circle me-2"></i>
No quizzes have been created for this subject yet.
<br>
<small class="text-muted">Create a quiz to see analytics here.</small>
</div>
</div>
`;
return;
}

// Display individual charts for each quiz


document.getElementById('quizTitle').textContent = 'All Quizzes Overview';
document.getElementById('quizTitle').style.display = 'block';

// Destroy any existing charts


Object.values(charts).forEach(chart => chart.destroy());
charts = {};

// Create a container for the quiz grid


const quizGrid = document.createElement('div');
quizGrid.className = 'row';
chartsContainer.appendChild(quizGrid);

// Create a card for each quiz


Object.entries(data.quiz_analytics).forEach(([quiz_id, quiz_data]) => {
// Validate quiz_data
if (!quiz_data) {
console.warn(`Invalid quiz data for quiz ${quiz_id}`);
return;
}

const quizCol = document.createElement('div');


quizCol.className = 'col-12';

const quizCard = document.createElement('div');


quizCard.className = 'card quiz-card';

// Quiz header with title


const quizHeader = document.createElement('div');
quizHeader.className = 'card-header quiz-header';
quizHeader.innerHTML = `
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

<h4 class="text-center mb-0">${quiz_data.quiz_title || 'Untitled Quiz'}</h4>


`;

// Quiz body with stats and chart


const quizBody = document.createElement('div');
quizBody.className = 'card-body quiz-body';

// Stats cards row


const statsRow = document.createElement('div');
statsRow.className = 'row g-3 mb-4';
statsRow.innerHTML = `
<div class="col-md-3">
<div class="card bg-primary text-white stats-card">
<div class="card-body text-center">
<h5 class="card-title">Average Score</h5>
<h3 class="mb-0">${quiz_data.average_score ? quiz_data.average_score.toFixed(2) :
0}</h3>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card bg-success text-white stats-card">
<div class="card-body text-center">
<h5 class="card-title">Highest Score</h5>
<h3 class="mb-0">${quiz_data.highest_score || 0}</h3>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card bg-warning text-white stats-card">
<div class="card-body text-center">
<h5 class="card-title">Lowest Score</h5>
<h3 class="mb-0">${quiz_data.lowest_score || 0}</h3>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card bg-info text-white stats-card">
<div class="card-body text-center">
<h5 class="card-title">Completion Rate</h5>
<h3 class="mb-0">${quiz_data.completion_rate ? quiz_data.completion_rate.toFixed(2) +
'%' : '0%'}</h3>
</div>
</div>
</div>
`;

// Chart container
const chartContainer = document.createElement('div');
chartContainer.className = 'chart-container';
chartContainer.style.height = '300px';
chartContainer.style.marginTop = '20px';

// Add chart container to quiz body


quizBody.appendChild(statsRow);
quizBody.appendChild(chartContainer);

// Add quiz body to card


quizCard.appendChild(quizHeader);
quizCard.appendChild(quizBody);

// Add card to column


quizCol.appendChild(quizCard);

// Add column to grid


QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

quizGrid.appendChild(quizCol);

// Create chart if there are student scores


if (quiz_data.student_scores && Array.isArray(quiz_data.student_scores) &&
quiz_data.student_scores.length > 0) {
const ctx = document.createElement('canvas');
chartContainer.appendChild(ctx);

const chartData = {
labels: quiz_data.student_scores.map(score => score.name),
datasets: [{
label: 'Score',
data: quiz_data.student_scores.map(score => score.score),
backgroundColor: 'rgba(54, 162, 235, 0.5)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
}]
};

const chart = new Chart(ctx, {


type: 'bar',
data: chartData,
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true,
title: {
display: true,
text: 'Score'
}
},
x: {
title: {
display: true,
text: 'Students'
}
}
}
}
});

charts[quiz_id] = chart;
}
});
} else {
// Single quiz view
const quizCard = document.createElement('div');
quizCard.className = 'card quiz-card';

const quizHeader = document.createElement('div');


quizHeader.className = 'card-header quiz-header';
quizHeader.innerHTML = `
<h4 class="text-center mb-0">${data.quiz_title}</h4>
`;

const quizBody = document.createElement('div');


quizBody.className = 'card-body quiz-body';

const statsRow = document.createElement('div');


statsRow.className = 'row g-3 mb-4';
statsRow.innerHTML = `
<div class="col-md-3">
<div class="card bg-primary text-white stats-card">
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

<div class="card-body text-center">


<h5 class="card-title">Average Score</h5>
<h3 class="mb-0">${data.average_score ? data.average_score.toFixed(2) : 0}</h3>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card bg-success text-white stats-card">
<div class="card-body text-center">
<h5 class="card-title">Highest Score</h5>
<h3 class="mb-0">${data.highest_score || 0}</h3>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card bg-warning text-white stats-card">
<div class="card-body text-center">
<h5 class="card-title">Lowest Score</h5>
<h3 class="mb-0">${data.lowest_score || 0}</h3>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card bg-info text-white stats-card">
<div class="card-body text-center">
<h5 class="card-title">Completion Rate</h5>
<h3 class="mb-0">${data.completion_rate ? data.completion_rate.toFixed(2) + '%' :
'0%'}</h3>
</div>
</div>
</div>
`;

const chartContainer = document.createElement('div');


chartContainer.className = 'chart-container';
chartContainer.style.height = '300px';
chartContainer.style.marginTop = '20px';

quizCard.appendChild(quizHeader);
quizBody.appendChild(statsRow);
quizBody.appendChild(chartContainer);
quizCard.appendChild(quizBody);
chartsContainer.appendChild(quizCard);

// Create the chart for single quiz view


if (data.student_scores && Array.isArray(data.student_scores) && data.student_scores.length > 0) {
const ctx = document.createElement('canvas');
chartContainer.appendChild(ctx);

const chartData = {
labels: data.student_scores.map(score => score.name),
datasets: [{
label: 'Score',
data: data.student_scores.map(score => score.score),
backgroundColor: 'rgba(54, 162, 235, 0.5)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
}]
};

const chart = new Chart(ctx, {


type: 'bar',
data: chartData,
options: {
responsive: true,
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true,
title: {
display: true,
text: 'Score'
}
},
x: {
title: {
display: true,
text: 'Students'
}
}
}
}
});

charts.single = chart;
}
}

document.getElementById('chartContainer').style.display = 'block';
document.getElementById('actionButtons').style.display = 'flex';
document.getElementById('downloadCSV').href = quizId === 'all' ? 'download_all_scores.php' :
`download_scores.php?quiz_id=${quizId}`;
})
.catch(error => {
console.error('Error:', error);
chartsContainer.innerHTML = `
<div class="text-center my-5">
<div class="alert alert-danger">
<i class="fas fa-exclamation-circle me-2"></i>
Error loading quiz analytics: ${error.message}
</div>
</div>
`;
});
}

function exportToPDF() {
const { jsPDF } = window.jspdf;
const doc = new jsPDF();
const element = document.getElementById('analytics-section');

html2canvas(element).then(canvas => {
const imgData = canvas.toDataURL('image/png');
const imgWidth = 210; // A4 width in mm
const pageHeight = 297; // A4 height in mm
const imgHeight = canvas.height * imgWidth / canvas.width;
let heightLeft = imgHeight;
let position = 0;

doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);


heightLeft -= pageHeight;

while (heightLeft >= 0) {


position = heightLeft - imgHeight;
doc.addPage();
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
}

doc.save('quiz_analytics.pdf');
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

});
}

function downloadCSV() {
const quizSelect = document.getElementById('quizSelect');
const selectedQuiz = quizSelect ? quizSelect.value : 'all';

if (selectedQuiz === 'all') {


// Download all quizzes for the subject
const subjectSelect = document.querySelector('select[onchange*="subject"]');
const selectedSubject = subjectSelect ? subjectSelect.value : '';
const classCode = subjectToClassCode[selectedSubject];

if (!classCode) {
// Show no quizzes message
const chartsContainer = document.getElementById('chartContainer');
chartsContainer.innerHTML = `
<div class="text-center my-5">
<div class="alert alert-info">
<i class="fas fa-info-circle me-2"></i>
No quizzes have been created for this subject yet.
<br>
<small class="text-muted">Create a quiz to see analytics here.</small>
</div>
</div>
`;
chartsContainer.style.display = 'block';
return;
}
document.getElementById('csv-download-iframe').src =
`download_all_scores.php?class_code=${classCode}`;
} else {
// Download only the selected quiz
document.getElementById('csv-download-iframe').src = `download_scores.php?quiz_id=${selectedQuiz}`;
}
}

// Add this new script for handling student removal


document.addEventListener('DOMContentLoaded', function() {
// Handle student removal
document.querySelectorAll('.delete-student-btn').forEach(button => {
button.addEventListener('click', function() {
const studentId = this.getAttribute('data-student-id');
const classCode = this.getAttribute('data-class-code');

if (confirm('Are you sure you want to remove this student from the class?')) {
fetch('teacher_remove_student.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `student_id=${studentId}&class_code=${classCode}`
})
.then(response => response.json())
.then(data => {
if (data.success) {
// Remove the row from the table
const row = document.getElementById(`student-${studentId}`);
if (row) {
row.remove();
}
// Show success message
showCenteredAlert(data.message, 'success');
} else {
showCenteredAlert(data.message, 'danger');
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

}
})
.catch(error => {
console.error('Error:', error);
showCenteredAlert('An error occurred while removing the student', 'danger');
});
}
});
});
});

const subjectToClassCode = <?php


$subjectMap = [];
foreach ($quizzes as $quiz) {
$subjectMap[$quiz['subject']] = $quiz['class_code'];
}
echo json_encode($subjectMap);
?>;
</script>
</head>
<body class="bg-light">
<!-- Navigation Bar -->
<nav class="navbar navbar-expand-lg navbar-dark bg-success">
<div class="container-fluid">
<a class="navbar-brand" href="#">Teacher Dashboard</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-
controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#" onclick="showSection('home-section')">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#" onclick="showSection('quizzes-section')">Quizzes</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#" onclick="showSection('materials-section')">Materials</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#" onclick="showSection('enrolled-students-section')">Enrolled
Students</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#" onclick="showSection('analytics-section')">Analytics</a>
</li>
</ul>
<ul class="navbar-nav ms-auto">
<li class="nav-item me-3">
<select class="form-select" onchange="window.location.href='teacher_dashboard.php?subject=' +
this.value">
<?php foreach ($subjects as $sub): ?>
<option value="<?php echo htmlspecialchars($sub); ?>" <?php echo ($selected_subject === $sub) ?
'selected' : ''; ?>>
<?php echo htmlspecialchars($sub); ?>
</option>
<?php endforeach; ?>
</select>
</li>
<li class="nav-item">
<a class="nav-link btn btn-danger text-white" href="logout.php">
<i class="fas fa-sign-out-alt me-2"></i>Logout
</a>
</li>
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

</ul>
</div>
</div>
</nav>

<div class="container mt-5">


<?php if (isset($_SESSION['success'])): ?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
<?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php endif; ?>
<?php if (isset($_SESSION['error'])): ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<?php echo $_SESSION['error']; unset($_SESSION['error']); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php endif; ?>
<!-- Home Section -->
<section id="home-section" class="section active">
<h2 class="text-center mb-4">Welcome, <?php echo htmlspecialchars($teacher_name); ?>!</h2>
<?php if (!empty($selected_subject)): ?>
<h3 class="text-center mb-2">Subject: <?php echo htmlspecialchars($selected_subject); ?></h3>
<?php if (!empty($class_code_for_home)): ?>
<h3 class="text-center mb-4">Class Code: <?php echo
htmlspecialchars($class_code_for_home); ?></h3>
<?php endif; ?>
<?php endif; ?>
<div class="row">
<div class="col-md-6 mb-3">
<div class="card h-100 shadow">
<div class="card-body text-center">
<h3 class="card-title mb-4">Create Quiz</h3>
<?php if (!empty($subjects)): ?>
<a href="create_quiz.php" class="btn btn-info btn-lg w-100">
<i class="fas fa-plus-circle me-2"></i>Create Quiz
</a>
<?php else: ?>
<div class="alert alert-warning">
<i class="fas fa-exclamation-triangle me-2"></i>
You need to have subjects assigned before creating quizzes.
Please contact the administrator to assign subjects to your account.
</div>
<?php endif; ?>
</div>
</div>
</div>

<div class="col-md-6 mb-3">


<div class="card h-100 shadow">
<div class="card-body text-center">
<h3 class="card-title mb-4">Upload Material</h3>
<?php if (!empty($subjects)): ?>
<a href="upload_material.php" class="btn btn-secondary btn-lg w-100">
<i class="fas fa-upload me-2"></i>Upload Material
</a>
<?php else: ?>
<div class="alert alert-warning">
<i class="fas fa-exclamation-triangle me-2"></i>
You need to have subjects assigned before uploading materials.
Please contact the administrator to assign subjects to your account.
</div>
<?php endif; ?>
</div>
</div>
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

</div>
</div>
</section>

<!-- Quizzes Section -->


<section id="quizzes-section" class="section">
<h2 class="text-center mb-4">Created Quizzes</h2>
<div class="table-responsive">
<table class="table table-bordered">
<thead class="table-dark">
<tr>
<th>Quiz Title</th>
<th>Quiz Type</th>
<th>Subject</th>
<th>Class Code</th>
<th>Created At</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php foreach ($quizzes as $quiz): ?>
<tr id="quiz-<?php echo $quiz['id']; ?>">
<td><?php echo htmlspecialchars($quiz['quiz_title']); ?></td>
<td>
<?php
$quiz_type = $quiz['quiz_type'];
if (empty($quiz_type)) {
// If quiz type is empty, determine it from questions
$stmt = $conn->prepare("SELECT DISTINCT question_type FROM questions WHERE quiz_id
= ?");
$stmt->bind_param("i", $quiz['id']);
$stmt->execute();
$result = $stmt->get_result();
$types = [];
while ($row = $result->fetch_assoc()) {
$types[] = $row['question_type'];
}
$stmt->close();

if (count($types) === 1) {
$quiz_type = $types[0];
} else {
$quiz_type = 'mixed';
}

// Update the quiz type in the database


$update_stmt = $conn->prepare("UPDATE quizzes SET quiz_type = ? WHERE id = ?");
$update_stmt->bind_param("si", $quiz_type, $quiz['id']);
$update_stmt->execute();
$update_stmt->close();
}

// Format the quiz type for display


$display_type = ucwords(str_replace('_', ' ', $quiz_type));
echo htmlspecialchars($display_type);
?>
</td>
<td><?php echo htmlspecialchars($quiz['subject']); ?></td>
<td><?php echo htmlspecialchars($quiz['class_code']); ?></td>
<td><?php echo htmlspecialchars($quiz['created_at']); ?></td>
<td>
<a href="view_student_scores.php?quiz_id=<?php echo $quiz['id']; ?>" class="btn btn-warning
btn-sm">View Scores</a>
<a href="edit_quiz.php?id=<?php echo $quiz['id']; ?>&section=quizzes-section" class="btn btn-
primary btn-sm">Edit</a>
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

<button class="btn btn-danger btn-sm delete-btn" data-id="<?php echo $quiz['id']; ?>" data-
type="quiz">Delete</button>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</section>

<!-- Materials Section -->


<section id="materials-section" class="section">
<h2 class="text-center mb-4">Uploaded Materials</h2>
<div class="table-responsive">
<table class="table table-bordered">
<thead class="table-dark">
<tr>
<th>Title</th>
<th>Type</th>
<th>Subject</th>
<th>Class Code</th>
<th>Link / File</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
foreach ($materials as $material):
echo "<tr id='material-{$material['id']}'>";
echo "<td>" . htmlspecialchars($material['material_title']) . "</td>";
echo "<td>" . htmlspecialchars($material['material_type']) . "</td>";
echo "<td>" . htmlspecialchars($material['subject']) . "</td>";
echo "<td>" . htmlspecialchars($material['class_code']) . "</td>";
if ($material['material_type'] == 'Link') {
echo "<td><a href='" . htmlspecialchars($material['material_link']) . "'
target='_blank'>Link</a></td>";
} else {
echo "<td><a href='" . htmlspecialchars($material['file_path']) . "' download>Download</a></td>";
}
echo "<td>
<a href='edit_material.php?id=" . $material['id'] . "&section=materials-section' class='btn btn-
primary btn-sm'>Edit</a>
<button class='btn btn-danger btn-sm delete-btn' data-id='" . $material['id'] . "' data-
type='material'>Delete</button>
</td>";
echo "</tr>";
endforeach;
?>
</tbody>
</table>
</div>
</section>

<!-- Form to Create a New Material -->


<section id="create-material-section" class="section">
<h2 class="text-center mb-4">Create a New Material</h2>
<form action="teacher_dashboard.php" method="POST" class="bg-[#1a1a2e] p-8 rounded-lg shadow-lg mb-
8">
<div class="mb-4">
<label for="material_title" class="block text-lg font-medium mb-2">Material Title</label>
<input type="text" id="material_title" name="material_title" class="w-full p-3 rounded bg-gray-800 text-
white" required>
</div>
<div class="mb-4">
<label for="material_type" class="block text-lg font-medium mb-2">Material Type</label>
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

<select id="material_type" name="material_type" class="w-full p-3 rounded bg-gray-800 text-white">


<option value="Document">Document</option>
<option value="Link">Link</option>
</select>
</div>
<div class="mb-4">
<label for="material_link" class="block text-lg font-medium mb-2">Material Link</label>
<input type="url" id="material_link" name="material_link" class="w-full p-3 rounded bg-gray-800 text-
white">
</div>
<div class="mb-4">
<label for="file_path" class="block text-lg font-medium mb-2">File Path</label>
<input type="text" id="file_path" name="file_path" class="w-full p-3 rounded bg-gray-800 text-white">
</div>
<div class="mb-4">
<label for="class_code" class="block text-lg font-medium mb-2">Class Code</label>
<input type="text" id="class_code" name="class_code" class="w-full p-3 rounded bg-gray-800 text-
white" required>
</div>
<button type="submit" name="create_material" class="bg-[#d4af37] text-white py-3 px-6 rounded
hover:bg-[#ffcc00] transition duration-300">Create Material</button>
</form>
</section>

<!-- Enrolled Students Section -->


<section id="enrolled-students-section" class="section">
<h2 class="text-center mb-4">Enrolled Students</h2>
<div class="table-responsive">
<table class="table table-bordered">
<thead class="table-dark">
<tr>
<th>Student Name</th>
<th>Email</th>
<th>Class Code</th>
<th>Enrolled At</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
foreach ($students as $student):
// Get student's full name details
$stmt = $conn->prepare("SELECT last_name, first_name, middle_name FROM users WHERE id = ?");
$stmt->bind_param("i", $student['student_id']);
$stmt->execute();
$name_result = $stmt->get_result();
$name_data = $name_result->fetch_assoc();
$stmt->close();

// Format the name: Last Name, First Name Middle Initial


$middle_initial = !empty($name_data['middle_name']) ? substr($name_data['middle_name'], 0, 1) .
'.' : '';
$formatted_name = $name_data['last_name'] . ', ' . $name_data['first_name'] . ' ' . $middle_initial;

echo "<tr id='student-{$student['student_id']}'>";


echo "<td>" . htmlspecialchars($formatted_name) . "</td>";
echo "<td>" . htmlspecialchars($student['email']) . "</td>";
echo "<td>" . htmlspecialchars($student['class_code']) . "</td>";
echo "<td>" . htmlspecialchars($student['enrolled_at']) . "</td>";
echo "<td>
<button class='btn btn-danger btn-sm delete-student-btn'
data-student-id='{$student['student_id']}'
data-class-code='{$student['class_code']}'>
<i class='fas fa-trash'></i> Remove
</button>
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

</td>";
echo "</tr>";
endforeach;
?>
</tbody>
</table>
</div>
</section>

<!-- Analytics Section -->


<section id="analytics-section" class="section">
<h2 class="text-center mb-4">Quiz Analytics</h2>

<!-- Quiz Selection -->


<div class="row mb-4">
<div class="col-md-6 mx-auto">
<select id="quizSelect" class="form-select" onchange="loadQuizAnalytics(this.value)">
<option value="all">All Quizzes</option>
<?php foreach ($quizzes as $quiz): ?>
<option value="<?php echo $quiz['id']; ?>">
<?php echo htmlspecialchars($quiz['quiz_title']); ?>
</option>
<?php endforeach; ?>
</select>
</div>
</div>

<!-- Quiz Title -->


<h3 id="quizTitle" class="text-center mb-4" style="display: none;"></h3>

<!-- Statistics Cards -->


<div class="row mb-4" id="statsCards" style="display: none;">
<div class="col-md-4">
<div class="card bg-primary text-white shadow">
<div class="card-body text-center">
<h5 class="card-title">Average Score</h5>
<h2 id="avgScore">-</h2>
<p class="mb-0">out of <span id="totalQuestions">-</span> questions</p>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card bg-success text-white shadow">
<div class="card-body text-center">
<h5 class="card-title">Highest Score</h5>
<h2 id="highestScore">-</h2>
<p class="mb-0">by <span id="highestScorer">-</span></p>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card bg-warning text-white shadow">
<div class="card-body text-center">
<h5 class="card-title">Lowest Score</h5>
<h2 id="lowestScore">-</h2>
<p class="mb-0">by <span id="lowestScorer">-</span></p>
</div>
</div>
</div>
</div>

<!-- Chart Container -->


<div class="card mb-4 shadow" id="chartContainer" style="display: none;">
<div class="card-header bg-info text-white">
<h5 class="mb-0">Student Performance</h5>
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

</div>
<div class="card-body">
<canvas id="scoreChart"></canvas>
</div>
</div>

<!-- Action Buttons -->


<div class="d-flex justify-content-center gap-3 mb-4" id="actionButtons" style="display: none;">
<a href="#" id="downloadCSV" class="btn btn-success" onclick="downloadCSV(); return false;">
<i class="fas fa-download me-2"></i>Download CSV
</a>
<button onclick="exportToPDF()" class="btn btn-danger">
<i class="fas fa-file-pdf me-2"></i>Export PDF
</button>
</div>
</section>
</div>
<iframe id="csv-download-iframe" style="display:none;"></iframe>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
</body>
</html>

-student_dashboard.php
<?php
session_start();

// Debug: Check session data


error_log("Dashboard Session data: " . print_r($_SESSION, true));

// Add cache control headers to prevent back button access after logout
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'student') {


header("Location: index.php");
exit();
}

include 'config.php';

$student_id = $_SESSION['user_id'];

// Fetch enrolled subjects for the student


$sql = "SELECT e.id, e.subject_id, e.teacher_id, e.class_code, ts.subject, ts.class_code as ts_class_code,
CONCAT(t.last_name, ', ', t.first_name, ' ', IFNULL(LEFT(t.middle_name, 1), ''), '.') as instructor_name,
e.enrolled_at
FROM enrollments e
LEFT JOIN teacher_subjects ts ON e.subject_id = ts.id
LEFT JOIN teachers t ON ts.teacher_id = t.id
WHERE e.student_id = ?
ORDER BY e.enrolled_at ASC";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $student_id);
$stmt->execute();
$result = $stmt->get_result();

$enrolled_subjects = [];
while ($row = $result->fetch_assoc()) {
// Debug information
error_log("Enrolled subject data: " . print_r($row, true));
$enrolled_subjects[] = $row;
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

$stmt->close();
$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Dashboard - Diffun National High School</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="styles.css">
<style>
.navbar {
background-color: #0d6efd;
}
.navbar-brand {
color: white !important;
}
.nav-link {
color: rgba(255,255,255,.75) !important;
}
.nav-link:hover {
color: white !important;
}
.card-header {
background-color: #0d6efd;
color: white;
}
.btn-primary {
background-color: #0d6efd;
border-color: #0d6efd;
}
.btn-success {
background-color: #198754;
border-color: #198754;
}
.table-dark {
background-color: #0d6efd;
color: white;
}
</style>
</head>
<body class="bg-light">
<!-- Navigation Bar -->
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
<div class="container-fluid">
<a class="navbar-brand" href="#">Student Dashboard</a>
<ul class="navbar-nav ms-auto">
<li class="nav-item">
<a class="nav-link btn btn-danger text-white" href="logout.php">
<i class="fas fa-sign-out-alt me-2"></i>Logout
</a>
</li>
</ul>
</div>
</nav>

<div class="container mt-5">


<?php if (isset($_SESSION['success'])): ?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
<?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>


</div>
<?php endif; ?>
<?php if (isset($_SESSION['error'])): ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<?php echo $_SESSION['error']; unset($_SESSION['error']); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php endif; ?>
<!-- Home Section -->
<section id="home-section" class="mb-5">
<h2 class="text-center mb-4">Welcome, <?php echo htmlspecialchars($_SESSION['first_name']); ?>!</h2>
<div class="d-flex justify-content-center gap-3">
<a href="#enrollSubjectModal" class="btn btn-success btn-lg" data-bs-toggle="modal">
<i class="fas fa-plus-circle me-2"></i>Enroll Subject
</a>
</div>
</section>

<!-- Enrolled Subjects Section -->


<section id="enrolled-subjects-section" class="mb-5">
<h2 class="text-center mb-4">Enrolled Subjects</h2>
<div class="table-responsive mb-4">
<table class="table table-bordered table-striped">
<thead class="table-dark">
<tr>
<th>#</th>
<th>Teacher Name</th>
<th>Subject Name</th>
<th>Class Code</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php if (!empty($enrolled_subjects)): ?>
<?php foreach ($enrolled_subjects as $index => $subject): ?>
<tr>
<td><?php echo $index + 1; ?></td>
<td><?php echo htmlspecialchars($subject['instructor_name']); ?></td>
<td><?php echo htmlspecialchars($subject['subject']); ?></td>
<td><?php echo htmlspecialchars($subject['class_code']); ?></td>

<td>
<a href="subject_details.php?instructor_id=<?php echo
urlencode($subject['teacher_id']); ?>&class_code=<?php echo urlencode($subject['class_code']); ?>" class="btn
btn-primary btn-sm">
View
</a>
</td>
</tr>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td colspan="5" class="text-center">No subjects enrolled yet.</td>
</tr>
<?php endif; ?>
</tbody>
</table>
</div>
</section>
</div>

<!-- Enroll Subject Modal -->


<div class="modal fade" id="enrollSubjectModal" tabindex="-1" aria-labelledby="enrollSubjectModalLabel" aria-
hidden="true">
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

<div class="modal-dialog modal-lg">


<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="enrollSubjectModalLabel">Enroll Subject</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form id="enrollSubjectForm" method="POST" action="enroll_subject.php">
<div class="mb-3">
<label for="class_code" class="form-label">Enter Subject Code</label>
<input type="text" class="form-control" id="class_code" name="class_code" placeholder="Enter the
subject code" required autofocus>
</div>
<button type="submit" name="enroll_subject" class="btn btn-primary mt-3">Enroll</button>
</form>
</div>
</div>
</div>
</div>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Automatically dismiss alert after 2.5 seconds
document.addEventListener('DOMContentLoaded', function() {
const alert = document.querySelector('.alert');
if (alert) {
setTimeout(function() {
const bsAlert = new bootstrap.Alert(alert);
bsAlert.close();
}, 2500); // 2500 milliseconds = 2.5 seconds
}
});
</script>
</body>
</html>

-logout.php
<?php
session_start();

// Clear all session variables


$_SESSION = array();

// Destroy the session cookie


if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-3600, '/');
}

// Destroy the session


session_destroy();

// Add cache control headers


header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

// Redirect to login page


header("Location: index.php");
exit();
?>
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

*Conclusion: The implementation of a Digital Quiz Management System at Diffun National High School will
significantly improve the efficiency of the assessment process, enhance student performance, and provide valuable
insights into individual learning progress.

References:

Ibrahim, M., Al-Harthy, I., Alhassan, A., Alnajar, R., & Al-Mutairi, H. (2022). Online student assessment and
evaluation system for higher education. International Journal of Emerging Technologies in Learning, 17(7), 95–106.
https://www.ncbi.nlm.nih.gov/pmc/articles/PMC9073482/

Cabezas, F., Burgos, L., Darrigol, J., & Zúñiga, M. (2024). Implementation of an early alert system in quizzes of a high
complexity subject in higher education: Improvement of student performance and teacher perception. Education
and Information Technologies. https://doi.org/10.1007/s10639-024-12610-5

de Taza, E., de Jesus, H., & Zaragoza, Y. (2024). Project GOALS: Enhancing student learning using improved
monitoring tool in modular distance learning. American Journal of Management Science and Engineering, 9(5), 104–
109. https://doi.org/10.11648/j.ajmse.20240905.12

Santos, R., & Braga, A. (2015). Feedback mechanisms in digital quizzes: A study on Quizizz and student engagement.
Future Internet, 7(4), 484–495. https://www.mdpi.com/1999-5903/7/4/484

Rahmah, N., Lestari, A., Musa, L. A. D., & Sugilar, H. (2019). Quizizz online digital system assessment tools.
ResearchGate.
https://www.researchgate.net/publication/339019100_Quizizz_Online_Digital_System_Assessment_Tools

Sandoval, I. (2017). Centralized learning and assessment tool for Department of Education. Academia.edu.
https://www.academia.edu/35236895/_Centralized_Learning_and_Assessment_Tool_for_Department_of_Educati
on

Simon, P. D., Jiang, J., Fryer, L. K., King, R. B., & Frondozo, C. E. (2024). An assessment of learning management
system use in higher education: Perspectives from a comprehensive sample of teachers and students. Technology,
Knowledge and Learning. Advance online publication. https://doi.org/10.1007/s10758-024-09734-5
QUIRINO STATE UNIVERSITY
COLEGE OF INFORMATION TECHNOLOGY & COMPUTING SCIENCES
Diffun Campus

You might also like