<?php

/**
 * Result Management System for Institutions
 *
 * Copyright (C) 2025 ASTGD
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

/**
 * This file is part of the RMS (Result Management System for Institutions) plugin.
 *
 * It ensures that the file is not accessed directly by checking if the ABSPATH constant is defined.
 * If ABSPATH is not defined, the script exits to prevent unauthorized access.
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class ASTGDRMSYS_Subject_Manager
 *
 * This class is responsible for managing subjects within the RMS (Result Management System for Institutions) plugin.
 *
 * @package ResultManagementSystem
 * @subpackage Subject_Manager
 * @since 1.0.0
 */
class ASTGDRMSYS_Subject_Manager {

	private $wpdb;
	private $prefix;
	private $messages = array();

	/**
	 * Constructor for the class.
	 *
	 * This method initializes the class and sets up any necessary properties or methods.
	 */
	public function __construct() {
		global $wpdb;
		$this->wpdb   = $wpdb;
		$this->prefix = $wpdb->prefix;

		$this->handle_actions();
	}

	/**
	 * Handles various actions related to adding a subject.
	 *
	 * This function processes the actions triggered from the add-subject page.
	 * It performs necessary operations based on the action type.
	 *
	 * @return void
	 */
	private function handle_actions() {
		if ( isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD'] === 'POST' ) {
			check_admin_referer( 'astgdrmsys_subject_action', 'astgdrmsys_nonce' );
		}

		// Handle delete securely
		if ( isset( $_GET['delid'], $_GET['astgdrmsys_nonce'] ) ) {
			// Sanitize and validate the 'delid' parameter
			$delid = isset( $_GET['delid'] ) ? absint( wp_unslash( $_GET['delid'] ) ) : 0;
			$nonce = isset( $_GET['astgdrmsys_nonce'] ) ? sanitize_text_field( wp_unslash( $_GET['astgdrmsys_nonce'] ) ) : '';

			// Check if the nonce is valid and the user has permission
			if ( wp_verify_nonce( $nonce, 'astgdrmsys_edit_action' ) && current_user_can( 'manage_options' ) ) {
				$this->astgdrmsys_delete_subject( $delid );
			} else {
				wp_die( esc_html__( 'Unauthorized delete attempt.', 'result-management-system-for-institutions' ) );
			}
		}
		// Handle updates
		elseif ( isset( $_POST['updatesubmit'] ) ) {
			$this->astgdrmsys_update_subject();
		}
		// Handle add
		elseif ( isset( $_POST['addsubmit'] ) ) {
			$this->astgdrmsys_add_subject();
		}

		// Handle messages
		$this->handle_messages();
	}


	/**
	 * Handles the display and processing of messages.
	 *
	 * This function is responsible for managing the messages that are displayed
	 * to the user, including success, error, and informational messages. It ensures
	 * that the appropriate messages are shown based on the context and actions taken
	 * by the user.
	 *
	 * @return void
	 */
	private function handle_messages() {
		$messages = array(
			'edit' => 'Subject Updated Successfully',
			'del'  => 'Subject Deleted Successfully',
			'add'  => 'Subject Added Successfully',
		);

		foreach ( $messages as $key => $text ) {
            // phpcs:ignore WordPress.Security.NonceVerification
			if ( isset( $_GET[ $key ] ) && $_GET[ $key ] === 'true' ) {
				$this->add_message( 'success', $text );
			}
		}
	}

	/**
	 * Adds a message to the system.
	 *
	 * @param string $type The type of the message (e.g., 'error', 'success', 'info').
	 * @param string $text The content of the message.
	 */
	private function add_message( $type, $text ) {
		$this->messages[] = array(
			'type' => $type,
			'text' => $text,
		);
	}

	/**
	 * Deletes a subject based on the provided ID.
	 *
	 * @param int $id The ID of the subject to be deleted.
	 *
	 * @return void
	 */
	private function astgdrmsys_delete_subject( $id ) {
		$this->wpdb->query( 'START TRANSACTION' );

		try {
			$this->wpdb->delete( $this->prefix . 'astgdrmsys_subject', array( 'id' => $id ), array( '%d' ) );
			$this->wpdb->query( 'COMMIT' );
			wp_safe_redirect(
				add_query_arg(
					array(
						'page' => 'astgdrmsys-subject',
						'del'  => 'true',
					),
					admin_url( 'admin.php' )
				)
			);
			exit;
		} catch ( Exception $e ) {
			$this->wpdb->query( 'ROLLBACK' );
			$this->add_message( 'error', 'Error deleting subject' );
		}
	}

	/**
	 * Updates the subject information in the database.
	 *
	 * This function is responsible for updating the details of a subject
	 * in the database. It retrieves the necessary data from the request,
	 * validates it, and performs the update operation.
	 *
	 * @return void
	 */
	private function astgdrmsys_update_subject() {
		// Check if the form was submitted and the nonce is valid
		if (
			! isset( $_POST['updatesub'], $_GET['editid'], $_POST['astgdrmsys_update_subject_nonce'] ) ||
			! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['astgdrmsys_update_subject_nonce'] ) ), 'astgdrmsys_update_subject_action' )
		) {
			// Nonce is invalid, do not proceed with the action
			wp_die( esc_html__( 'Security check failed. Please try again.', 'result-management-system-for-institutions' ) );
		}

		$id               = absint( wp_unslash( $_GET['editid'] ) );
		$updateclass      = isset( $_POST['updateclass'] ) ? sanitize_text_field( wp_unslash( $_POST['updateclass'] ) ) : '';
		$updatedepartment = isset( $_POST['updatedepartment'] ) ? sanitize_text_field( wp_unslash( $_POST['updatedepartment'] ) ) : '';
		$updatesub        = isset( $_POST['updatesub'] ) ? sanitize_text_field( wp_unslash( $_POST['updatesub'] ) ) : '';
		$updatesubcode    = isset( $_POST['updatesubcode'] ) ? sanitize_text_field( wp_unslash( $_POST['updatesubcode'] ) ) : '';
		$updatemin        = isset( $_POST['updatemin'] ) ? sanitize_text_field( wp_unslash( $_POST['updatemin'] ) ) : '';
		$updatetotal      = isset( $_POST['updatetotal'] ) ? sanitize_text_field( wp_unslash( $_POST['updatetotal'] ) ) : '';

		$updated = $this->wpdb->update(
			$this->prefix . 'astgdrmsys_subject',
			array(
				'subname'   => $updatesub,
				'subcode'   => $updatesubcode,
				'minmark'   => $updatemin,
				'total'     => $updatetotal,
			),
			array( 'id' => $id ),
			array( '%s', '%s', '%d', '%d' ),
			array( '%d' )
		);

		if ( $updated !== false ) {
			wp_safe_redirect(
				add_query_arg(
					array(
						'page'             => 'astgdrmsys-subject',
						'edit'             => 'true',
						'classsearch'      => $updateclass,
						'departmentsearch' => $updatedepartment,
					),
					admin_url( 'admin.php' )
				)
			);
			exit;
		}
	}

	/**
	 * Adds a new subject to the system.
	 *
	 * This function handles the logic for adding a new subject to the database.
	 * It validates the input data, processes the form submission, and saves the
	 * new subject information to the database.
	 *
	 * @return void
	 */
	private function astgdrmsys_add_subject() {
		global $wpdb;

		// Check nonce and fields first
		if ( ! isset( $_POST['astgdrmsys_add_subject_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['astgdrmsys_add_subject_nonce'] ) ), 'astgdrmsys_add_subject_action' ) ) {
			$this->add_message( 'error', __( 'Invalid request. Please try again.', 'result-management-system-for-institutions' ) );
			return;
		}

		$subjectadd      = isset( $_POST['subject'] ) ? sanitize_text_field( wp_unslash( $_POST['subject'] ) ) : '';
		$subjectcodeadd  = isset( $_POST['subjectcode'] ) ? sanitize_text_field( wp_unslash( $_POST['subjectcode'] ) ) : '';
		$classadded      = isset( $_POST['classadd'] ) ? absint( wp_unslash( $_POST['classadd'] ) ) : 0;
		$departmentadd   = isset( $_POST['departmentadd'] ) ? absint( wp_unslash( $_POST['departmentadd'] ) ) : 0;
		$minmarkqadd     = isset( $_POST['minmark'] ) ? absint( wp_unslash( $_POST['minmark'] ) ) : 0;
		$totaladd        = isset( $_POST['total'] ) ? absint( wp_unslash( $_POST['total'] ) ) : 0;

		// Cache key for checking duplicate subject code
		$cache_key     = 'subject_code_check_' . md5( $subjectcodeadd . $classadded . $departmentadd );
		$check_subcode = wp_cache_get( $cache_key );

		if ( $check_subcode === false ) {
			// sanitize the table name
			$subject_table = esc_sql( $this->prefix . 'astgdrmsys_subject' );
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
			$check_subcode = $wpdb->get_var(
				$wpdb->prepare(
                    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
					"SELECT COUNT(*) FROM $subject_table WHERE subcode = %s AND class = %d AND department = %d",
					$subjectcodeadd,
					$classadded,
					$departmentadd
				)
			);
			// Store the result in cache for future use
			wp_cache_set( $cache_key, $check_subcode );
		}

		// Check if the subject code already exists
		if ( $check_subcode > 0 ) {
			$this->add_message( 'error', esc_html__( 'Subject Code already exists! Please choose a different code.', 'result-management-system-for-institutions' ) );
			return;
		}

		// Insert subject
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$inserted = $wpdb->insert(
			$this->prefix . 'astgdrmsys_subject',
			array(
				'class'      => $classadded,
				'department' => $departmentadd,
				'subname'    => $subjectadd,
				'subcode'    => $subjectcodeadd,
				'minmark'    => $minmarkqadd,
				'total'      => $totaladd,
			),
			array( '%d', '%d', '%s', '%s', '%d', '%d' )
		);

		if ( $inserted ) {
			$redirect_url = esc_url_raw(
				add_query_arg(
					array(
						'page'             => 'astgdrmsys-subject',
						'add'              => 'true',
						'classsearch'      => $classadded,
						'departmentsearch' => $departmentadd,
					),
					admin_url( 'admin.php' )
				)
			);

			wp_safe_redirect( $redirect_url );
			exit;
		}
	}

	/**
	 * Renders the add-subject page.
	 *
	 * This function is responsible for rendering the user interface for adding a new subject
	 * in the RMS Result Management System plugin.
	 *
	 * @return void
	 */
	public function astgdrmsys_subject_render() {
		// Check if it is a POST request and verify the nonce
		if ( isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD'] === 'POST' ) {
			if (
				! isset( $_POST['astgdrmsys_subject_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['astgdrmsys_subject_nonce'] ) ), 'astgdrmsys_subject_action' )
			) {
				wp_die( esc_html__( 'Security check failed. Please try again.', 'result-management-system-for-institutions' ) );
			}
		}
		// Display messages
		foreach ( $this->messages as $message ) {
			printf(
				'<div class="notice notice-%1$s is-dismissible"><p>%2$s</p></div>',
				esc_attr( $message['type'] ),
				esc_html( $message['text'] )
			);
		}

		// Check if editing a subject
		if ( isset( $_GET['editid'] ) ) {
			$this->astgdrmsys_render_edit_form();
		} else {
			// Only render the search form and list view if not editing
			$this->astgdrmsys_render_search_form();
			$this->astgdrmsys_render_list_view();
		}

		// Render the add modal
		$this->astgdrmsys_render_add_modal();
	}

	/**
	 * Renders the search form for the subject management interface.
	 *
	 * This function outputs the HTML for the search form, allowing users to search for subjects
	 * within the result management system.
	 *
	 * @return void
	 */
	private function astgdrmsys_render_search_form() {
		global $wpdb;
		$prefix = $this->prefix; ?>
		<div class='container astgdrmsys-premium-wrap'>
			<div class="premium-page-header">
				<div class="page-header-text">
					<h1><?php esc_html_e( 'Subjects', 'result-management-system-for-institutions' ); ?></h1>
					<p>Manage the subjects for all classes.</p>
				</div>
				<div class="page-header-actions">
					<button id="addsub" class="hero-btn primary-btn">
						<i class="dashicons dashicons-plus"></i> <?php esc_html_e( 'Add Subject', 'result-management-system-for-institutions' ); ?>
					</button>
				</div>
			</div>

			<form method='get' action='' onsubmit="return validateForm();" class="premium-filter-form">
				<?php wp_nonce_field( 'astgdrmsys_subject_action', 'astgdrmsys_subject_nonce' ); ?>
				<input type='text' name='page' hidden value='astgdrmsys-subject'>
				
				<div class="filter-group">
					<label>Select Class :</label>
					<select name='classsearch' class="selectClass premium-input" required>
						<option value="" selected disabled>Select Class</option>
						<?php
						$cache_key = 'astgdrmsys_all_classes';
						$classes   = wp_cache_get( $cache_key );

						if ( $classes === false ) {
							$class_table = esc_sql( $prefix . 'astgdrmsys_class' );

                            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
							$classes = $wpdb->get_results(
								$wpdb->prepare(
                                    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
									"SELECT * FROM $class_table"
								),
								ARRAY_A
							);
							// Store the result in cache for future use
							wp_cache_set( $cache_key, $classes );
						}
						// Loop through the classes and create options
						foreach ( $classes as $class ) {
							?>
							<option value="<?php echo esc_html( $class['id'] ); ?>"><?php echo esc_html( $class['class'] ); ?></option>
							<?php
						}
						?>
					</select>
				</div>
				
				<div class="filter-group">
					<label>Select Department :</label>
					<select name="departmentsearch" class="selectDepartment premium-input" required>
						<option value="">Select Department</option>
					</select>
				</div>
				
				<div class="filter-actions" style="margin-bottom: 5px;">
					<button type='submit' class='hero-btn primary-btn'>View Subjects</button>
				</div>
			</form>
		</div>
		<?php
	}

	/**
	 * Renders the list view for the subjects.
	 *
	 * This function is responsible for generating and displaying the list view
	 * of subjects in the admin panel. It retrieves the necessary data and
	 * outputs the HTML for the list.
	 *
	 * @return void
	 */
	private function astgdrmsys_render_list_view() {
		global $wpdb;
		$prefix = $this->prefix;
		// Check if the class and department are set in the GET parameters
		if ( isset( $_GET['classsearch'], $_GET['departmentsearch'], $_GET['astgdrmsys_subject_nonce'] ) ) {
			// Verify the nonce
			if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['astgdrmsys_subject_nonce'] ) ), 'astgdrmsys_subject_action' ) ) {
				// Nonce is invalid, redirect with an error message
				wp_die( esc_html__( 'Security check failed. Please try again.', 'result-management-system-for-institutions' ) );
			}

			// Sanitize the inputs from GET parameters
			$classsearch      = isset( $_GET['classsearch'] ) ? absint( wp_unslash( $_GET['classsearch'] ) ) : 0;
			$departmentsearch = isset( $_GET['departmentsearch'] ) ? absint( wp_unslash( $_GET['departmentsearch'] ) ) : 0;

			// Sanitize table names
			$class_table   = esc_sql( $prefix . 'astgdrmsys_class' );
			$dept_table    = esc_sql( $prefix . 'astgdrmsys_department' );
			$subject_table = esc_sql( $prefix . 'astgdrmsys_subject' );

			// Fetch class name
			$class_cache_key = 'astgdrmsys_class_' . $classsearch;
			$classresult     = wp_cache_get( $class_cache_key );

			if ( $classresult === false ) {
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
				$classresult = $wpdb->get_row(
					$wpdb->prepare(
                        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
						"SELECT class FROM `{$class_table}` WHERE id = %d",
						$classsearch
					)
				);
				wp_cache_set( $class_cache_key, $classresult );
			}
			$classname = $classresult ? esc_html( $classresult->class ) : __( 'Unknown Class', 'result-management-system-for-institutions' );

			// Fetch department name
			$dept_cache_key   = 'astgdrmsys_department_' . $departmentsearch;
			$departmentresult = wp_cache_get( $dept_cache_key );

			if ( $departmentresult === false ) {
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
				$departmentresult = $wpdb->get_row(
					$wpdb->prepare(
                        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
						"SELECT department FROM `{$dept_table}` WHERE id = %d",
						$departmentsearch
					)
				);
				// Store the result in cache for future use
				wp_cache_set( $dept_cache_key, $departmentresult );
			}
			$departmentname = $departmentresult ? esc_html( $departmentresult->department ) : __( 'Unknown Department', 'result-management-system-for-institutions' );

			// Fetch subjects
			$subjects_cache_key = 'astgdrmsys_subjects_' . md5( $classsearch . '_' . $departmentsearch );
			$subjects           = wp_cache_get( $subjects_cache_key );

			if ( $subjects === false ) {
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
				$subjects = $wpdb->get_results(
					$wpdb->prepare(
                        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
						"SELECT * FROM $subject_table WHERE `class` = %d AND `department` = %d",
						$classsearch,
						$departmentsearch
					),
					ARRAY_A
				);
				wp_cache_set( $subjects_cache_key, $subjects );
			}

			?>
			<div class='subjectscontainer astgdrmsys-premium-wrap m-4 px-1'>
				<center>
					<h3 class='heading'>
						<?php
						echo esc_html__( 'Subjects in ', 'result-management-system-for-institutions' ) . "<span class='show-classname'>" . esc_html( $classname ) . ' - ' . esc_html( $departmentname ) . '</span>';
						?>
					</h3>
				</center>
				<table class="styled-table">
					<thead>
						<tr class="title-tr">
							<th scope="col"><?php esc_html_e( 'Subject', 'result-management-system-for-institutions' ); ?></th>
							<th scope="col"><?php esc_html_e( 'Subject Code', 'result-management-system-for-institutions' ); ?></th>
							<th scope="col"><?php esc_html_e( 'Minimum Mark', 'result-management-system-for-institutions' ); ?></th>
							<th scope="col"><?php esc_html_e( 'Total Mark', 'result-management-system-for-institutions' ); ?></th>
							<th scope="col"><?php esc_html_e( 'Action', 'result-management-system-for-institutions' ); ?></th>
						</tr>
					</thead>
					<tbody>
						<?php
						if ( $subjects ) {
							foreach ( $subjects as $subject ) {
								?>
								<tr>
									<td><strong><?php echo esc_html( $subject['subname'] ); ?></strong></td>
									<td><?php echo esc_html( $subject['subcode'] ); ?></td>
									<td><?php echo esc_html( $subject['minmark'] ); ?></td>
									<td><?php echo esc_html( $subject['total'] ); ?></td>
									<td>
										<?php
										$edit_id      = intval( $subject['id'] );
										$class_search = sanitize_text_field( wp_unslash( $_GET['classsearch'] ) );
										$cache_key    = wp_create_nonce( 'astgdrmsys_edit_action' );
										?>
										<a href="
										<?php
										echo esc_url(
											admin_url(
												add_query_arg(
													array(
														'page' => 'astgdrmsys-subject',
														'editid' => $edit_id,
														'astgdrmsys_nonce' => $cache_key,
													),
													'admin.php'
												)
											)
										);
										?>
													" class="button button-small">
											<span class="dashicons dashicons-edit"></span>
										</a>
										<a href="
										<?php
										echo esc_url(
											add_query_arg(
												array(
													'page' => 'astgdrmsys-subject',
													'classsearch' => $class_search,
													'delid' => $edit_id,
													'astgdrmsys_nonce' => $cache_key,
												),
												admin_url( 'admin.php' )
											)
										);
										?>
													"
											onclick="return confirm('<?php esc_attr_e( 'Are you sure you want to delete this subject?', 'result-management-system-for-institutions' ); ?>');"
											class="button button-small button-link-delete">
											<span class="dashicons dashicons-trash"></span>
										</a>
									</td>
								</tr>
								<?php
							}
						} else {
							echo '<tr><td colspan="7"><center>' . esc_html__( 'No Subjects found in ', 'result-management-system-for-institutions' ) . esc_html( $classname ) . ' - ' . esc_html( $departmentname ) . '</center></td></tr>';
						}
						?>
					</tbody>
				</table>
			</div>
			<?php
		}
	}

	/**
	 * Renders the edit form for the subject.
	 *
	 * This function generates and displays the HTML form used to edit a subject.
	 * It is intended to be used within the context of the subject management
	 * functionality of the plugin.
	 *
	 * @return void
	 */
	private function astgdrmsys_render_edit_form() {
		global $wpdb;

		// Check if nonce is set and valid
		if ( isset( $_GET['editid'], $_GET['astgdrmsys_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['astgdrmsys_nonce'] ) ), 'astgdrmsys_edit_action' ) ) {
			// Sanitize and validate the 'editid' parameter
			$id = absint( $_GET['editid'] ); // absint ensures the value is a positive integer

			// Handle invalid 'id'
			if ( $id <= 0 ) {
				wp_die( esc_html__( 'Invalid ID provided.', 'result-management-system-for-institutions' ) );
			}

		} else {
			// Handle the missing or invalid nonce
			wp_die( esc_html__( 'Security check failed. Please try again.', 'result-management-system-for-institutions' ) );
		}

		// sanitize the table name
		$subject_table = esc_sql( $this->prefix . 'astgdrmsys_subject' );
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$subject = $wpdb->get_row(
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
			$wpdb->prepare( "SELECT * FROM $subject_table WHERE id = %d", $id )
		);
		// Check if the subject exists
		if ( ! $subject ) {
			wp_die( 'Subject not found' );
		}
		?>
		<div class="wrap astgdrmsys-premium-wrap">
			<h1><?php esc_html_e( 'Edit Subject', 'result-management-system-for-institutions' ); ?></h1>
			<form method="post" action="">
				<?php wp_nonce_field( 'astgdrmsys_subject_action', 'astgdrmsys_nonce' ); ?>
				<?php wp_nonce_field( 'astgdrmsys_update_subject_action', 'astgdrmsys_update_subject_nonce' ); ?>
				<table class="form-table">
					<input type="text" name="updateclass" id="updateclass" value="<?php echo esc_attr( $subject->class ); ?>" hidden>
					<input type="text" name="updatedepartment" id="updatedepartment" value="<?php echo esc_attr( $subject->department ); ?>" hidden>
					<tr>
						<th><label for="updatesub"><?php esc_html_e( 'Subject Name', 'result-management-system-for-institutions' ); ?></label></th>
						<td>
							<input type="text" name="updatesub" id="updatesub" value="<?php echo esc_attr( $subject->subname ); ?>" class="regular-text" required>
						</td>
					</tr>
					<tr>
						<th><label for="updatesubcode"><?php esc_html_e( 'Subject Code', 'result-management-system-for-institutions' ); ?></label></th>
						<td>
							<input type="text" name="updatesubcode" id="updatesubcode" value="<?php echo esc_attr( $subject->subcode ); ?>" class="regular-text" required>
						</td>
					</tr>
					<tr>
						<th><label for="updatemin"><?php esc_html_e( 'Minimum Passing Mark', 'result-management-system-for-institutions' ); ?></label></th>
						<td>
							<input type="number" name="updatemin" id="updatemin" value="<?php echo esc_attr( $subject->minmark ); ?>" class="regular-text">
						</td>
					</tr>
					<tr>
						<th><label for="updatetotal"><?php esc_html_e( 'Total Mark', 'result-management-system-for-institutions' ); ?></label></th>
						<td>
							<input type="number" name="updatetotal" id="updatetotal" value="<?php echo esc_attr( $subject->total ); ?>" class="regular-text">
						</td>
					</tr>
				</table>
				<div class="button-group">
					<?php submit_button( __( 'Update Subject', 'result-management-system-for-institutions' ), 'primary', 'updatesubmit' ); ?>
					<button type="button" class="button" onclick="window.history.back();"><?php esc_html_e( 'Cancel', 'result-management-system-for-institutions' ); ?></button>
				</div>
			</form>
		</div>
		<?php
	}

	/**
	 * Renders the modal for adding a new subject.
	 *
	 * This function generates and displays the HTML for a modal dialog
	 * that allows users to add a new subject to the system.
	 *
	 * @return void
	 */
	private function astgdrmsys_render_add_modal() {
		?>
		<div id="addmodal" class="modal">
			<div class="modal-content">
				<span class="close-subject-modal">&times;</span>
				<h2><?php esc_html_e( 'Add Subject', 'result-management-system-for-institutions' ); ?></h2>
				<form method="post" action="">
					<?php wp_nonce_field( 'astgdrmsys_add_subject_action', 'astgdrmsys_add_subject_nonce' ); ?>
					<?php wp_nonce_field( 'astgdrmsys_subject_action', 'astgdrmsys_nonce' ); ?>
					<div class="form-field">
						<label for="subject"><?php esc_html_e( 'Subject Name:', 'result-management-system-for-institutions' ); ?></label>
						<input type="text" name="subject" id="subject" required>
					</div>
					<div class="form-field">
						<label for="subjectcode"><?php esc_html_e( 'Subject Code:', 'result-management-system-for-institutions' ); ?></label>
						<input type="text" name="subjectcode" id="subjectcode" required>
					</div>
					<div class="form-field">
						<label for="classadd"><?php esc_html_e( 'Class:', 'result-management-system-for-institutions' ); ?></label>
						<select name="classadd" class="selectClass" required>
							<option value="" disabled selected>Select Class</option>
							<?php
							// sanitize table name
							$class_table = esc_sql( $this->prefix . 'astgdrmsys_class' );
                            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
							$classes = $this->wpdb->get_results(
                                // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
								"SELECT * FROM $class_table",
								ARRAY_A
							);
							foreach ( $classes as $class ) {
								// Convert $class to array if it's an object
								if ( is_object( $class ) ) {
									$class = (array) $class;
								}
								echo "<option value='" . esc_html( $class['id'] ) . "'>" . esc_html( $class['class'] ) . '</option>';
							}
							?>
						</select>
					</div>
					<div class="form-field">
						<label for="departmentadd"><?php esc_html_e( 'Department:', 'result-management-system-for-institutions' ); ?></label>
						<select name="departmentadd" class="selectDepartment" required>
							<option value="" disabled selected>Select Department</option>
						</select>
					</div>
					<div class="form-field">
						<label for="minmark"><?php esc_html_e( 'Minimum Passing Mark:', 'result-management-system-for-institutions' ); ?></label>
						<input type="number" name="minmark" id="minmark" required>
					</div>
					<div class="form-field">
						<label for="total"><?php esc_html_e( 'Total Mark:', 'result-management-system-for-institutions' ); ?></label>
						<input type="number" name="total" id="total" required>
					</div>
					<div class="button-group">
						<?php submit_button( __( 'Add Subject', 'result-management-system-for-institutions' ), 'primary', 'addsubmit' ); ?>
						<button type="button" class="button cancel-button"><?php esc_html_e( 'Cancel', 'result-management-system-for-institutions' ); ?></button>
					</div>
				</form>
			</div>
		</div>
		<?php
	}
}

/**
 * Initialize and render the subject manager.
 *
 * This code creates an instance of the ASTGDRMSYS_Subject_Manager class
 * and calls its render method to display the subject management interface.
 *
 * @package ResultManagementSystem_Result_Management
 * @subpackage Menu_Files_Subject
 */
// Initialize the manager
$subject_manager = new ASTGDRMSYS_Subject_Manager();
$subject_manager->astgdrmsys_subject_render();
?>