<?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 Result Management System for Institutions plugin.
 *
 * It handles the addition of exam names in the plugin's menu.
 *
 * @package ResultManagementSystem
 * @subpackage Menu_Files
 * @since 1.0.0
 *
 * @file add-exam-name.php
 *
 * This file should not be accessed directly. If accessed directly, the script will exit.
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class ASTGDRMSYS_ExamName_Manager
 *
 * This class is responsible for managing exam names within the plugin.
 * It provides functionalities to add, edit, and delete exam names.
 *
 * @package ResultManagementSystem
 * @subpackage MenuFiles
 * @since 1.0.0
 */
class ASTGDRMSYS_ExamName_Manager {

	private $wpdb;
	private $prefix;

	/**
	 * Constructor method for the class.
	 *
	 * This method is automatically called when an instance of the class is created.
	 * It is typically used to initialize properties or set up any necessary configurations.
	 */
	public function __construct() {
		global $wpdb;
		$this->wpdb   = $wpdb;
		$this->prefix = $wpdb->prefix;
	}

	/**
	 * Initialize the exam name addition functionality.
	 *
	 * This method sets up the necessary components and configurations
	 * required for adding a new exam name within the plugin.
	 *
	 * @return void
	 */
	public function astgdrmsys_initialize() {
		$this->handle_actions();
		$this->astgdrmsys_render_examname_page();
	}

	/**
	 * Handles various actions related to exam names.
	 *
	 * This function processes different actions that can be performed
	 * on exam names within the plugin. It ensures that the appropriate
	 * action is taken based on the user's input or request.
	 *
	 * @return void
	 */
        private function handle_actions() {
                // Check if this is a POST request
                if ( isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD'] === 'POST' ) {
                        // Nonce check and sanitization
                        if ( ! isset( $_POST['astgdrmsys_exam_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['astgdrmsys_exam_nonce'] ) ), 'astgdrmsys_exam_action' ) ) {
                                wp_die( esc_html__( 'Invalid request. Please refresh and try again.', 'result-management-system-for-institutions' ) );
                        }
                }

                // Handle delete action
                if ( isset( $_GET['delid'] ) && isset( $_GET['astgdrmsys_exam_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['astgdrmsys_exam_nonce'] ) ), 'astgdrmsys_exam_action' ) ) {
                        $this->handle_delete();
                }

		// Handle update action
		if ( isset( $_POST['updatesubmit'] ) && isset( $_POST['astgdrmsys_exam_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['astgdrmsys_exam_nonce'] ) ), 'astgdrmsys_exam_action' ) ) {
			$this->handle_update();
		}

		// Handle add action
		if ( isset( $_POST['addsubmit'] ) && isset( $_POST['astgdrmsys_exam_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['astgdrmsys_exam_nonce'] ) ), 'astgdrmsys_exam_action' ) ) {
			$this->handle_add();
		}

                // handle publish action
                $this->handle_publish();
        }

        /**
         * Returns the available exam category options.
         *
         * @return array<string, string> Associative array of exam category keys and labels.
         */
        private function get_exam_category_options(): array {
                return array(
                        'class_test'      => __( 'Class Test', 'result-management-system-for-institutions' ),
                        'general_exam'    => __( 'General Exam', 'result-management-system-for-institutions' ),
                        'combined_result' => __( 'Combined Result', 'result-management-system-for-institutions' ),
                );
        }

        /**
         * Returns the default assessment display-name map keyed by exam type.
         *
         * @return array<string, array<string, string>>
         */
        private function get_assessment_default_map(): array {
                $baseline = $this->get_display_name_baseline();

                return array(
                        'single'    => array(
                                'first_assessment_display_name'  => $baseline['single_mark_display_name'],
                                'second_assessment_display_name' => '',
                                'third_assessment_display_name'  => '',
                                'total_display_name'             => $baseline['total_mark_display_name'],
                        ),
                        'composite' => array(
                                'first_assessment_display_name'  => $baseline['class_mark_display_name'],
                                'second_assessment_display_name' => $baseline['final_mark_display_name'],
                                'third_assessment_display_name'  => '',
                                'total_display_name'             => $baseline['total_mark_display_name'],
                        ),
                        'triple'    => array(
                                'first_assessment_display_name'  => $baseline['practical_mark_display_name'],
                                'second_assessment_display_name' => $baseline['class_mark_display_name'],
                                'third_assessment_display_name'  => $baseline['final_mark_display_name'],
                                'total_display_name'             => $baseline['total_mark_display_name'],
                        ),
                );
        }

        /**
         * Resolve assessment display names for a given exam context.
         *
         * @param array<string, mixed> $exam Exam data.
         * @return array<string, string> Resolved assessment labels.
         */
        private function resolve_assessment_display_names( array $exam ): array {
                if ( function_exists( '\\ASTGDRMSYS\\ResultManagement\\astgdrmsys_determine_assessment_display_names' ) ) {
                        return \ASTGDRMSYS\ResultManagement\astgdrmsys_determine_assessment_display_names( $exam );
                }

                return $this->fallback_assessment_display_names( $exam );
        }

        /**
         * Prepare sanitized assessment display-name input and merge defaults for the selected assessment format.
         *
         * @param array<string, string> $raw_input Raw input keyed by assessment column name.
         * @param string                $exam_type Selected exam type.
         *
         * @return array<string, string> Sanitized assessment labels ready for persistence.
         */
        private function prepare_assessment_display_input( array $raw_input, string $exam_type ): array {
                $exam = array(
                        'exam_type'                         => $exam_type,
                        'first_assessment_display_name'     => isset( $raw_input['first_assessment_display_name'] ) ? sanitize_text_field( (string) $raw_input['first_assessment_display_name'] ) : '',
                        'second_assessment_display_name'    => isset( $raw_input['second_assessment_display_name'] ) ? sanitize_text_field( (string) $raw_input['second_assessment_display_name'] ) : '',
                        'third_assessment_display_name'     => isset( $raw_input['third_assessment_display_name'] ) ? sanitize_text_field( (string) $raw_input['third_assessment_display_name'] ) : '',
                        'total_display_name'                => isset( $raw_input['total_display_name'] ) ? sanitize_text_field( (string) $raw_input['total_display_name'] ) : '',
                );

                return $this->resolve_assessment_display_names( $exam );
        }

        /**
         * Retrieve the baseline assessment display names, falling back to plugin defaults when necessary.
         *
         * @return array<string, string> Baseline assessment label values.
         */
        private function get_display_name_baseline(): array {
                $defaults = array(
                        'class_display_name'           => 'Class',
                        'dept_display_name'            => 'Department',
                        'section_display_name'         => 'Section',
                        'exam_year_display_name'       => 'Exam Year',
                        'exam_name_display_name'       => 'Exam Name',
                        'roll_display_name'            => 'Roll No',
                        'regno_display_name'           => 'Registration Number',
                        'practical_mark_display_name'  => 'Practical Mark',
                        'class_mark_display_name'      => 'Class Mark',
                        'final_mark_display_name'      => 'Final Mark',
                        'total_mark_display_name'      => 'Total Mark',
                        'single_mark_display_name'     => 'Exam Mark',
                );

                if ( function_exists( '\\ASTGDRMSYS\\ResultManagement\\astgdrmsys_get_display_name_baseline' ) ) {
                        return \ASTGDRMSYS\ResultManagement\astgdrmsys_get_display_name_baseline();
                }

                return $defaults;
        }

        /**
         * Provide a local fallback for resolving assessment display names when helper functions are unavailable.
         *
         * @param array<string, mixed> $exam Exam data used to derive label defaults.
         * @return array<string, string> Assessment labels keyed by column name.
         */
        private function fallback_assessment_display_names( array $exam ): array {
                $baseline  = $this->get_display_name_baseline();
                $exam_type = isset( $exam['exam_type'] ) ? (string) $exam['exam_type'] : 'single';

                $first  = isset( $exam['first_assessment_display_name'] ) ? trim( (string) $exam['first_assessment_display_name'] ) : '';
                $second = isset( $exam['second_assessment_display_name'] ) ? trim( (string) $exam['second_assessment_display_name'] ) : '';
                $third  = isset( $exam['third_assessment_display_name'] ) ? trim( (string) $exam['third_assessment_display_name'] ) : '';
                $total  = isset( $exam['total_display_name'] ) ? trim( (string) $exam['total_display_name'] ) : '';

                $defaults_by_type = array(
                        'single'    => array(
                                'first'  => $baseline['single_mark_display_name'],
                                'second' => '',
                                'third'  => '',
                        ),
                        'composite' => array(
                                'first'  => $baseline['class_mark_display_name'],
                                'second' => $baseline['final_mark_display_name'],
                                'third'  => '',
                        ),
                        'triple'    => array(
                                'first'  => $baseline['practical_mark_display_name'],
                                'second' => $baseline['class_mark_display_name'],
                                'third'  => $baseline['final_mark_display_name'],
                        ),
                );

                $fallbacks = $defaults_by_type[ $exam_type ] ?? $defaults_by_type['single'];

                return array(
                        'first_assessment_display_name'  => $first !== '' ? $first : $fallbacks['first'],
                        'second_assessment_display_name' => $second !== '' ? $second : ( $fallbacks['second'] ?? '' ),
                        'third_assessment_display_name'  => $third !== '' ? $third : ( $fallbacks['third'] ?? '' ),
                        'total_display_name'             => $total !== '' ? $total : $baseline['total_mark_display_name'],
                );
        }

        /**
         * Normalizes a set of subject entries into a consistent structure.
         *
         * @param array<int, mixed> $subjects Raw subject entries.
         *
         * @return array<int, array<string, mixed>> Normalized subject entries.
         */
        private function normalize_subject_entries( array $subjects ): array {
                $normalized = array();

                foreach ( $subjects as $subject ) {
                        if ( is_object( $subject ) ) {
                                $subject = (array) $subject;
                        }

                        if ( ! is_array( $subject ) ) {
                                continue;
                        }

                        $subject_id = isset( $subject['id'] ) ? intval( $subject['id'] ) : 0;

                        if ( $subject_id <= 0 ) {
                                continue;
                        }

                        $name = '';
                        if ( isset( $subject['name'] ) ) {
                                $name = sanitize_text_field( $subject['name'] );
                        } elseif ( isset( $subject['subname'] ) ) {
                                $name = sanitize_text_field( $subject['subname'] );
                        }

                        $code = '';
                        if ( isset( $subject['code'] ) ) {
                                $code = sanitize_text_field( (string) $subject['code'] );
                        } elseif ( isset( $subject['subcode'] ) ) {
                                $code = sanitize_text_field( (string) $subject['subcode'] );
                        }

                        $full_mark = 0.0;
                        if ( isset( $subject['full_mark'] ) && $subject['full_mark'] !== '' ) {
                                $full_mark = floatval( $subject['full_mark'] );
                        } elseif ( isset( $subject['total'] ) && $subject['total'] !== '' ) {
                                $full_mark = floatval( $subject['total'] );
                        }

                        $normalized[] = array(
                                'id'        => $subject_id,
                                'name'      => $name,
                                'code'      => $code,
                                'full_mark' => $full_mark,
                        );
                }

                return $normalized;
        }

        /**
         * Parses a stored subject list into a normalized structure.
         *
         * @param mixed $value Stored subject data.
         *
         * @return array<int, array<string, mixed>> Normalized subject entries.
         */
        private function parse_subject_full_marks( $value ): array {
                if ( empty( $value ) ) {
                        return array();
                }

                if ( is_string( $value ) ) {
                        $decoded = json_decode( $value, true );

                        if ( json_last_error() === JSON_ERROR_NONE && is_array( $decoded ) ) {
                                $value = $decoded;
                        } else {
                                $maybe_unserialized = maybe_unserialize( $value );

                                if ( is_array( $maybe_unserialized ) ) {
                                        $value = $maybe_unserialized;
                                }
                        }
                } elseif ( is_object( $value ) ) {
                        $value = (array) $value;
                }

                if ( ! is_array( $value ) ) {
                        return array();
                }

                return $this->normalize_subject_entries( $value );
        }

        /**
         * Parses stored combined exam component data into a normalized structure.
         *
         * @param mixed $value Raw stored value.
         *
         * @return array{class_tests: array<int>, general_exam: int} Parsed component IDs.
         */
        private function parse_combined_component_exams( $value ): array {
                $defaults = array(
                        'class_tests'  => array(),
                        'general_exam' => 0,
                );

                if ( empty( $value ) ) {
                        return $defaults;
                }

                if ( is_string( $value ) ) {
                        $decoded = json_decode( $value, true );

                        if ( json_last_error() === JSON_ERROR_NONE && is_array( $decoded ) ) {
                                $value = $decoded;
                        } else {
                                $maybe_unserialized = maybe_unserialize( $value );

                                if ( is_array( $maybe_unserialized ) ) {
                                        $value = $maybe_unserialized;
                                }
                        }
                } elseif ( is_object( $value ) ) {
                        $value = (array) $value;
                }

                if ( ! is_array( $value ) ) {
                        return $defaults;
                }

                $class_tests = array();
                if ( isset( $value['class_tests'] ) && is_array( $value['class_tests'] ) ) {
                        foreach ( $value['class_tests'] as $exam_id ) {
                                $exam_id = intval( $exam_id );

                                if ( $exam_id > 0 ) {
                                        $class_tests[] = $exam_id;
                                }
                        }
                }

                $class_tests = array_values( array_unique( $class_tests ) );
                $general     = isset( $value['general_exam'] ) ? intval( $value['general_exam'] ) : 0;

                return array(
                        'class_tests'  => $class_tests,
                        'general_exam' => $general > 0 ? $general : 0,
                );
        }

        /**
         * Normalizes various department identifiers (ID or name) to a canonical form for comparisons.
         *
         * @param string $value Department identifier from the request or database.
         *
         * @return string Normalized identifier when possible, otherwise the original value.
         */
        private function normalize_department_identifier( string $value ): string {
                $value = trim( $value );

                if ( $value === '' ) {
                        return '';
                }

                $departments = $this->get_departments( $this->wpdb );

                foreach ( $departments as $department ) {
                        if ( (string) $department['id'] === $value ) {
                                return (string) $department['id'];
                        }
                }

                foreach ( $departments as $department ) {
                        if ( strcasecmp( $department['department'], $value ) === 0 ) {
                                return (string) $department['id'];
                        }
                }

                return $value;
        }

        /**
         * Sanitizes raw combined exam component inputs from the request.
         *
         * @param mixed $class_tests_input Selected class test IDs.
         * @param mixed $general_input     Selected general exam ID.
         *
         * @return array{class_tests: array<int>, general_exam: int} Sanitized values.
         */
        private function prepare_combined_component_input( $class_tests_input, $general_input ): array {
                $class_tests = array();

                if ( is_array( $class_tests_input ) ) {
                        $class_tests_input = wp_unslash( $class_tests_input );
                        foreach ( $class_tests_input as $value ) {
                                $value = intval( $value );
                                if ( $value > 0 ) {
                                        $class_tests[] = $value;
                                }
                        }
                } elseif ( ! empty( $class_tests_input ) ) {
                        $value = intval( $class_tests_input );
                        if ( $value > 0 ) {
                                $class_tests[] = $value;
                        }
                }

                $class_tests = array_values( array_unique( $class_tests ) );
                $general     = intval( $general_input );

                return array(
                        'class_tests'  => $class_tests,
                        'general_exam' => $general > 0 ? $general : 0,
                );
        }

        /**
         * Validates combined exam component selections and fetches their metadata.
         *
         * @param array $components       Raw component array with IDs.
         * @param int   $class_id         Current class ID.
         * @param string $department_value Current department identifier.
         * @param int   $current_exam_id  Current exam ID to prevent self-references.
         *
         * @return array{components: array{class_tests: array<int>, general_exam: int}, records: array<int, array<string, mixed>>}
         */
        private function validate_combined_component_exams( array $components, int $class_id, string $department_value, int $current_exam_id = 0 ): array {
                $class_tests = array();

                if ( isset( $components['class_tests'] ) && is_array( $components['class_tests'] ) ) {
                        foreach ( $components['class_tests'] as $exam_id ) {
                                $exam_id = intval( $exam_id );

                                if ( $exam_id > 0 && $exam_id !== $current_exam_id ) {
                                        $class_tests[] = $exam_id;
                                }
                        }
                }

                $general_exam_id = isset( $components['general_exam'] ) ? intval( $components['general_exam'] ) : 0;

                if ( $general_exam_id <= 0 || $general_exam_id === $current_exam_id ) {
                        wp_die( esc_html__( 'Please select a valid General Exam to combine.', 'result-management-system-for-institutions' ) );
                }

                $class_tests = array_values( array_unique( array_diff( $class_tests, array( $general_exam_id ) ) ) );

                if ( empty( $class_tests ) ) {
                        wp_die( esc_html__( 'Select at least one Class Test exam to build a combined result.', 'result-management-system-for-institutions' ) );
                }

                $exam_ids = $class_tests;
                $exam_ids[] = $general_exam_id;
                $exam_ids   = array_values( array_unique( $exam_ids ) );

                $placeholders = implode( ',', array_fill( 0, count( $exam_ids ), '%d' ) );
                $exam_table   = esc_sql( $this->prefix . 'astgdrmsys_exam_name' );

                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                $records = $this->wpdb->get_results(
                        $this->wpdb->prepare(
                                "SELECT id, class_id, department, exam_category, exam_year_id FROM {$exam_table} WHERE id IN ($placeholders)",
                                $exam_ids
                        ),
                        ARRAY_A
                );

                $record_map = array();
                foreach ( $records as $record ) {
                        $record_map[ (int) $record['id'] ] = $record;
                }

                if ( ! isset( $record_map[ $general_exam_id ] ) ) {
                        wp_die( esc_html__( 'The selected General Exam could not be found.', 'result-management-system-for-institutions' ) );
                }

                $target_department = $this->normalize_department_identifier( $department_value );
                $general_record    = $record_map[ $general_exam_id ];
                $general_category  = $general_record['exam_category'] ?? 'general_exam';

                if ( 'general_exam' !== $general_category ) {
                        wp_die( esc_html__( 'The selected General Exam must use the General Exam type.', 'result-management-system-for-institutions' ) );
                }

                if ( $class_id > 0 && intval( $general_record['class_id'] ) !== $class_id ) {
                        wp_die( esc_html__( 'The selected General Exam belongs to a different class.', 'result-management-system-for-institutions' ) );
                }

                if ( $target_department !== '' ) {
                        $general_department = $this->normalize_department_identifier( (string) ( $general_record['department'] ?? '' ) );

                        if ( $general_department !== '' && $general_department !== $target_department ) {
                                wp_die( esc_html__( 'The selected General Exam belongs to a different department.', 'result-management-system-for-institutions' ) );
                        }
                }

                foreach ( $class_tests as $exam_id ) {
                        if ( ! isset( $record_map[ $exam_id ] ) ) {
                                wp_die( esc_html__( 'One of the selected Class Test exams could not be found.', 'result-management-system-for-institutions' ) );
                        }

                        $record   = $record_map[ $exam_id ];
                        $category = $record['exam_category'] ?? 'general_exam';

                        if ( 'class_test' !== $category ) {
                                wp_die( esc_html__( 'All selected exams must use the Class Test exam type.', 'result-management-system-for-institutions' ) );
                        }

                        if ( $class_id > 0 && intval( $record['class_id'] ) !== $class_id ) {
                                wp_die( esc_html__( 'One of the selected Class Test exams belongs to a different class.', 'result-management-system-for-institutions' ) );
                        }

                        if ( $target_department !== '' ) {
                                $record_department = $this->normalize_department_identifier( (string) ( $record['department'] ?? '' ) );

                                if ( $record_department !== '' && $record_department !== $target_department ) {
                                        wp_die( esc_html__( 'One of the selected Class Test exams belongs to a different department.', 'result-management-system-for-institutions' ) );
                                }
                        }
                }

                return array(
                        'components' => array(
                                'class_tests'  => $class_tests,
                                'general_exam' => $general_exam_id,
                        ),
                        'records'    => $record_map,
                );
        }

        /**
         * Retrieves subjects for a class/department combination in normalized format.
         *
         * @param int    $class_id         The class ID.
         * @param string $department_value The department identifier.
         *
         * @return array<int, array<string, mixed>> Normalized subject entries.
         */
        private function get_subjects_for_exam_context( int $class_id, string $department_value ): array {
                if ( $class_id <= 0 ) {
                        return array();
                }

                if ( function_exists( '\\ASTGDRMSYS\\ResultManagement\\astgdrmsys_get_subjects_for_exam' ) ) {
                        $subjects = \ASTGDRMSYS\ResultManagement\astgdrmsys_get_subjects_for_exam( $this->wpdb, $class_id, $department_value );

                        if ( is_array( $subjects ) ) {
                                return $this->normalize_subject_entries( $subjects );
                        }
                }

                return array();
        }

        /**
         * Builds the subject list that should be displayed on the edit screen.
         *
         * @param array<string, mixed> $exam Exam data.
         *
         * @return array<int, array<string, mixed>> Subject entries for display.
         */
        private function get_exam_subjects_for_display( array $exam ): array {
                $stored_subjects = array();

                if ( isset( $exam['subject_full_marks'] ) ) {
                        $stored_subjects = $this->parse_subject_full_marks( $exam['subject_full_marks'] );
                }

                if ( ! empty( $stored_subjects ) ) {
                        return $stored_subjects;
                }

                $class_id         = isset( $exam['class_id'] ) ? intval( $exam['class_id'] ) : 0;
                $department_value = isset( $exam['department'] ) ? (string) $exam['department'] : '';

                return $this->get_subjects_for_exam_context( $class_id, $department_value );
        }

        /**
         * Sanitizes and prepares subject data received from form submissions.
         *
         * @param mixed  $raw_input        Raw subject data from the request.
         * @param int    $class_id         The associated class ID.
         * @param string $department_value The associated department identifier.
         *
         * @return array<int, array<string, mixed>> Sanitized subject list.
         */
        private function prepare_subject_full_marks_input( $raw_input, int $class_id, string $department_value ): array {
                if ( is_array( $raw_input ) ) {
                        $raw_input = wp_unslash( $raw_input );
                } else {
                        $raw_input = array();
                }

                $normalized_input = array();

                foreach ( $raw_input as $subject_id => $subject_data ) {
                        $subject_id = intval( $subject_id );

                        if ( $subject_id <= 0 ) {
                                continue;
                        }

                        if ( is_object( $subject_data ) ) {
                                $subject_data = (array) $subject_data;
                        }

                        if ( ! is_array( $subject_data ) ) {
                                $subject_data = array();
                        }

                        $normalized_input[ $subject_id ] = array(
                                'name'      => isset( $subject_data['name'] ) ? sanitize_text_field( $subject_data['name'] ) : '',
                                'code'      => isset( $subject_data['code'] ) ? sanitize_text_field( (string) $subject_data['code'] ) : '',
                                'full_mark' => isset( $subject_data['full_mark'] ) && $subject_data['full_mark'] !== '' ? floatval( $subject_data['full_mark'] ) : null,
                        );
                }

                $subjects = $this->get_subjects_for_exam_context( $class_id, $department_value );

                if ( empty( $subjects ) ) {
                        $sanitized = array();

                        foreach ( $normalized_input as $subject_id => $data ) {
                                $sanitized[] = array(
                                        'id'        => $subject_id,
                                        'name'      => $data['name'],
                                        'code'      => $data['code'],
                                        'full_mark' => $data['full_mark'] ?? 0,
                                );
                        }

                        return $sanitized;
                }

                $result = array();

                foreach ( $subjects as $subject ) {
                        $subject_id = $subject['id'];
                        $entry      = $subject;

                        if ( isset( $normalized_input[ $subject_id ] ) ) {
                                $input_data = $normalized_input[ $subject_id ];

                                if ( $input_data['name'] !== '' ) {
                                        $entry['name'] = $input_data['name'];
                                }

                                if ( $input_data['code'] !== '' ) {
                                        $entry['code'] = $input_data['code'];
                                }

                                if ( $input_data['full_mark'] !== null ) {
                                        $entry['full_mark'] = $input_data['full_mark'];
                                }
                        }

                        $result[] = $entry;
                }

                return $result;
        }

        /**
         * Builds a stable lookup key for matching student records across exams.
         *
         * @param array<string, mixed> $student Student record from the student_result table.
         *
         * @return string Lookup key or empty string when insufficient data is available.
         */
        private function build_student_index_key( array $student ): string {
                if ( ! empty( $student['regno'] ) ) {
                        return 'regno:' . strtolower( trim( (string) $student['regno'] ) );
                }

                if ( ! empty( $student['sno'] ) ) {
                        return 'sno:' . strtolower( trim( (string) $student['sno'] ) );
                }

                if ( ! empty( $student['name'] ) ) {
                        $parts = array(
                                strtolower( trim( (string) $student['name'] ) ),
                                strtolower( trim( (string) ( $student['fname'] ?? '' ) ) ),
                                strtolower( trim( (string) ( $student['mname'] ?? '' ) ) ),
                        );

                        return 'name:' . implode( '|', $parts );
                }

                return '';
        }

        /**
         * Retrieves students for a specific exam/class/department combination.
         *
         * @param int         $exam_id           Exam identifier.
         * @param int         $exam_year_id      Exam year identifier.
         * @param int         $class_id          Class identifier.
         * @param string|null $department_value  Department identifier stored with the exam.
         *
         * @return array<int, array<string, mixed>> Student rows.
         */
        private function fetch_students_for_exam( int $exam_id, int $exam_year_id, int $class_id, $department_value ): array {
                $result_table = esc_sql( $this->prefix . 'astgdrmsys_student_result' );

                $conditions = array( 'exam_name = %d', 'exam_year = %d' );
                $params     = array( $exam_id, $exam_year_id );

                if ( $class_id > 0 ) {
                        $conditions[] = 'class = %d';
                        $params[]     = $class_id;
                }

                $department_value = is_string( $department_value ) ? trim( $department_value ) : '';

                if ( $department_value !== '' ) {
                        $conditions[] = 'department = %s';
                        $params[]     = $department_value;
                }

                $sql = sprintf(
                        'SELECT * FROM %s WHERE %s',
                        $result_table,
                        implode( ' AND ', $conditions )
                );

                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                return $this->wpdb->get_results( $this->wpdb->prepare( $sql, $params ), ARRAY_A );
        }

        /**
         * Retrieves marks for the provided student rows indexed by SID.
         *
         * @param array<int, array<string, mixed>> $students Student rows to inspect.
         *
         * @return array<int, array<string, mixed>> Map of SID => ['marks' => array, 'remark' => string].
         */
        private function fetch_marks_map( array $students ): array {
                if ( empty( $students ) ) {
                        return array();
                }

                $sids = array();
                foreach ( $students as $student ) {
                        if ( isset( $student['sid'] ) ) {
                                $sid = intval( $student['sid'] );

                                if ( $sid > 0 ) {
                                        $sids[] = $sid;
                                }
                        }
                }

                $sids = array_values( array_unique( $sids ) );

                if ( empty( $sids ) ) {
                        return array();
                }

                $marks_table = esc_sql( $this->prefix . 'astgdrmsys_mark' );
                $placeholders = implode( ',', array_fill( 0, count( $sids ), '%d' ) );

                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                $rows = $this->wpdb->get_results(
                        $this->wpdb->prepare(
                                "SELECT sid, marks, remark FROM {$marks_table} WHERE sid IN ($placeholders)",
                                $sids
                        ),
                        ARRAY_A
                );

                $map = array();

                foreach ( $rows as $row ) {
                        $sid   = intval( $row['sid'] );
                        $marks = maybe_unserialize( $row['marks'] );

                        if ( isset( $marks[0] ) && is_array( $marks[0] ) ) {
                                $marks = $marks[0];
                        }

                        if ( ! is_array( $marks ) ) {
                                $marks = array();
                        }

                        $map[ $sid ] = array(
                                'marks'  => $marks,
                                'remark' => isset( $row['remark'] ) ? (string) $row['remark'] : '',
                        );
                }

                return $map;
        }

        /**
         * Calculates averaged marks across the provided mark datasets.
         *
         * @param array<int, array<string, mixed>> $marks_sets Collection of marks arrays.
         *
         * @return array<string, mixed> Averaged mark structure suitable for persistence.
         */
        private function calculate_combined_marks( array $marks_sets ): array {
                $subject_totals = array();
                $fourth_subject = '';

                foreach ( $marks_sets as $marks ) {
                        if ( ! is_array( $marks ) || empty( $marks ) ) {
                                continue;
                        }

                        if ( isset( $marks['fourth_subject'] ) && $fourth_subject === '' ) {
                                $fourth_subject = trim( (string) $marks['fourth_subject'] );
                        }

                        foreach ( $marks as $subcode => $mark ) {
                                if ( 'fourth_subject' === $subcode || 'insub' === $subcode ) {
                                        continue;
                                }

                                $score = null;

                                if ( is_array( $mark ) ) {
                                        if ( ! empty( $mark['not_taken'] ) ) {
                                                continue;
                                        }

                                        if ( isset( $mark['total'] ) && $mark['total'] !== '' ) {
                                                $score = floatval( $mark['total'] );
                                        } else {
                                                $total = 0.0;
                                                $has_components = false;

                                                foreach ( array( 'practical', 'class', 'final' ) as $part ) {
                                                        if ( isset( $mark[ $part ] ) && $mark[ $part ] !== '' ) {
                                                                $total         += floatval( $mark[ $part ] );
                                                                $has_components = true;
                                                        }
                                                }

                                                if ( $has_components ) {
                                                        $score = $total;
                                                }
                                        }
                                } elseif ( is_numeric( $mark ) ) {
                                        $score = floatval( $mark );
                                }

                                if ( $score === null ) {
                                        continue;
                                }

                                if ( ! isset( $subject_totals[ $subcode ] ) ) {
                                        $subject_totals[ $subcode ] = array(
                                                'sum'   => 0.0,
                                                'count' => 0,
                                        );
                                }

                                $subject_totals[ $subcode ]['sum']   += $score;
                                $subject_totals[ $subcode ]['count'] += 1;
                        }
                }

                $combined = array();

                foreach ( $subject_totals as $subcode => $data ) {
                        if ( $data['count'] > 0 ) {
                                $average = round( $data['sum'] / $data['count'], 2 );

                                $combined[ $subcode ] = array(
                                        'practical' => 0,
                                        'class'     => 0,
                                        'final'     => $average,
                                        'total'     => $average,
                                );
                        }
                }

                if ( $fourth_subject !== '' ) {
                        $combined['fourth_subject'] = $fourth_subject;
                }

                return $combined;
        }

        /**
         * Generates combined exam results by averaging marks across source exams.
         *
         * @param int   $exam_id         Newly created combined exam ID.
         * @param array $components      Sanitized component IDs.
         * @param array $component_meta  Exam metadata keyed by exam ID.
         * @param array $exam_context    Context about the combined exam (class_id, department, exam_year_id).
         *
         * @return void
         */
        private function generate_combined_exam_results( int $exam_id, array $components, array $component_meta, array $exam_context ): void {
                $general_exam_id = isset( $components['general_exam'] ) ? intval( $components['general_exam'] ) : 0;
                $class_test_ids  = isset( $components['class_tests'] ) && is_array( $components['class_tests'] ) ? $components['class_tests'] : array();

                if ( $general_exam_id <= 0 || empty( $class_test_ids ) ) {
                        return;
                }

                try {
                        $general_meta = $component_meta[ $general_exam_id ] ?? null;

                        if ( ! $general_meta ) {
                                return;
                        }

                        $general_students = $this->fetch_students_for_exam(
                                $general_exam_id,
                                intval( $general_meta['exam_year_id'] ?? 0 ),
                                intval( $general_meta['class_id'] ?? 0 ),
                                $general_meta['department'] ?? ''
                        );

                        if ( empty( $general_students ) ) {
                                return;
                        }

                        $general_marks_map = $this->fetch_marks_map( $general_students );

                        if ( empty( $general_marks_map ) ) {
                                return;
                        }

                        $class_test_maps = array();

                        foreach ( $class_test_ids as $source_id ) {
                                $meta = $component_meta[ $source_id ] ?? null;

                                if ( ! $meta ) {
                                        continue;
                                }

                                $students = $this->fetch_students_for_exam(
                                        intval( $source_id ),
                                        intval( $meta['exam_year_id'] ?? 0 ),
                                        intval( $meta['class_id'] ?? 0 ),
                                        $meta['department'] ?? ''
                                );

                                if ( empty( $students ) ) {
                                        continue;
                                }

                                $marks_map = $this->fetch_marks_map( $students );

                                if ( empty( $marks_map ) ) {
                                        continue;
                                }

                                $indexed = array();

                                foreach ( $students as $student ) {
                                        $key = $this->build_student_index_key( $student );

                                        if ( $key === '' ) {
                                                continue;
                                        }

                                        $sid = isset( $student['sid'] ) ? intval( $student['sid'] ) : 0;

                                        if ( $sid > 0 && isset( $marks_map[ $sid ] ) ) {
                                                $indexed[ $key ] = array(
                                                        'row'   => $student,
                                                        'marks' => $marks_map[ $sid ]['marks'],
                                                );
                                        }
                                }

                                if ( ! empty( $indexed ) ) {
                                        $class_test_maps[] = $indexed;
                                }
                        }

                        if ( empty( $class_test_maps ) ) {
                                return;
                        }

                        $result_table = esc_sql( $this->prefix . 'astgdrmsys_student_result' );
                        $marks_table  = esc_sql( $this->prefix . 'astgdrmsys_mark' );

                        foreach ( $general_students as $student ) {
                                $sid = isset( $student['sid'] ) ? intval( $student['sid'] ) : 0;

                                if ( $sid <= 0 || ! isset( $general_marks_map[ $sid ] ) ) {
                                        continue;
                                }

                                $key = $this->build_student_index_key( $student );

                                if ( $key === '' ) {
                                        continue;
                                }

                                $marks_sets = array( $general_marks_map[ $sid ]['marks'] );

                                foreach ( $class_test_maps as $map ) {
                                        if ( isset( $map[ $key ] ) && ! empty( $map[ $key ]['marks'] ) ) {
                                                $marks_sets[] = $map[ $key ]['marks'];
                                        }
                                }

                                $combined_marks = $this->calculate_combined_marks( $marks_sets );

                                if ( empty( $combined_marks ) ) {
                                        continue;
                                }

                                $insert_data = array(
                                        'sno'           => $student['sno'] ?? '',
                                        'regno'         => $student['regno'] ?? '',
                                        'name'          => $student['name'] ?? '',
                                        'gender'        => $student['gender'] ?? '',
                                        'fname'         => $student['fname'] ?? '',
                                        'mname'         => $student['mname'] ?? '',
                                        'remark'        => $student['remark'] ?? '',
                                        'class'         => $student['class'] ?? ($exam_context['class_id'] ?? ''),
                                        'section'       => $student['section'] ?? '',
                                        'department'    => $student['department'] ?? ( $exam_context['department'] ?? '' ),
                                        'exam_name'     => $exam_id,
                                        'exam_year'     => intval( $exam_context['exam_year_id'] ?? 0 ),
                                        'is_absent'     => isset( $student['is_absent'] ) ? intval( $student['is_absent'] ) : 0,
                                        'student_image' => $student['student_image'] ?? '',
                                        'custom_fields' => $student['custom_fields'] ?? null,
                                );

                                $this->wpdb->insert( $result_table, $insert_data );

                                $new_sid = intval( $this->wpdb->insert_id );

                                if ( $new_sid > 0 ) {
                                        $this->wpdb->insert(
                                                $marks_table,
                                                array(
                                                        'sid'    => $new_sid,
                                                        'marks'  => serialize( $combined_marks ),
                                                        'remark' => $general_marks_map[ $sid ]['remark'] ?? '',
                                                )
                                        );
                                }
                        }
                } catch ( \Exception $e ) {
                        do_action( 'astgdrmsys_log_error', 'ASTDGRMSYS Error generating combined exam results: ' . $e->getMessage() );
                }
        }

        /**
         * Removes existing student results and marks for a combined exam prior to regeneration.
         *
         * @param int $exam_id Exam identifier whose derived results should be cleared.
         *
         * @return void
         */
        private function clear_combined_exam_results( int $exam_id ): void {
                try {
                        $result_table = esc_sql( $this->prefix . 'astgdrmsys_student_result' );
                        $marks_table  = esc_sql( $this->prefix . 'astgdrmsys_mark' );

                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                        $student_ids = $this->wpdb->get_col(
                                $this->wpdb->prepare(
                                        "SELECT sid FROM {$result_table} WHERE exam_name = %d",
                                        $exam_id
                                )
                        );

                        if ( ! empty( $student_ids ) ) {
                                $placeholders = implode( ',', array_fill( 0, count( $student_ids ), '%d' ) );

                                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                                $this->wpdb->query(
                                        $this->wpdb->prepare(
                                                "DELETE FROM {$marks_table} WHERE sid IN ($placeholders)",
                                                $student_ids
                                        )
                                );
                        }

                        $this->wpdb->delete( $result_table, array( 'exam_name' => $exam_id ) );
                } catch ( \Exception $e ) {
                        do_action( 'astgdrmsys_log_error', 'ASTDGRMSYS Error clearing combined exam results: ' . $e->getMessage() );
                }
        }

        /**
         * Renders the table markup used to collect subject full marks.
         *
         * @param array<int, array<string, mixed>> $subjects           Subject entries to render.
         * @param string                            $field_prefix       Form field name prefix.
         * @param string                            $table_id           ID attribute for the table element.
         * @param string                            $placeholder_message Message to display when no subjects are available.
         *
         * @return void
         */
        private function render_subjects_table( array $subjects, string $field_prefix, string $table_id, string $placeholder_message ): void {
                ?>
                <div class="table-responsive">
                        <table class="table table-bordered mb-0" id="<?php echo esc_attr( $table_id ); ?>">
                                <thead class="thead-light">
                                        <tr>
                                                <th><?php esc_html_e( 'Subject', 'result-management-system-for-institutions' ); ?></th>
                                                <th><?php esc_html_e( 'Subject Code', 'result-management-system-for-institutions' ); ?></th>
                                                <th><?php esc_html_e( 'Full Marks', 'result-management-system-for-institutions' ); ?></th>
                                        </tr>
                                </thead>
                                <tbody class="exam-subjects-body">
                                <?php if ( empty( $subjects ) ) : ?>
                                        <tr class="exam-subjects-placeholder">
                                                <td colspan="3"><?php echo esc_html( $placeholder_message ); ?></td>
                                        </tr>
                                <?php else : ?>
                                        <?php foreach ( $subjects as $subject ) :
                                                $subject_id = isset( $subject['id'] ) ? intval( $subject['id'] ) : 0;

                                                if ( $subject_id <= 0 ) {
                                                        continue;
                                                }

                                                $name      = isset( $subject['name'] ) ? $subject['name'] : '';
                                                $code      = isset( $subject['code'] ) ? $subject['code'] : '';
                                                $full_mark = isset( $subject['full_mark'] ) ? $subject['full_mark'] : 0;
                                                ?>
                                                <tr data-subject-id="<?php echo esc_attr( $subject_id ); ?>">
                                                        <td>
                                                                <?php echo esc_html( $name ); ?>
                                                                <input type="hidden" name="<?php echo esc_attr( $field_prefix . '[' . $subject_id . '][name]' ); ?>" value="<?php echo esc_attr( $name ); ?>">
                                                                <input type="hidden" name="<?php echo esc_attr( $field_prefix . '[' . $subject_id . '][code]' ); ?>" value="<?php echo esc_attr( $code ); ?>">
                                                        </td>
                                                        <td><?php echo esc_html( $code ); ?></td>
                                                        <td>
                                                                <input type="number" class="form-control" step="0.01" min="0" name="<?php echo esc_attr( $field_prefix . '[' . $subject_id . '][full_mark]' ); ?>" value="<?php echo esc_attr( $full_mark ); ?>">
                                                        </td>
                                                </tr>
                                        <?php endforeach; ?>
                                <?php endif; ?>
                                </tbody>
                        </table>
                </div>
                <?php
        }

	/**
	 * Handles the deletion of an exam name.
	 *
	 * This private function is responsible for managing the deletion process
	 * of an exam name within the plugin. It ensures that the necessary
	 * operations are performed to remove the exam name from the system.
	 *
	 * @return void
	 */
        private function handle_delete() {
                if ( ! ( isset( $_GET['delid'], $_GET['astgdrmsys_exam_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['astgdrmsys_exam_nonce'] ) ), 'astgdrmsys_exam_action' ) ) ) {
                        return;
                }

                $delid = absint( wp_unslash( $_GET['delid'] ) );

                if ( $delid <= 0 ) {
                        return;
                }

                $exam_category = $this->wpdb->get_var(
                        $this->wpdb->prepare(
                                "SELECT COALESCE(exam_category, 'general_exam') FROM {$this->prefix}astgdrmsys_exam_name WHERE id = %d",
                                $delid
                        )
                );

                if ( 'combined_result' === $exam_category ) {
                        $this->clear_combined_exam_results( $delid );
                }

                $deleted = $this->wpdb->delete(
                        $this->prefix . 'astgdrmsys_exam_name',
                        array( 'id' => $delid )
                );

                if ( $deleted ) {
                        wp_safe_redirect( add_query_arg( 'del', 'true', admin_url( 'admin.php?page=astgdrmsys-exam-name' ) ) );
                        exit;
                }
        }

	/**
	 * Handles the update process for the exam name.
	 *
	 * This function is responsible for managing the update logic
	 * related to exam names within the plugin.
	 *
	 * @return void
	 */
	private function handle_update() {
		// Check if the form is submitted and nonce is valid
		if ( ! isset( $_POST['astgdrmsys_exam_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['astgdrmsys_exam_nonce'] ) ), 'astgdrmsys_exam_action' ) ) {
			wp_die( esc_html__( 'Security check failed', 'result-management-system-for-institutions' ) );
		}

		// Check if the edit ID is set
		if ( ! isset( $_GET['editid'] ) ) {
			return;
		}
		// Sanitize and validate the input data
		$exam_year_raw   = isset( $_POST['updateexam_year'] ) ? sanitize_text_field( wp_unslash( $_POST['updateexam_year'] ) ) : '';
		$exam_year_array = explode( ',', $exam_year_raw );
                $publish_status  = isset( $_POST['update_result_publish_status'] ) ? 1 : 0;
                $fail_on_single_subject = isset( $_POST['update_fail_on_single_subject'] ) ? 1 : 0;
                $include_qr_code = isset( $_POST['update_include_qr_code'] ) ? 1 : 0;
                $restrict_non_logged_in = isset( $_POST['update_restrict_non_logged_in'] ) ? 1 : 0;
                $check_only_own_result  = isset( $_POST['update_check_only_own_result'] ) ? 1 : 0;
                $editid          = isset( $_GET['editid'] ) ? absint( wp_unslash( $_GET['editid'] ) ) : 0;

                $existing = $this->wpdb->get_row(
                        $this->wpdb->prepare(
                                "SELECT principal_signature, office_seal, COALESCE(exam_category, 'general_exam') AS exam_category FROM {$this->prefix}astgdrmsys_exam_name WHERE id = %d",
                                $editid
                        ),
                        ARRAY_A
                );

                $previous_category   = $existing['exam_category'] ?? 'general_exam';
                $principal_signature = $existing['principal_signature'] ?? '';
                if ( isset( $_FILES['update_principal_signature'] ) && ! empty( $_FILES['update_principal_signature']['name'] ) ) {
                        $upload_overrides = array( 'test_form' => false );
                        $movefile         = wp_handle_upload( $_FILES['update_principal_signature'], $upload_overrides );
                        if ( $movefile && ! isset( $movefile['error'] ) ) {
                                $principal_signature = esc_url_raw( $movefile['url'] );
                        }
                }

                $office_seal = $existing['office_seal'] ?? '';
                if ( isset( $_FILES['update_office_seal'] ) && ! empty( $_FILES['update_office_seal']['name'] ) ) {
                        $upload_overrides = array( 'test_form' => false );
                        $movefile         = wp_handle_upload( $_FILES['update_office_seal'], $upload_overrides );
                        if ( $movefile && ! isset( $movefile['error'] ) ) {
                                $office_seal = esc_url_raw( $movefile['url'] );
                        }
                }

                $category_keys    = array_keys( $this->get_exam_category_options() );
                $exam_category    = isset( $_POST['update_exam_category'] ) ? sanitize_text_field( wp_unslash( $_POST['update_exam_category'] ) ) : 'general_exam';
                $department_value = isset( $_POST['updatedepartment'] ) ? sanitize_text_field( wp_unslash( $_POST['updatedepartment'] ) ) : '';
                $class_name       = isset( $_POST['updateHiddenClassname'] ) ? sanitize_text_field( wp_unslash( $_POST['updateHiddenClassname'] ) ) : '';
                $class_id         = isset( $_POST['updateHiddenClassid'] ) ? intval( wp_unslash( $_POST['updateHiddenClassid'] ) ) : 0;

                $subject_input    = $_POST['update_exam_subjects'] ?? array();
                $subject_marks    = $this->prepare_subject_full_marks_input( $subject_input, $class_id, $department_value );

                if ( ! in_array( $exam_category, $category_keys, true ) ) {
                        $exam_category = 'general_exam';
                }

                $exam_type_value = isset( $_POST['update_exam_type'] ) ? sanitize_text_field( wp_unslash( $_POST['update_exam_type'] ) ) : 'single';

                $combined_components = array(
                        'class_tests'  => array(),
                        'general_exam' => 0,
                );
                $combined_meta       = array();

                if ( 'combined_result' === $exam_category ) {
                        $raw_components = $this->prepare_combined_component_input(
                                $_POST['update_combined_class_tests'] ?? array(),
                                $_POST['update_combined_general_exam'] ?? ''
                        );

                        $validation = $this->validate_combined_component_exams( $raw_components, $class_id, $department_value, $editid );
                        $combined_components = $validation['components'];
                        $combined_meta       = $validation['records'];
                }

                $assessment_display = $this->prepare_assessment_display_input(
                        array(
                                'first_assessment_display_name'  => $_POST['update_first_assessment_display_name'] ?? '',
                                'second_assessment_display_name' => $_POST['update_second_assessment_display_name'] ?? '',
                                'third_assessment_display_name'  => $_POST['update_third_assessment_display_name'] ?? '',
                                'total_display_name'             => $_POST['update_total_display_name'] ?? '',
                        ),
                        $exam_type_value
                );

                $data = array(
                        'exam_name'             => isset( $_POST['updateexam_name'] ) ? sanitize_text_field( wp_unslash( $_POST['updateexam_name'] ) ) : '',
                        'department'            => $department_value,
                        'class'                 => $class_name,
                        'class_id'              => $class_id,
                        'exam_year'             => isset( $exam_year_array[0] ) ? trim( $exam_year_array[0] ) : '',
                        'exam_year_id'          => isset( $exam_year_array[1] ) ? trim( $exam_year_array[1] ) : '',
                        'exam_type'             => $exam_type_value,
                        'exam_category'         => $exam_category,
                        'result_title'          => isset( $_POST['update_result_title'] ) ? sanitize_text_field( wp_unslash( $_POST['update_result_title'] ) ) : '',
                        'result_subtitle'       => isset( $_POST['update_result_subtitle'] ) ? sanitize_text_field( wp_unslash( $_POST['update_result_subtitle'] ) ) : '',
                        'result_footer_text'    => isset( $_POST['update_result_footer_text'] ) ? sanitize_text_field( wp_unslash( $_POST['update_result_footer_text'] ) ) : '',
                        'principal_signature'   => $principal_signature,
                        'office_seal'           => $office_seal,
                        'include_qr_code'       => $include_qr_code,
                        'result_publish_status' => $publish_status,
                        'fail_on_single_subject'=> $fail_on_single_subject,
                        'restrict_non_logged_in'=> $restrict_non_logged_in,
                        'check_only_own_result' => $check_only_own_result,
			'custom_field_name1'    => isset( $_POST['update_custom_field_name1'] ) ? sanitize_text_field( wp_unslash( $_POST['update_custom_field_name1'] ) ) : '',
			'custom_field_value1'   => isset( $_POST['update_custom_field_value1'] ) ? sanitize_text_field( wp_unslash( $_POST['update_custom_field_value1'] ) ) : '',
                        'custom_field_name2'    => isset( $_POST['update_custom_field_name2'] ) ? sanitize_text_field( wp_unslash( $_POST['update_custom_field_name2'] ) ) : '',
                        'custom_field_value2'   => isset( $_POST['update_custom_field_value2'] ) ? sanitize_text_field( wp_unslash( $_POST['update_custom_field_value2'] ) ) : '',
                        'custom_field_name3'    => isset( $_POST['update_custom_field_name3'] ) ? sanitize_text_field( wp_unslash( $_POST['update_custom_field_name3'] ) ) : '',
                        'custom_field_value3'   => isset( $_POST['update_custom_field_value3'] ) ? sanitize_text_field( wp_unslash( $_POST['update_custom_field_value3'] ) ) : '',
                        'subject_full_marks'    => maybe_serialize( $subject_marks ),
                        'first_assessment_display_name'  => $assessment_display['first_assessment_display_name'] ?? '',
                        'second_assessment_display_name' => $assessment_display['second_assessment_display_name'] ?? '',
                        'third_assessment_display_name'  => $assessment_display['third_assessment_display_name'] ?? '',
                        'total_display_name'             => $assessment_display['total_display_name'] ?? '',
                        'combined_component_exams' => 'combined_result' === $exam_category ? maybe_serialize( $combined_components ) : null,
                );

                // sql query to update
                $updated = $this->wpdb->update(
                        $this->prefix . 'astgdrmsys_exam_name',
			$data,
			array( 'id' => $editid )
		);

		// redirecting url to show message
                if ( false !== $updated ) {
                        if ( 'combined_result' === $exam_category ) {
                                $this->clear_combined_exam_results( $editid );
                                $this->generate_combined_exam_results(
                                        $editid,
                                        $combined_components,
                                        $combined_meta,
                                        array(
                                                'class_id'     => $class_id,
                                                'department'   => $department_value,
                                                'exam_year_id' => intval( $data['exam_year_id'] ?? 0 ),
                                        )
                                );
                        } elseif ( 'combined_result' === $previous_category ) {
                                $this->clear_combined_exam_results( $editid );
                        }

                        wp_safe_redirect( add_query_arg( 'edit', 'true', admin_url( 'admin.php?page=astgdrmsys-exam-name' ) ) );
                        exit;
                }
        }

	/**
	 * Handles the publishing of an exam name.
	 *
	 * This function is responsible for managing the publishing process
	 * of an exam name within the plugin. It ensures that the necessary
	 * operations are performed to publish the exam name.
	 *
	 * @return void
	 */
	private function handle_publish() {
		if ( isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD'] === 'POST' ) {
			// Nonce check and sanitization
			if ( ! isset( $_POST['astgdrmsys_exam_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['astgdrmsys_exam_nonce'] ) ), 'astgdrmsys_exam_action' ) ) {
				wp_die( esc_html__( 'Invalid request. Please refresh and try again.', 'result-management-system-for-institutions' ) );
			}
		}

		// Check if the publish ID is set
		$pubid = isset( $_GET['pubid'] ) ? absint( wp_unslash( $_GET['pubid'] ) ) : 0;

		$data = array(
			'result_publish_status' => 1,
		);

		$updated = $this->wpdb->update(
			$this->prefix . 'astgdrmsys_exam_name',
			$data,
			array( 'id' => $pubid )
		);
		
		if ( $updated ) {
			$this->compute_ranks_for_exam( $pubid );
			wp_safe_redirect( add_query_arg( 'publish', 'true', admin_url( 'admin.php?page=astgdrmsys-exam-name' ) ) );
			exit;
		}
	}
	
	/**
	 * Compute and store student ranks for a published exam.
	 *
	 * @param int $exam_id Exam identifier.
	 * @return void
	 */
	private function compute_ranks_for_exam( $exam_id ) {
		// Fetch exam details
		$exam = $this->wpdb->get_row(
			$this->wpdb->prepare(
				"SELECT class_id, exam_year_id FROM {$this->prefix}astgdrmsys_exam_name WHERE id = %d",
				$exam_id
			),
			ARRAY_A
		);
		
		if ( empty( $exam ) ) {
			return;
		}

		$class_id       = intval( $exam['class_id'] );
		$exam_year_id = intval( $exam['exam_year_id'] );

		$result_table = $this->prefix . 'astgdrmsys_student_result';
		$marks_table  = $this->prefix . 'astgdrmsys_mark';

		// Get all students for this exam
		$students = $this->wpdb->get_results(
			$this->wpdb->prepare(
				"SELECT sid FROM {$result_table} WHERE class = %d AND exam_name = %d AND exam_year = %d",
				$class_id,
				$exam_id,
				$exam_year_id
			),
			ARRAY_A
		);

		if ( empty( $students ) ) {
			return;
		}

		$totals = array();
		foreach ( $students as $student ) {
			$sid = intval( $student['sid'] );
			$serialized = $this->wpdb->get_var(
				$this->wpdb->prepare(
					"SELECT marks FROM {$marks_table} WHERE sid = %d",
					$sid
				)
			);

			$marks = maybe_unserialize( $serialized );
			if ( isset( $marks[0] ) && is_array( $marks[0] ) ) {
				$marks = $marks[0];
			}

			$total = 0;
			if ( is_array( $marks ) ) {
				foreach ( $marks as $subcode => $mark ) {
					if ( in_array( $subcode, array( 'fourth_subject', 'insub' ), true ) ) {
						continue;
					}
					
					if ( is_array( $mark ) ) {
						if ( isset( $mark['total'] ) && is_numeric( $mark['total'] ) ) {
							$total += floatval( $mark['total'] );
						} else {
							foreach ( $mark as $part ) {
								if ( is_numeric( $part ) ) {
									$total += floatval( $part );
								}
							}
						}
					} elseif ( is_numeric( $mark ) ) {
						$total += floatval( $mark );
					}
				}
			}

			$totals[ $sid ] = $total;
		}

                arsort( $totals );
                $rank       = 0;
                $prev_total = null;
                foreach ( $totals as $sid => $total ) {
                        if ( null === $prev_total || $total < $prev_total ) {
				$rank++;
                        }
                        $prev_total = $total;
                        $this->wpdb->update( $result_table, array( 'rank' => $rank ), array( 'sid' => $sid ) );
                }
        }

        /**
         * Determine the appropriate source exam to seed students from.
         *
         * @param int    $requested_exam_id Preferred exam identifier supplied by the admin.
         * @param int    $class_id          Class identifier tied to the new exam.
         * @param string $department        Department identifier for the new exam.
         * @param int    $exam_year_id      Exam year identifier for the new exam.
         * @param int    $new_exam_id       Newly created exam identifier.
         *
         * @return int Source exam identifier or 0 when none can be resolved.
         */
        private function resolve_seed_source_exam_id( int $requested_exam_id, int $class_id, string $department, int $exam_year_id, int $new_exam_id ): int {
                $exam_table = esc_sql( $this->prefix . 'astgdrmsys_exam_name' );

                if ( $requested_exam_id > 0 ) {
                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
                        $exists = $this->wpdb->get_var(
                                $this->wpdb->prepare(
                                        "SELECT COUNT(1) FROM {$exam_table} WHERE id = %d",
                                        $requested_exam_id
                                )
                        );

                        if ( $exists ) {
                                return $requested_exam_id;
                        }
                }

                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
                $latest_exam_id = $this->wpdb->get_var(
                        $this->wpdb->prepare(
                                "SELECT id FROM {$exam_table} WHERE class_id = %d AND department = %s AND exam_year_id = %d AND id <> %d ORDER BY id DESC LIMIT 1",
                                $class_id,
                                $department,
                                $exam_year_id,
                                $new_exam_id
                        )
                );

                return intval( $latest_exam_id );
        }

        /**
         * Copy students from an existing exam into a newly created exam.
         *
         * @param array<string, mixed> $context Context data for seeding.
         *
         * @return array<string, mixed> Result data including status and counters.
         */
        private function seed_exam_students( array $context ): array {
                $defaults = array(
                        'new_exam_id'    => 0,
                        'new_exam_name'  => '',
                        'new_exam_year'  => '',
                        'class_id'       => 0,
                        'department'     => '',
                        'exam_year_id'   => 0,
                        'source_exam_id' => 0,
                );

                $context = wp_parse_args( $context, $defaults );

                $new_exam_id  = intval( $context['new_exam_id'] );
                $class_id     = intval( $context['class_id'] );
                $department   = sanitize_text_field( (string) $context['department'] );
                $exam_year_id = intval( $context['exam_year_id'] );

                if ( $new_exam_id <= 0 || $class_id <= 0 || $department === '' ) {
                        return array(
                                'status' => 'error',
                                'reason' => 'invalid_context',
                        );
                }

                $source_exam_id = $this->resolve_seed_source_exam_id(
                        intval( $context['source_exam_id'] ),
                        $class_id,
                        $department,
                        $exam_year_id,
                        $new_exam_id
                );

                if ( $source_exam_id <= 0 ) {
                        return array(
                                'status' => 'warning',
                                'reason' => 'no_source_exam',
                        );
                }

                $result_table = esc_sql( $this->prefix . 'astgdrmsys_student_result' );
                $marks_table  = esc_sql( $this->prefix . 'astgdrmsys_mark' );

                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
                $students = $this->wpdb->get_results(
                        $this->wpdb->prepare(
                                "SELECT sid, sno, regno, name, gender, fname, mname, section, student_image, custom_fields FROM {$result_table} WHERE exam_name = %d AND class = %d AND department = %s AND exam_year = %d",
                                $source_exam_id,
                                $class_id,
                                $department,
                                $exam_year_id
                        ),
                        ARRAY_A
                );

                if ( empty( $students ) ) {
                        return array(
                                'status' => 'warning',
                                'reason' => 'no_students',
                        );
                }

                $marks_map = $this->fetch_marks_map( $students );

                $inserted = 0;
                $skipped  = 0;

                foreach ( $students as $student ) {
                        $sno   = $student['sno'] ?? '';
                        $regno = $student['regno'] ?? '';
                        $sid   = isset( $student['sid'] ) ? intval( $student['sid'] ) : 0;

                        if ( $sno === '' && $regno === '' ) {
                                $skipped++;
                                continue;
                        }

                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
                        $exists = $this->wpdb->get_var(
                                $this->wpdb->prepare(
                                        "SELECT COUNT(*) FROM {$result_table} WHERE exam_name = %d AND exam_year = %d AND class = %d AND department = %s AND (sno = %s OR regno = %s)",
                                        $new_exam_id,
                                        $exam_year_id,
                                        $class_id,
                                        $department,
                                        $sno,
                                        $regno
                                )
                        );

                        if ( $exists ) {
                                $skipped++;
                                continue;
                        }

                        $insert_data = array(
                                'sno'           => $sno,
                                'regno'         => $regno,
                                'name'          => $student['name'] ?? '',
                                'gender'        => $student['gender'] ?? '',
                                'fname'         => $student['fname'] ?? '',
                                'mname'         => $student['mname'] ?? '',
                                'remark'        => '',
                                'class'         => $class_id,
                                'section'       => $student['section'] ?? '',
                                'department'    => $department,
                                'exam_name'     => $new_exam_id,
                                'exam_year'     => $exam_year_id,
                                'is_absent'     => 0,
                                'student_image' => $student['student_image'] ?? '',
                                'custom_fields' => $student['custom_fields'] ?? null,
                        );

                        $this->wpdb->insert( $result_table, $insert_data );

                        $new_sid = intval( $this->wpdb->insert_id );

                        if ( $new_sid > 0 ) {
                                $marks_source   = $marks_map[ $sid ]['marks'] ?? array();
                                $seeded_marks   = $this->build_seed_marks_template( $marks_source );
                                $serialized_map = maybe_serialize( $seeded_marks );

                                $this->wpdb->insert(
                                        $marks_table,
                                        array(
                                                'sid'    => $new_sid,
                                                'marks'  => $serialized_map,
                                                'remark' => '',
                                        )
                                );

                                $inserted++;
                        } else {
                                $skipped++;
                        }
                }

                return array(
                        'status'         => 'success',
                        'inserted'       => $inserted,
                        'skipped'        => $skipped,
                        'source_exam_id' => $source_exam_id,
                );
        }

        /**
         * Build a marks array for seeded students that preserves fourth-subject and not-taken subjects.
         *
         * @param array<string, mixed> $marks Raw marks from the source exam.
         *
         * @return array<string, mixed> Marks data suitable for insertion for the new exam.
         */
        private function build_seed_marks_template( array $marks ): array {
                if ( isset( $marks[0] ) && is_array( $marks[0] ) ) {
                        $marks = $marks[0];
                }

                if ( ! is_array( $marks ) ) {
                        return array();
                }

                $template = array();

                if ( isset( $marks['fourth_subject'] ) && $marks['fourth_subject'] !== '' ) {
                        $template['fourth_subject'] = $marks['fourth_subject'];
                }

                foreach ( $marks as $subcode => $mark ) {
                        if ( in_array( $subcode, array( 'fourth_subject', 'insub' ), true ) ) {
                                continue;
                        }

                        if ( is_array( $mark ) && ! empty( $mark['not_taken'] ) ) {
                                $template[ $subcode ] = array(
                                        'practical' => 0,
                                        'class'     => 0,
                                        'final'     => 0,
                                        'total'     => 0,
                                        'not_taken' => 1,
                                );
                        }
                }

                return $template;
        }

        /**
         * Assigns active student database enrollments to a newly created exam.
         *
         * @param array<string, mixed> $context Exam context.
         *
         * @return array<string, mixed> Assignment result.
         */
        private function count_assignable_students_from_database( array $context ): int {
                $defaults = array(
                        'class_id'     => 0,
                        'department'   => '',
                        'exam_year_id' => 0,
                        'section_ids'  => array(),
                );

                $context = wp_parse_args( $context, $defaults );

                $class_id      = intval( $context['class_id'] );
                $exam_year_id  = intval( $context['exam_year_id'] );
                $department_id = $this->resolve_department_id_for_student_database( (string) $context['department'], $class_id );
                $section_ids   = array();

                if ( is_array( $context['section_ids'] ) ) {
                        foreach ( $context['section_ids'] as $section_id ) {
                                $section_id = intval( $section_id );

                                if ( $section_id > 0 ) {
                                        $section_ids[] = $section_id;
                                }
                        }
                }

                $section_ids = array_values( array_unique( $section_ids ) );

                if ( $class_id <= 0 || $department_id <= 0 || $exam_year_id <= 0 ) {
                        return 0;
                }

                $students_table    = esc_sql( $this->prefix . 'astgdrmsys_students' );
                $enrollments_table = esc_sql( $this->prefix . 'astgdrmsys_student_enrollments' );
                $where_sql         = 'WHERE e.exam_year_id = %d
                                        AND e.class_id = %d
                                        AND e.department_id = %d
                                        AND e.status = %s
                                        AND s.status = %s';
                $query_params      = array(
                        $exam_year_id,
                        $class_id,
                        $department_id,
                        'active',
                        'active',
                );

                if ( ! empty( $section_ids ) ) {
                        $section_placeholders = implode( ',', array_fill( 0, count( $section_ids ), '%d' ) );
                        $where_sql           .= " AND e.section_id IN ($section_placeholders)";
                        $query_params         = array_merge( $query_params, $section_ids );
                }

                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
                return intval(
                        $this->wpdb->get_var(
                                $this->wpdb->prepare(
                                        "SELECT COUNT(DISTINCT s.id)
                                        FROM {$enrollments_table} e
                                        INNER JOIN {$students_table} s ON s.id = e.student_id
                                        {$where_sql}",
                                        $query_params
                                )
                        )
                );
        }

        private function assign_exam_students_from_database( array $context ): array {
                $defaults = array(
                        'new_exam_id'  => 0,
                        'class_id'     => 0,
                        'department'   => '',
                        'exam_year_id' => 0,
                        'section_ids'  => array(),
                );

                $context = wp_parse_args( $context, $defaults );

                $new_exam_id  = intval( $context['new_exam_id'] );
                $class_id     = intval( $context['class_id'] );
                $exam_year_id = intval( $context['exam_year_id'] );
                $department_id = $this->resolve_department_id_for_student_database( (string) $context['department'], $class_id );
                $section_ids  = array();

                if ( is_array( $context['section_ids'] ) ) {
                        foreach ( $context['section_ids'] as $section_id ) {
                                $section_id = intval( $section_id );

                                if ( $section_id > 0 ) {
                                        $section_ids[] = $section_id;
                                }
                        }
                }

                $section_ids = array_values( array_unique( $section_ids ) );

                if ( $new_exam_id <= 0 || $class_id <= 0 || $department_id <= 0 || $exam_year_id <= 0 ) {
                        return array(
                                'status' => 'error',
                                'reason' => 'invalid_context',
                        );
                }

                $students_table    = esc_sql( $this->prefix . 'astgdrmsys_students' );
                $enrollments_table = esc_sql( $this->prefix . 'astgdrmsys_student_enrollments' );
                $result_table      = esc_sql( $this->prefix . 'astgdrmsys_student_result' );
                $marks_table       = esc_sql( $this->prefix . 'astgdrmsys_mark' );
                $where_sql         = 'WHERE e.exam_year_id = %d
                                        AND e.class_id = %d
                                        AND e.department_id = %d
                                        AND e.status = %s
                                        AND s.status = %s';
                $query_params      = array(
                        $exam_year_id,
                        $class_id,
                        $department_id,
                        'active',
                        'active',
                );

                if ( ! empty( $section_ids ) ) {
                        $section_placeholders = implode( ',', array_fill( 0, count( $section_ids ), '%d' ) );
                        $where_sql           .= " AND e.section_id IN ($section_placeholders)";
                        $query_params         = array_merge( $query_params, $section_ids );
                }

                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
                $enrollments = $this->wpdb->get_results(
                        $this->wpdb->prepare(
                                "SELECT e.id AS enrollment_id, e.roll_no, e.exam_year_id, e.class_id, e.department_id, e.section_id, s.id AS student_id, s.regno, s.name, s.gender, s.fname, s.mname, s.student_image, s.custom_fields
                                FROM {$enrollments_table} e
                                INNER JOIN {$students_table} s ON s.id = e.student_id
                                {$where_sql}
                                ORDER BY CAST(e.roll_no AS UNSIGNED), s.name ASC",
                                $query_params
                        ),
                        ARRAY_A
                );

                if ( empty( $enrollments ) ) {
                        return array(
                                'status' => 'warning',
                                'reason' => 'no_students',
                        );
                }

                $inserted = 0;
                $skipped  = 0;

                foreach ( $enrollments as $enrollment ) {
                        $student_id = isset( $enrollment['student_id'] ) ? intval( $enrollment['student_id'] ) : 0;

                        if ( $student_id <= 0 ) {
                                $skipped++;
                                continue;
                        }

                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
                        $exists = $this->wpdb->get_var(
                                $this->wpdb->prepare(
                                        "SELECT COUNT(*) FROM {$result_table} WHERE exam_name = %d AND student_id = %d",
                                        $new_exam_id,
                                        $student_id
                                )
                        );

                        if ( $exists ) {
                                $skipped++;
                                continue;
                        }

                        $insert_data = array(
                                'student_id'    => $student_id,
                                'enrollment_id' => intval( $enrollment['enrollment_id'] ),
                                'sno'           => $enrollment['roll_no'] ?? '',
                                'regno'         => $enrollment['regno'] ?? '',
                                'name'          => $enrollment['name'] ?? '',
                                'gender'        => $enrollment['gender'] ?? '',
                                'fname'         => $enrollment['fname'] ?? '',
                                'mname'         => $enrollment['mname'] ?? '',
                                'remark'        => '',
                                'class'         => $class_id,
                                'section'       => $enrollment['section_id'] ?? '',
                                'department'    => $department_id,
                                'exam_name'     => $new_exam_id,
                                'exam_year'     => $exam_year_id,
                                'is_absent'     => 0,
                                'student_image' => $enrollment['student_image'] ?? '',
                                'custom_fields' => $enrollment['custom_fields'] ?? null,
                        );

                        $this->wpdb->insert( $result_table, $insert_data );
                        $new_sid = intval( $this->wpdb->insert_id );

                        if ( $new_sid > 0 ) {
                                $this->wpdb->insert(
                                        $marks_table,
                                        array(
                                                'sid'    => $new_sid,
                                                'marks'  => maybe_serialize( array() ),
                                                'remark' => '',
                                        )
                                );
                                $inserted++;
                        } else {
                                $skipped++;
                        }
                }

                return array(
                        'status'   => 'success',
                        'inserted' => $inserted,
                        'skipped'  => $skipped,
                );
        }

        /**
         * Resolves an exam department value to the student database department id.
         */
        private function resolve_department_id_for_student_database( string $department_value, int $class_id ): int {
                $department_value = trim( $department_value );

                if ( $department_value === '' ) {
                        return 0;
                }

                if ( is_numeric( $department_value ) ) {
                        return intval( $department_value );
                }

                $department_table = esc_sql( $this->prefix . 'astgdrmsys_department' );

                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
                return intval(
                        $this->wpdb->get_var(
                                $this->wpdb->prepare(
                                        "SELECT id FROM {$department_table} WHERE LOWER(TRIM(department)) = LOWER(TRIM(%s)) ORDER BY id ASC LIMIT 1",
                                        $department_value
                                )
                        )
                );
        }

	/**
	 * Handles the addition of a new exam name.
         *
         * This function processes the form submission for adding a new exam name.
	 * It validates the input data, saves the new exam name to the database,
	 * and provides feedback to the user.
	 *
	 * @return void
	 */
	private function handle_add() {
		if ( ! isset( $_POST['astgdrmsys_exam_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['astgdrmsys_exam_nonce'] ) ), 'astgdrmsys_exam_action' ) ) {
			wp_die( esc_html__( 'Security check failed', 'result-management-system-for-institutions' ) );
		}

		// $exam_array     = isset( $_POST['exam_year'] ) ? explode( '-', sanitize_text_field( wp_unslash( $_POST['exam_year'] ) ) ) : array( '', 0 );
		if ( isset( $_POST['exam_year'] ) ) {
			$raw_exam_year = sanitize_text_field( wp_unslash( $_POST['exam_year'] ) );
			$last_dash     = strrpos( $raw_exam_year, '-' );
			
			if ( $last_dash !== false ) {
				$exam_year    = substr( $raw_exam_year, 0, $last_dash ); // everything before last dash
				$exam_year_id = substr( $raw_exam_year, $last_dash + 1 ); // after last dash
			} else {
				$exam_year    = $raw_exam_year;
				$exam_year_id = 0;
			}
		} else {
			$exam_year    = '';
			$exam_year_id = 0;
		}
                $department_value    = isset( $_POST['departmentadd'] ) ? sanitize_text_field( wp_unslash( $_POST['departmentadd'] ) ) : '';
                $class_name          = isset( $_POST['hiddenclassname'] ) ? sanitize_text_field( wp_unslash( $_POST['hiddenclassname'] ) ) : '';
                $class_id            = isset( $_POST['hiddenclassid'] ) ? intval( wp_unslash( $_POST['hiddenclassid'] ) ) : 0;

                $subject_input       = $_POST['exam_subjects'] ?? array();
                $subject_marks       = $this->prepare_subject_full_marks_input( $subject_input, $class_id, $department_value );
                $publish_status      = isset( $_POST['result_publish_status'] ) ? 1 : 0;
                $failed_on_single_subject = isset($_POST['fail_on_single_subject']) ? 1 : 0;
                $include_qr_code = isset($_POST['include_qr_code']) ? 1 : 0;
                $restrict_non_logged_in = isset($_POST['restrict_non_logged_in']) ? 1 : 0;
                $check_only_own_result  = isset($_POST['check_only_own_result']) ? 1 : 0;
                $auto_seed_students     = isset( $_POST['auto_seed_students'] );
                $filter_by_section      = $auto_seed_students && isset( $_POST['filter_by_section'] );
                $section_ids            = array();
                $category_keys          = array_keys( $this->get_exam_category_options() );
                $exam_category          = isset( $_POST['exam_category'] ) ? sanitize_text_field( wp_unslash( $_POST['exam_category'] ) ) : 'general_exam';

                if ( ! in_array( $exam_category, $category_keys, true ) ) {
                        $exam_category = 'general_exam';
                }

                if ( $filter_by_section ) {
                        $raw_section_ids = isset( $_POST['section_filter'] ) && is_array( $_POST['section_filter'] ) ? wp_unslash( $_POST['section_filter'] ) : array();

                        foreach ( $raw_section_ids as $section_id ) {
                                $section_id = intval( $section_id );

                                if ( $section_id > 0 ) {
                                        $section_ids[] = $section_id;
                                }
                        }

                        $section_ids = array_values( array_unique( $section_ids ) );

                        if ( empty( $section_ids ) ) {
                                wp_die( esc_html__( 'Please select at least one section or turn off section filtering.', 'result-management-system-for-institutions' ) );
                        }
                }

                if ( $auto_seed_students && 'combined_result' !== $exam_category ) {
                        $assignable_students = $this->count_assignable_students_from_database(
                                array(
                                        'class_id'     => $class_id,
                                        'department'   => $department_value,
                                        'exam_year_id' => intval( $exam_year_id ),
                                        'section_ids'  => $section_ids,
                                )
                        );

                        if ( $assignable_students <= 0 ) {
                                wp_safe_redirect(
                                        add_query_arg(
                                                array(
                                                        'save_error' => 'no_students',
                                                ),
                                                admin_url( 'admin.php?page=astgdrmsys-exam-name' )
                                        )
                                );
                                exit;
                        }
                }

                $principal_signature = '';
                if ( isset( $_FILES['principal_signature'] ) && ! empty( $_FILES['principal_signature']['name'] ) ) {
                        $upload_overrides = array( 'test_form' => false );
                        $movefile         = wp_handle_upload( $_FILES['principal_signature'], $upload_overrides );
                        if ( $movefile && ! isset( $movefile['error'] ) ) {
                                $principal_signature = esc_url_raw( $movefile['url'] );
                        }
                }

                $office_seal = '';
                if ( isset( $_FILES['office_seal'] ) && ! empty( $_FILES['office_seal']['name'] ) ) {
                        $upload_overrides = array( 'test_form' => false );
                        $movefile         = wp_handle_upload( $_FILES['office_seal'], $upload_overrides );
                        if ( $movefile && ! isset( $movefile['error'] ) ) {
                                $office_seal = esc_url_raw( $movefile['url'] );
                        }
                }

                $exam_type_value = isset( $_POST['exam_type'] ) ? sanitize_text_field( wp_unslash( $_POST['exam_type'] ) ) : 'single';

                $combined_components = array(
                        'class_tests'  => array(),
                        'general_exam' => 0,
                );
                $combined_meta       = array();

                if ( 'combined_result' === $exam_category ) {
                        $raw_components = $this->prepare_combined_component_input(
                                $_POST['combined_class_tests'] ?? array(),
                                $_POST['combined_general_exam'] ?? ''
                        );

                        $validation = $this->validate_combined_component_exams( $raw_components, $class_id, $department_value );
                        $combined_components = $validation['components'];
                        $combined_meta       = $validation['records'];
                }

                $assessment_display = $this->prepare_assessment_display_input(
                        array(
                                'first_assessment_display_name'  => $_POST['first_assessment_display_name'] ?? '',
                                'second_assessment_display_name' => $_POST['second_assessment_display_name'] ?? '',
                                'third_assessment_display_name'  => $_POST['third_assessment_display_name'] ?? '',
                                'total_display_name'             => $_POST['total_display_name'] ?? '',
                        ),
                        $exam_type_value
                );

                $data = array(
                        'exam_name'             => isset( $_POST['exam_name'] ) ? sanitize_text_field( wp_unslash( $_POST['exam_name'] ) ) : '',
                        'department'            => $department_value,
                        'class'                 => $class_name,
                        'class_id'              => $class_id,
                        'exam_year'    => $exam_year,
                        'exam_year_id' => intval( $exam_year_id ),
                        // 'exam_year'             => trim( $exam_array[0] ),
                        // 'exam_year_id'          => isset( $_POST['hiddenExamYearId'] ) ? intval( wp_unslash( $_POST['hiddenExamYearId'] ) ) : 0,
                        'exam_type'             => $exam_type_value,
                        'exam_category'         => $exam_category,
                        'result_title'          => isset( $_POST['result_title'] ) ? sanitize_text_field( wp_unslash( $_POST['result_title'] ) ) : '',
                        'result_subtitle'       => isset( $_POST['result_subtitle'] ) ? sanitize_text_field( wp_unslash( $_POST['result_subtitle'] ) ) : '',
                        'result_footer_text'    => isset( $_POST['result_footer_text'] ) ? sanitize_text_field( wp_unslash( $_POST['result_footer_text'] ) ) : '',
                        'principal_signature'   => $principal_signature,
                        'office_seal'           => $office_seal,
                        'include_qr_code'       => $include_qr_code,
                        'result_publish_status' => $publish_status,
                        'fail_on_single_subject'=> $failed_on_single_subject,
                        'restrict_non_logged_in'=> $restrict_non_logged_in,
                        'check_only_own_result' => $check_only_own_result,
                        'first_assessment_display_name'  => $assessment_display['first_assessment_display_name'] ?? '',
                        'second_assessment_display_name' => $assessment_display['second_assessment_display_name'] ?? '',
                        'third_assessment_display_name'  => $assessment_display['third_assessment_display_name'] ?? '',
                        'total_display_name'             => $assessment_display['total_display_name'] ?? '',
                        'subject_full_marks'    => maybe_serialize( $subject_marks ),
                        'combined_component_exams' => 'combined_result' === $exam_category ? maybe_serialize( $combined_components ) : null,
                        'custom_field_name1'    => isset( $_POST['custom_field_name1'] ) ? sanitize_text_field( wp_unslash( $_POST['custom_field_name1'] ) ) : '',
                        'custom_field_value1'   => isset( $_POST['custom_field_value1'] ) ? sanitize_text_field( wp_unslash( $_POST['custom_field_value1'] ) ) : '',
                        'custom_field_name2'    => isset( $_POST['custom_field_name2'] ) ? sanitize_text_field( wp_unslash( $_POST['custom_field_name2'] ) ) : '',
                        'custom_field_value2'   => isset( $_POST['custom_field_value2'] ) ? sanitize_text_field( wp_unslash( $_POST['custom_field_value2'] ) ) : '',
                        'custom_field_name3'    => isset( $_POST['custom_field_name3'] ) ? sanitize_text_field( wp_unslash( $_POST['custom_field_name3'] ) ) : '',
			'custom_field_value3'   => isset( $_POST['custom_field_value3'] ) ? sanitize_text_field( wp_unslash( $_POST['custom_field_value3'] ) ) : '',
		);

                $inserted = $this->wpdb->insert(
                        $this->prefix . 'astgdrmsys_exam_name',
                        $data
                );

                if ( $inserted ) {
                        $new_exam_id = intval( $this->wpdb->insert_id );
                        $seed_result = null;

                        if ( 'combined_result' === $exam_category && ! empty( $combined_components['class_tests'] ) ) {
                                $this->generate_combined_exam_results(
                                        $new_exam_id,
                                        $combined_components,
                                        $combined_meta,
                                        array(
                                                'class_id'     => $class_id,
                                                'department'   => $department_value,
                                                'exam_year_id' => intval( $exam_year_id ),
                                        )
                                );
                        } elseif ( $auto_seed_students ) {
                                $seed_result = $this->assign_exam_students_from_database(
                                        array(
                                                'new_exam_id'    => $new_exam_id,
                                                'class_id'       => $class_id,
                                                'department'     => $department_value,
                                                'exam_year_id'   => intval( $exam_year_id ),
                                                'section_ids'    => $section_ids,
                                        )
                                );
                        }

                        $query_args = array( 'add' => 'true' );

                        if ( is_array( $seed_result ) && isset( $seed_result['status'] ) ) {
                                $query_args['seed_status'] = $seed_result['status'];

                                if ( isset( $seed_result['inserted'] ) ) {
                                        $query_args['seed_added'] = max( 0, intval( $seed_result['inserted'] ) );
                                }

                                if ( isset( $seed_result['skipped'] ) ) {
                                        $query_args['seed_skipped'] = max( 0, intval( $seed_result['skipped'] ) );
                                }

                                if ( isset( $seed_result['reason'] ) ) {
                                        $query_args['seed_reason'] = sanitize_text_field( $seed_result['reason'] );
                                }
                        }

                        wp_safe_redirect( add_query_arg( $query_args, admin_url( 'admin.php?page=astgdrmsys-exam-name' ) ) );
                        exit;
                }
        }

	/**
	 * Retrieves the list of departments.
	 *
	 * @return array An array of departments.
	 */
	private function get_departments( $wpdb ) {
		$cache_key   = 'astgdrmsys_departments';
		$departments = wp_cache_get( $cache_key );

		if ( $departments === false ) {
			$department_table = esc_sql( $wpdb->prefix . 'astgdrmsys_department' );

            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.DirectQuery
			$departments = $wpdb->get_results(
                // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
				"SELECT id, department FROM `$department_table` ORDER BY department ASC",
				ARRAY_A
			);

			if ( $departments ) {
				wp_cache_set( $cache_key, $departments );
			}
		}

		return $departments;
	}

	private function get_classes( $wpdb ) {
		$class_table = esc_sql( $wpdb->prefix . 'astgdrmsys_class' );
		return $wpdb->get_results( "SELECT id, class FROM `$class_table` ORDER BY class ASC", ARRAY_A );
	}

	/**
	 * Retrieves the list of exam years.
	 *
	 * This function fetches and returns an array of years for which exams are available.
	 *
	 * @return array An array of exam years.
	 */
	private function get_exam_years( $wpdb ) {
		$cache_key  = 'astgdrmsys_exam_years';
		$exam_years = wp_cache_get( $cache_key );

		if ( $exam_years === false ) {
			$examyear_table = esc_sql( $this->prefix . 'astgdrmsys_exam_year' );

            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.DirectQuery
			$exam_years = $wpdb->get_results(
                // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
				"SELECT DISTINCT ey.id AS exam_year_id, ey.exam_year FROM `$examyear_table` ey",
				ARRAY_A
			);

			if ( $exam_years ) {
				wp_cache_set( $cache_key, $exam_years );
			}
		}

		return $exam_years;
	}


	/**
	 * Retrieves the list of exam names.
	 *
	 * @return array An array of exam names.
	 */
	private function get_exam_names( $wpdb ) {
		$cache_key  = 'astgdrmsys_exam_names';
		$exam_names = wp_cache_get( $cache_key );

		if ( $exam_names === false ) {
			$examname_table   = esc_sql( $this->prefix . 'astgdrmsys_exam_name' );
			$department_table = esc_sql( $this->prefix . 'astgdrmsys_department' );
			$examyear_table   = esc_sql( $this->prefix . 'astgdrmsys_exam_year' );

            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.DirectQuery
			$exam_names = $wpdb->get_results(
                // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                                "SELECT e.id, e.exam_name, e.class, d.department, ey.exam_year, COALESCE(e.exam_category, 'general_exam') AS exam_category, e.result_title, e.result_subtitle, e.result_footer_text, e.result_publish_status FROM `$examname_table` e JOIN `$department_table` d ON e.department = d.id JOIN `$examyear_table` ey ON e.exam_year_id = ey.id",
				ARRAY_A
			);

			if ( $exam_names ) {
				wp_cache_set( $cache_key, $exam_names );
			}
		}

		return $exam_names;
	}


	/**
	 * Renders messages to be displayed in the admin interface.
	 *
	 * This function is responsible for outputting any messages that need to be
	 * shown to the user, such as success or error notifications.
	 *
	 * @return void
	 */
        private function astgdrmsys_render_messages() {

                $messages = array(
                        'edit'    => __( 'Exam Name Updated Successfully', 'result-management-system-for-institutions' ),
                        'del'     => __( 'Exam Name Deleted Successfully', 'result-management-system-for-institutions' ),
                        'add'     => __( 'Exam Name Added Successfully', 'result-management-system-for-institutions' ),
                        'publish' => __( 'Selected exam has been published successfully', 'result-management-system-for-institutions' ),
                );

                foreach ( $messages as $key => $message ) {
                        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
                        if ( isset( $_GET[ $key ] ) && $_GET[ $key ] === 'true' ) {
                                echo wp_kses_post( $this->get_alert_html( $message ) );
                        }
                }

                // phpcs:ignore WordPress.Security.NonceVerification.Recommended
                $save_error = isset( $_GET['save_error'] ) ? sanitize_text_field( wp_unslash( $_GET['save_error'] ) ) : '';

                if ( 'no_students' === $save_error ) {
                        echo wp_kses_post(
                                $this->get_error_alert_html(
                                        __( 'Exam name was not saved because no active students matched the selected class, department, exam year, and section filter.', 'result-management-system-for-institutions' )
                                )
                        );
                }

                // phpcs:ignore WordPress.Security.NonceVerification.Recommended
                $seed_status = isset( $_GET['seed_status'] ) ? sanitize_text_field( wp_unslash( $_GET['seed_status'] ) ) : '';

                if ( $seed_status !== '' ) {
                        $seed_reason  = isset( $_GET['seed_reason'] ) ? sanitize_text_field( wp_unslash( $_GET['seed_reason'] ) ) : '';
                        $seed_added   = isset( $_GET['seed_added'] ) ? intval( wp_unslash( $_GET['seed_added'] ) ) : 0;
                        $seed_skipped = isset( $_GET['seed_skipped'] ) ? intval( wp_unslash( $_GET['seed_skipped'] ) ) : 0;

                        switch ( $seed_status ) {
                                case 'success':
                                        $message = sprintf(
                                                esc_html__( 'Students assigned from Student Database. Added %1$d students; skipped %2$d duplicates.', 'result-management-system-for-institutions' ),
                                                $seed_added,
                                                $seed_skipped
                                        );
                                        break;
                                case 'warning':
                                        if ( 'no_students' === $seed_reason ) {
                                                $message = __( 'Auto-assignment skipped because no active student database enrollments matched the selected class, department, and exam year.', 'result-management-system-for-institutions' );
                                        } else {
                                                $message = __( 'Student auto-assignment was skipped.', 'result-management-system-for-institutions' );
                                        }
                                        break;
                                default:
                                        $message = __( 'Student auto-assignment failed. Please review the selected class, department, and exam year.', 'result-management-system-for-institutions' );
                                        break;
                        }

                        echo wp_kses_post( $this->get_alert_html( $message ) );
                }
        }

	/**
	 * Generates the HTML for an alert message.
	 *
	 * @param string $message The message to be displayed in the alert.
	 * @return string The HTML string for the alert message.
	 */
	private function get_alert_html( $message ) {
		return sprintf(
			'<div id="message_div" class="alert alert-success">
                <center>%s</center>
                <button class="close-message" aria-label="Close">&times;</button>
            </div>',
			esc_html( $message )
		);
	}

        private function get_error_alert_html( $message ) {
                return sprintf(
                        '<div id="message_div" class="alert alert-danger">
                <center>%s</center>
                <button class="close-message" aria-label="Close">&times;</button>
            </div>',
                        esc_html( $message )
                );
        }

	/**
	 * Renders the page for adding a new exam name.
	 *
	 * This function is responsible for generating the HTML and handling any
	 * necessary logic to display the form for adding a new exam name in the
	 * admin panel.
	 *
	 * @return void
	 */
	private function astgdrmsys_render_examname_page() {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( isset( $_GET['editid'] ) ) {
			$this->astgdrmsys_render_edit_form( $this->wpdb );
		} else {
			$this->astgdrmsys_render_main_page();
		}
	}

	/**
	 * Renders the form for editing an exam name.
	 *
	 * This function generates and displays the HTML form used for editing
	 * an existing exam name within the plugin.
	 *
	 * @return void
	 */
	private function astgdrmsys_render_edit_form( $wpdb ) {
		if ( isset( $_GET['editid'], $_GET['astgdrmsys_exam_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['astgdrmsys_exam_nonce'] ) ), 'astgdrmsys_exam_action' ) ) {
			// Get the exam ID
			$editid = isset( $_GET['editid'] ) ? absint( wp_unslash( $_GET['editid'] ) ) : 0;

			// Get the exam details
			$cache_key = 'exam_name_' . $editid;
			$exam      = wp_cache_get( $cache_key );

			if ( $exam === false ) {
                // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery
				$exam = $wpdb->get_row(
					$wpdb->prepare(
                        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
						"SELECT * FROM {$this->prefix}astgdrmsys_exam_name WHERE `id` = %d",
						$editid
					),
					ARRAY_A
				);

				wp_cache_set( $cache_key, $exam );
			}

			if ( ! $exam ) {
				wp_die( esc_html_e( 'Exam not found', 'result-management-system-for-institutions' ) );
			}
		} else {
			wp_die( esc_html_e( 'Invalid request.', 'result-management-system-for-institutions' ) );

		}

                $departments             = $this->get_departments( $wpdb );
                $classes                 = $this->get_classes( $wpdb );
                $exam_years              = $this->get_exam_years( $wpdb );
                $exam_category_options   = $this->get_exam_category_options();
                $selected_exam_category  = ! empty( $exam['exam_category'] ) ? $exam['exam_category'] : 'general_exam';
                $subject_entries         = $this->get_exam_subjects_for_display( $exam );
                $combined_selection      = $this->parse_combined_component_exams( $exam['combined_component_exams'] ?? null );
                $selected_class_tests_attr = ! empty( $combined_selection['class_tests'] ) ? implode( ',', array_map( 'intval', $combined_selection['class_tests'] ) ) : '';
                $selected_general_exam_attr = ! empty( $combined_selection['general_exam'] ) ? intval( $combined_selection['general_exam'] ) : '';

                if ( ! array_key_exists( $selected_exam_category, $exam_category_options ) ) {
                        $selected_exam_category = 'general_exam';
                }

                $assessment_defaults_map = $this->get_assessment_default_map();
                $assessment_values       = $this->resolve_assessment_display_names( $exam );
                $exam                    = array_merge( $exam, $assessment_values );
                ?>
                <div class='container'>
                        <h3 class='heading text-center mb-4'><?php esc_html_e( 'Edit Exam Name', 'result-management-system-for-institutions' ); ?></h3>
                        <form method='post' action='' class="edit-form" enctype="multipart/form-data">
				<?php wp_nonce_field( 'astgdrmsys_exam_action', 'astgdrmsys_exam_nonce' ); ?>
				
				<!-- Exam Name -->
				<div class="form-group row mb-3">
					<label class="col-sm-3 col-form-label"><strong><?php esc_html_e( 'Enter Exam Name:', 'result-management-system-for-institutions' ); ?></strong></label>
					<div class="col-sm-9">
                                                <input type='text' class="form-control" name='updateexam_name' value='<?php echo esc_attr( $exam['exam_name'] ); ?>' required>
                                        </div>
                                </div>
				<!-- Class -->
				<div class="form-group row mb-3">
					<label class="col-sm-3 col-form-label"><strong><?php esc_html_e( 'Select Class:', 'result-management-system-for-institutions' ); ?></strong></label>
					<div class="col-sm-9">
						<select name="updateHiddenClassid" id="updateHiddenClassid" class="form-control" required>
							<option value="" disabled><?php esc_html_e( 'Select a Class', 'result-management-system-for-institutions' ); ?></option>
							<?php foreach ( $classes as $class ) : ?>
								<option value="<?php echo esc_attr( $class['id'] ); ?>" data-class-name="<?php echo esc_attr( $class['class'] ); ?>" <?php selected( (int) ( $exam['class_id'] ?? 0 ), (int) $class['id'] ); ?>>
									<?php echo esc_html( $class['class'] ); ?>
								</option>
							<?php endforeach; ?>
						</select>
						<input type="hidden" name="updateHiddenClassname" id="updateHiddenClassname" value="<?php echo esc_attr( $exam['class'] ); ?>">
					</div>
				</div>
				<!-- Department -->
				<div class="form-group row mb-3">
					<label class="col-sm-3 col-form-label"><strong><?php esc_html_e( 'Select Department:', 'result-management-system-for-institutions' ); ?></strong></label>
					<div class="col-sm-9">
                                                <select name="updatedepartment" id="updateSelectId" class="form-control" required>
                                                        <?php foreach ( $departments as $department ) : ?>
                                                                <option value="<?php echo esc_attr( $department['id'] ); ?>" <?php selected( (string) $exam['department'], (string) $department['id'] ); ?>>
                                                                        <?php echo esc_html( $department['department'] ); ?>
                                                                </option>
                                                        <?php endforeach; ?>
                                                </select>
					</div>
				</div>
				<!-- Exam Year -->
				<div class="form-group row mb-3">
					<label class="col-sm-3 col-form-label"><strong><?php esc_html_e( 'Select Exam Year:', 'result-management-system-for-institutions' ); ?></strong></label>
					<div class="col-sm-9">
						<select name='updateexam_year' id="updateExamYear" class="form-control" required>
							<option value="" disabled <?php selected( empty( $exam['exam_year'] ) ); ?>>
								<?php esc_html_e( 'Select an Exam Year', 'result-management-system-for-institutions' ); ?>
							</option>
							<?php foreach ( $exam_years as $exam_year ) : ?>
								<option value="<?php echo esc_attr( $exam_year['exam_year'] . ',' . $exam_year['exam_year_id'] ); ?>"
									<?php selected( $exam_year['exam_year'] . ',' . $exam_year['exam_year_id'], $exam['exam_year'] . ',' . $exam['exam_year_id'] ); ?>>
									<?php echo esc_html( $exam_year['exam_year'] ); ?>
								</option>
							<?php endforeach; ?>
						</select>
					</div>
				</div>
                                <!-- Assessment Format -->
                                <div class="form-group row mb-3">
                                        <label class="col-sm-3 col-form-label"><strong><?php esc_html_e( 'Assessment Format:', 'result-management-system-for-institutions' ); ?></strong></label>
                                        <div class="col-sm-9">
                                                <select class="form-control" name="update_exam_type" required>
                                                        <option value="single" <?php selected( $exam['exam_type'], 'single' ); ?>><?php esc_html_e( 'Single Assessment', 'result-management-system-for-institutions' ); ?></option>
                                                        <option value="composite" <?php selected( $exam['exam_type'], 'composite' ); ?>><?php esc_html_e( 'Two-Part Assessment', 'result-management-system-for-institutions' ); ?></option>
                                                        <option value="triple" <?php selected( $exam['exam_type'], 'triple' ); ?>><?php esc_html_e( 'Three-Part Assessment', 'result-management-system-for-institutions' ); ?></option>
                                                </select>
                                        </div>
                                </div>
                                <div class="form-group row mb-3 assessment-label-field" data-exam-types="single,composite,triple">
                                        <label class="col-sm-3 col-form-label" for="update_first_assessment_display_name"><strong><?php esc_html_e( 'First Assessment Display Name', 'result-management-system-for-institutions' ); ?></strong></label>
                                        <div class="col-sm-9">
                                                <input type="text"
                                                        class="form-control assessment-display-input"
                                                        id="update_first_assessment_display_name"
                                                        name="update_first_assessment_display_name"
                                                        value="<?php echo esc_attr( $exam['first_assessment_display_name'] ?? '' ); ?>"
                                                        data-default-single="<?php echo esc_attr( $assessment_defaults_map['single']['first_assessment_display_name'] ?? '' ); ?>"
                                                        data-default-composite="<?php echo esc_attr( $assessment_defaults_map['composite']['first_assessment_display_name'] ?? '' ); ?>"
                                                        data-default-triple="<?php echo esc_attr( $assessment_defaults_map['triple']['first_assessment_display_name'] ?? '' ); ?>"
                                                >
                                        </div>
                                </div>
                                <div class="form-group row mb-3 assessment-label-field" data-exam-types="composite,triple">
                                        <label class="col-sm-3 col-form-label" for="update_second_assessment_display_name"><strong><?php esc_html_e( 'Second Assessment Display Name', 'result-management-system-for-institutions' ); ?></strong></label>
                                        <div class="col-sm-9">
                                                <input type="text"
                                                        class="form-control assessment-display-input"
                                                        id="update_second_assessment_display_name"
                                                        name="update_second_assessment_display_name"
                                                        value="<?php echo esc_attr( $exam['second_assessment_display_name'] ?? '' ); ?>"
                                                        data-default-single="<?php echo esc_attr( $assessment_defaults_map['single']['second_assessment_display_name'] ?? '' ); ?>"
                                                        data-default-composite="<?php echo esc_attr( $assessment_defaults_map['composite']['second_assessment_display_name'] ?? '' ); ?>"
                                                        data-default-triple="<?php echo esc_attr( $assessment_defaults_map['triple']['second_assessment_display_name'] ?? '' ); ?>"
                                                >
                                        </div>
                                </div>
                                <div class="form-group row mb-3 assessment-label-field" data-exam-types="triple">
                                        <label class="col-sm-3 col-form-label" for="update_third_assessment_display_name"><strong><?php esc_html_e( 'Third Assessment Display Name', 'result-management-system-for-institutions' ); ?></strong></label>
                                        <div class="col-sm-9">
                                                <input type="text"
                                                        class="form-control assessment-display-input"
                                                        id="update_third_assessment_display_name"
                                                        name="update_third_assessment_display_name"
                                                        value="<?php echo esc_attr( $exam['third_assessment_display_name'] ?? '' ); ?>"
                                                        data-default-single="<?php echo esc_attr( $assessment_defaults_map['single']['third_assessment_display_name'] ?? '' ); ?>"
                                                        data-default-composite="<?php echo esc_attr( $assessment_defaults_map['composite']['third_assessment_display_name'] ?? '' ); ?>"
                                                        data-default-triple="<?php echo esc_attr( $assessment_defaults_map['triple']['third_assessment_display_name'] ?? '' ); ?>"
                                                >
                                        </div>
                                </div>
                                <div class="form-group row mb-3 assessment-label-field" data-exam-types="single,composite,triple">
                                        <label class="col-sm-3 col-form-label" for="update_total_display_name"><strong><?php esc_html_e( 'Total Display Name', 'result-management-system-for-institutions' ); ?></strong></label>
                                        <div class="col-sm-9">
                                                <input type="text"
                                                        class="form-control assessment-display-input"
                                                        id="update_total_display_name"
                                                        name="update_total_display_name"
                                                        value="<?php echo esc_attr( $exam['total_display_name'] ?? '' ); ?>"
                                                        data-default-single="<?php echo esc_attr( $assessment_defaults_map['single']['total_display_name'] ?? '' ); ?>"
                                                        data-default-composite="<?php echo esc_attr( $assessment_defaults_map['composite']['total_display_name'] ?? '' ); ?>"
                                                        data-default-triple="<?php echo esc_attr( $assessment_defaults_map['triple']['total_display_name'] ?? '' ); ?>"
                                                >
                                        </div>
                                </div>
                                <!-- Exam Type -->
                                <div class="form-group row mb-3">
                                        <label class="col-sm-3 col-form-label"><strong><?php esc_html_e( 'Exam Type:', 'result-management-system-for-institutions' ); ?></strong></label>
                                        <div class="col-sm-9">
                                                <select class="form-control" name="update_exam_category" required>
                                                        <?php foreach ( $exam_category_options as $category_key => $category_label ) : ?>
                                                                <option value="<?php echo esc_attr( $category_key ); ?>" <?php selected( $selected_exam_category, $category_key ); ?>>
                                                                        <?php echo esc_html( $category_label ); ?>
                                                                </option>
                                                        <?php endforeach; ?>
                                                </select>
                                        </div>
                                </div>
                                <!-- Combined Result Sources -->
                                <div class="form-group row mb-3 combined-exam-options" id="update-combined-exam-options" style="display: none;"
                                        data-placeholder="<?php echo esc_attr__( 'Select a class and department to load exams.', 'result-management-system-for-institutions' ); ?>"
                                        data-class-tests-placeholder="<?php echo esc_attr__( 'Select Class Test exams to include.', 'result-management-system-for-institutions' ); ?>"
                                        data-general-placeholder="<?php echo esc_attr__( 'Select a General Exam to include.', 'result-management-system-for-institutions' ); ?>"
                                        data-loading="<?php echo esc_attr__( 'Loading exams…', 'result-management-system-for-institutions' ); ?>"
                                        data-empty-class-tests="<?php echo esc_attr__( 'No Class Test exams available for the selected class and department.', 'result-management-system-for-institutions' ); ?>"
                                        data-empty-general="<?php echo esc_attr__( 'No General exams available for the selected class and department.', 'result-management-system-for-institutions' ); ?>"
                                        data-selected-class-tests="<?php echo esc_attr( $selected_class_tests_attr ); ?>"
                                        data-selected-general="<?php echo esc_attr( $selected_general_exam_attr ); ?>">
                                        <div class="col-sm-9 offset-sm-3">
                                                <label><strong><?php esc_html_e( 'Combined Result Sources', 'result-management-system-for-institutions' ); ?></strong></label>
                                                <p class="description mb-2"><?php esc_html_e( 'Select the Class Test exams and the General Exam whose marks should be averaged for this Combined Result.', 'result-management-system-for-institutions' ); ?></p>
                                                <label for="update-combined-class-tests"><?php esc_html_e( 'Class Test Exams', 'result-management-system-for-institutions' ); ?></label>
                                                <select id="update-combined-class-tests" name="update_combined_class_tests[]" class="form-control" multiple size="5">
                                                        <option value="" disabled><?php esc_html_e( 'Select a class and department first.', 'result-management-system-for-institutions' ); ?></option>
                                                </select>
                                                <small class="form-text text-muted"><?php esc_html_e( 'Hold Ctrl (Windows) or Command (Mac) to select multiple exams.', 'result-management-system-for-institutions' ); ?></small>
                                                <label for="update-combined-general-exam" class="mt-3"><?php esc_html_e( 'General Exam', 'result-management-system-for-institutions' ); ?></label>
                                                <select id="update-combined-general-exam" name="update_combined_general_exam" class="form-control">
                                                        <option value="" disabled><?php esc_html_e( 'Select a class and department first.', 'result-management-system-for-institutions' ); ?></option>
                                                </select>
                                        </div>
                                </div>
                                <!-- Subjects & Full Marks -->
                                <div class="form-group row mb-3">
                                        <label class="col-sm-3 col-form-label"><strong><?php esc_html_e( 'Subjects & Full Marks:', 'result-management-system-for-institutions' ); ?></strong></label>
                                        <div class="col-sm-9">
                                                <div class="exam-subjects-wrapper" id="update-exam-subjects-wrapper" data-field-prefix="update_exam_subjects" data-placeholder="<?php echo esc_attr__( 'Select a department to load subjects.', 'result-management-system-for-institutions' ); ?>" data-loading="<?php echo esc_attr__( 'Loading subjects…', 'result-management-system-for-institutions' ); ?>" data-empty="<?php echo esc_attr__( 'No subjects available for the selected department.', 'result-management-system-for-institutions' ); ?>" data-error="<?php echo esc_attr__( 'Failed to load subjects. Please try again.', 'result-management-system-for-institutions' ); ?>">
                                                        <?php $this->render_subjects_table( $subject_entries, 'update_exam_subjects', 'update-exam-subjects-table', __( 'Select a department to load subjects.', 'result-management-system-for-institutions' ) ); ?>
                                                </div>
                                        </div>
                                </div>
                                <!-- Marksheet Heading -->
                                <h4 class='heading text-center mb-4'><?php esc_html_e( 'To be Shown on the Result Marksheet', 'result-management-system-for-institutions' ); ?></h4>

                                <!-- Result Title -->
				<div class="form-group row mb-3">
					<label class="col-sm-3 col-form-label"><strong><?php esc_html_e( 'Result Title:', 'result-management-system-for-institutions' ); ?></strong></label>
					<div class="col-sm-9">
						<input type='text' class="form-control" name='update_result_title' value='<?php echo esc_attr( $exam['result_title'] ); ?>' required>
					</div>
				</div>
				<!-- Result Subtitle -->
				<div class="form-group row mb-3">
					<label class="col-sm-3 col-form-label"><strong><?php esc_html_e( 'Result Subtitle:', 'result-management-system-for-institutions' ); ?></strong></label>
					<div class="col-sm-9">
						<input type='text' class="form-control" name='update_result_subtitle' value='<?php echo esc_attr( $exam['result_subtitle'] ); ?>' required>
					</div>
				</div>
			
                                <!-- Footer Text -->
                                <div class="form-group row mb-3">
                                        <label class="col-sm-3 col-form-label"><strong><?php esc_html_e( 'Result Footer Text:', 'result-management-system-for-institutions' ); ?></strong></label>
                                        <div class="col-sm-9">
                                                <input type='text' class="form-control" name='update_result_footer_text' value='<?php echo esc_attr( $exam['result_footer_text'] ); ?>' required>
                                        </div>
                                </div>
                                <div class="form-group row mb-3">
                                        <label class="col-sm-3 col-form-label"><strong><?php esc_html_e( 'Principal Signature:', 'result-management-system-for-institutions' ); ?></strong></label>
                                        <div class="col-sm-9">
                                                <?php if ( ! empty( $exam['principal_signature'] ) ) : ?>
                                                        <img src="<?php echo esc_url( $exam['principal_signature'] ); ?>" alt="principal signature" style="max-height:80px;display:block;margin-bottom:5px;">
                                                <?php endif; ?>
                                                <input type="file" name="update_principal_signature" accept="image/*">
                                                <small><?php esc_html_e( 'Recommended size: 150x80 pixels.', 'result-management-system-for-institutions' ); ?></small>
                                        </div>
                                </div>
                                <div class="form-group row mb-3">
                                        <label class="col-sm-3 col-form-label"><strong><?php esc_html_e( 'Office Seal:', 'result-management-system-for-institutions' ); ?></strong></label>
                                        <div class="col-sm-9">
                                                <?php if ( ! empty( $exam['office_seal'] ) ) : ?>
                                                        <img src="<?php echo esc_url( $exam['office_seal'] ); ?>" alt="office seal" style="max-height:80px;display:block;margin-bottom:5px;">
                                                <?php endif; ?>
                                                <input type="file" name="update_office_seal" accept="image/*">
                                                <small><?php esc_html_e( 'Recommended size: 80x80 pixels.', 'result-management-system-for-institutions' ); ?></small>
                                        </div>
                                </div>
                                <div class="form-group row mb-3">
                                        <label class="col-sm-3 col-form-label"><strong><?php esc_html_e( 'Include QR Code:', 'result-management-system-for-institutions' ); ?></strong></label>
                                        <div class="col-sm-9">
                                                <div class="custom-control custom-switch">
                                                        <input type="checkbox" class="custom-control-input" id="update-include-qr-code" name="update_include_qr_code" value="1" <?php checked( $exam['include_qr_code'], 1 ); ?>>
                                                        <label class="custom-control-label" for="update-include-qr-code"><?php esc_html_e( 'Enable', 'result-management-system-for-institutions' ); ?></label>
                                                </div>
                                        </div>
                                </div>
                                <!-- Publish Toggle -->
                                <div class="form-group row mb-3">
                                        <label class="col-sm-3 col-form-label"><strong><?php esc_html_e( 'Publish Exam:', 'result-management-system-for-institutions' ); ?></strong></label>
                                        <div class="col-sm-9">
                                                <div class="custom-control custom-switch">
                                                        <input type="checkbox" class="custom-control-input" id="update-result-publish-status" name="update_result_publish_status" value="1" <?php checked( $exam['result_publish_status'], 1 ); ?>>
                                                        <label class="custom-control-label" for="update-result-publish-status"><?php esc_html_e( 'Enable', 'result-management-system-for-institutions' ); ?></label>
                                                </div>
                                        </div>
                                </div>
                                <!-- Restrict Non Logged In Users -->
                                <div class="form-group row mb-3">
                                        <label class="col-sm-3 col-form-label"><strong><?php esc_html_e( 'Restrict Non Logged In Users:', 'result-management-system-for-institutions' ); ?></strong></label>
                                        <div class="col-sm-9">
                                                <div class="custom-control custom-switch">
                                                        <input type="checkbox" class="custom-control-input" id="update-restrict-non-logged-in" name="update_restrict_non_logged_in" value="1" <?php checked( isset( $exam['restrict_non_logged_in'] ) ? $exam['restrict_non_logged_in'] : 0, 1 ); ?>>
                                                        <label class="custom-control-label" for="update-restrict-non-logged-in"><?php esc_html_e( 'Enable', 'result-management-system-for-institutions' ); ?></label>
                                                </div>
                                                <p class="description mb-0"><?php esc_html_e( 'Require users to log in before they can search for this exam result.', 'result-management-system-for-institutions' ); ?></p>
                                        </div>
                                </div>
                                <!-- Check Only Own Result -->
                                <div class="form-group row mb-3">
                                        <label class="col-sm-3 col-form-label"><strong><?php esc_html_e( 'Check Only Own Result:', 'result-management-system-for-institutions' ); ?></strong></label>
                                        <div class="col-sm-9">
                                                <div class="custom-control custom-switch">
                                                        <input type="checkbox" class="custom-control-input" id="update-check-only-own-result" name="update_check_only_own_result" value="1" <?php checked( isset( $exam['check_only_own_result'] ) ? $exam['check_only_own_result'] : 0, 1 ); ?>>
                                                        <label class="custom-control-label" for="update-check-only-own-result"><?php esc_html_e( 'Enable', 'result-management-system-for-institutions' ); ?></label>
                                                </div>
                                                <p class="description mb-0"><?php esc_html_e( 'Limit logged-in students to viewing only their own result for this exam.', 'result-management-system-for-institutions' ); ?></p>
                                        </div>
                                </div>
                                <!-- Fail on Single Subject Toggle -->
                                <div class="form-group row mb-3">
                                        <label class="col-sm-3 col-form-label">
                                                <strong><?php esc_html_e( 'Fail if failed in one or more subjects (excluding fourth subject):', 'result-management-system-for-institutions' ); ?></strong>
                                        </label>
					<div class="col-sm-9">
						<div class="custom-control custom-switch">
							<input type="checkbox"
								class="custom-control-input"
								id="update-fail-on-single-subject"
								name="update_fail_on_single_subject"
								value="1"
								<?php checked( $exam['fail_on_single_subject'], 1 ); ?>>
							<label class="custom-control-label" for="update-fail-on-single-subject">
								<?php esc_html_e( 'Enable', 'result-management-system-for-institutions' ); ?>
							</label>
						</div>
					</div>
				</div>
				<!-- Custom Fields -->
				<h4 class='heading text-center mb-4'>
					<?php esc_html_e( 'Custom Fields', 'result-management-system-for-institutions' ); ?>
				</h4>
				
				<?php for ( $i = 1; $i <= 3; $i++ ) : ?>
					<div class="form-group row mb-3">
						<!-- Field Name -->
						<div class="col-sm-6">
							<label for="update_custom_field_name<?php echo $i; ?>">
								<strong><?php printf( esc_html__( 'Field%d Name', 'result-management-system-for-institutions' ), $i ); ?></strong>
							</label>
							<input type="text" class="form-control"
							name="update_custom_field_name<?php echo $i; ?>"
							id="update_custom_field_name<?php echo $i; ?>"
							value="<?php echo esc_attr( $exam['custom_field_name' . $i] ); ?>"
							placeholder="<?php printf( esc_attr__( 'Enter Field%d Name', 'result-management-system-for-institutions' ), $i ); ?>">
						</div>
						
						<!-- Field Value -->
						<div class="col-sm-6">
							<label for="update_custom_field_value<?php echo $i; ?>">
								<strong><?php printf( esc_html__( 'Field%d Value', 'result-management-system-for-institutions' ), $i ); ?></strong>
							</label>
							<input type="text" class="form-control"
								name="update_custom_field_value<?php echo $i; ?>"
								id="update_custom_field_value<?php echo $i; ?>"
								value="<?php echo esc_attr( $exam['custom_field_value' . $i] ); ?>"
								placeholder="<?php printf( esc_attr__( 'Enter Field%d Value', 'result-management-system-for-institutions' ), $i ); ?>">
						</div>
					</div>
				<?php endfor; ?>

				<!-- Action Buttons -->
				<div class="form-group row mt-4">
					<div class="col-sm-9 offset-sm-3">
						<input type='submit' value='<?php esc_html_e( 'Update', 'result-management-system-for-institutions' ); ?>' class='btn btn-primary' name='updatesubmit'>
						<button type="button" class="btn btn-danger ml-2" onclick="window.history.back();"><?php esc_html_e( 'Cancel', 'result-management-system-for-institutions' ); ?></button>
					</div>
				</div>
			</form>
		</div>
		<?php
	}

	/**
	 * Renders the main page for the exam name management.
	 *
	 * This function is responsible for displaying the main interface
	 * where users can add or manage exam names within the plugin.
	 *
	 * @return void
	 */
	private function astgdrmsys_render_main_page() {
		global $wpdb;
                $exam_names            = $this->get_exam_names( $wpdb );
                $departments           = $this->get_departments( $wpdb );
                $classes               = $this->get_classes( $wpdb );
                $exam_years            = $this->get_exam_years( $wpdb );
                $exam_category_options = $this->get_exam_category_options();
                $assessment_defaults_map = $this->get_assessment_default_map();
                $new_assessment_defaults = $assessment_defaults_map['single'];
                ?>
                <div class="wrap astgdrmsys-premium-wrap">
			<div class="premium-page-header">
				<div class="page-header-text">
					<h1><?php esc_html_e( 'Exam Names', 'result-management-system-for-institutions' ); ?></h1>
					<p>Manage exam names and categories.</p>
				</div>
				<div class="page-header-actions">
					<button id="openModalBtn" class="hero-btn primary-btn">
						<i class="dashicons dashicons-plus"></i> <?php esc_html_e( 'Add New', 'result-management-system-for-institutions' ); ?>
					</button>
				</div>
			</div>

			<?php $this->astgdrmsys_render_messages(); ?>

			<div class="table-responsive mt-4">
				<table class="styled-table">
					<thead class="thead-dark">
						<tr>
							<th scope="col"><?php esc_html_e( 'ID', 'result-management-system-for-institutions' ); ?></th>
							<th scope="col"><?php esc_html_e( 'Exam Name', 'result-management-system-for-institutions' ); ?></th>
							<th scope="col"><?php esc_html_e( 'Department', 'result-management-system-for-institutions' ); ?></th>
							<th scope="col"><?php esc_html_e( 'Class', 'result-management-system-for-institutions' ); ?></th>
                                                        <th scope="col"><?php esc_html_e( 'Exam Year', 'result-management-system-for-institutions' ); ?></th>
                                                        <th scope="col"><?php esc_html_e( 'Exam Type', 'result-management-system-for-institutions' ); ?></th>
							<th scope="col"><?php esc_html_e( 'Result Title', 'result-management-system-for-institutions' ); ?></th>
							<th scope="col"><?php esc_html_e( 'Result Subtitle', 'result-management-system-for-institutions' ); ?></th>
							<th scope="col"><?php esc_html_e( 'Result Footer Text', 'result-management-system-for-institutions' ); ?></th>
							<th scope="col"><?php esc_html_e( 'Publish Status', 'result-management-system-for-institutions' ); ?></th>
							<th scope="col"><?php esc_html_e( 'Actions', 'result-management-system-for-institutions' ); ?></th>
						</tr>
					</thead>
					<tbody>
						<?php if ( ! empty( $exam_names ) ) : ?>
							<?php foreach ( $exam_names as $exam ) : ?>
								<tr>
									<td><?php echo esc_html( $exam['id'] ); ?></td>
									<td><?php echo esc_html( $exam['exam_name'] ); ?></td>
									<td><?php echo esc_html( $exam['department'] ); ?></td>
									<td><?php echo esc_html( $exam['class'] ); ?></td>
                                                                        <td><?php echo esc_html( $exam['exam_year'] ); ?></td>
                                                                        <td>
                                                                                <?php
                                                                                $category_key   = $exam['exam_category'] ?? 'general_exam';
                                                                                $category_label = $exam_category_options[ $category_key ] ?? $exam_category_options['general_exam'];
                                                                                echo esc_html( $category_label );
                                                                                ?>
                                                                        </td>
									<td><?php echo esc_html( $exam['result_title'] ); ?></td>
									<td><?php echo esc_html( $exam['result_subtitle'] ); ?></td>
									<td><?php echo esc_html( $exam['result_footer_text'] ); ?></td>
									<td>
										<?php
										$status       = $exam['result_publish_status'];
										$status_class = $status == 1 ? 'text-success' : 'text-danger';
										$status_text  = $status == 1 ? __( 'Published', 'result-management-system-for-institutions' ) : __( 'Not Published', 'result-management-system-for-institutions' );
										?>
										<span class="badge <?php echo esc_attr( $status_class ); ?>">
											<?php echo esc_html( $status_text ); ?>
										</span>
									</td>

									<td>
										<a href="<?php echo esc_url( wp_nonce_url( add_query_arg( array( 'editid' => $exam['id'] ) ), 'astgdrmsys_exam_action', 'astgdrmsys_exam_nonce' ) ); ?>"
											class="button button-small" title="Edit">
											<span class="dashicons dashicons-edit"></span>
										</a>
										<a href="<?php echo esc_url( wp_nonce_url( add_query_arg( array( 'pubid' => $exam['id'] ) ), 'astgdrmsys_exam_action' ) ); ?>"
											class="button button-small" title="Approve">
											<span class="dashicons dashicons-yes"></span>
										</a>
										<a href="<?php echo esc_url( wp_nonce_url( add_query_arg( array( 'delid' => $exam['id'] ) ), 'astgdrmsys_exam_action', 'astgdrmsys_exam_nonce' ) ); ?>"
											class="button button-small button-link-delete"
											onclick="return confirm('<?php esc_attr_e( 'Are you sure you want to delete this exam?', 'result-management-system-for-institutions' ); ?>');" title="Delete">
											<span class="dashicons dashicons-trash"></span>
										</a>
									</td>
								</tr>
							<?php endforeach; ?>
						<?php else : ?>
							<tr>
                                                                <td colspan="11" class="text-center">
									<?php esc_html_e( 'No exam names found.', 'result-management-system-for-institutions' ); ?>
								</td>
							</tr>
						<?php endif; ?>
					</tbody>
				</table>
			</div>

			<!-- Add Modal -->
			<div id="addmodal" class="modal">
				<div class="modal-dialog">
					<div class="modal-content">
						<div class="modal-header">
							<h5 class="modal-title"><?php esc_html_e( 'Add New Exam Name', 'result-management-system-for-institutions' ); ?></h5>
							<button type="button" class="close" id="closeModalBtn">
								<span>&times;</span>
							</button>
						</div>
						<div class="modal-body">
                                                        <div>
                                                                <p><?php esc_html_e( 'Please fill in the details below to add a new exam name.', 'result-management-system-for-institutions' ); ?></p>
                                                        </div>
                                                        <form method="post" action="" enctype="multipart/form-data">
								<?php wp_nonce_field( 'astgdrmsys_exam_action', 'astgdrmsys_exam_nonce' ); ?>
								<div class="form-group">
									<label for="exam_name"><?php esc_html_e( 'Exam Name', 'result-management-system-for-institutions' ); ?></label>
									<input type="text" class="form-control"
										name="exam_name" required>
								</div>

								<div class="form-group">
									<label for="hiddenclassid"><?php esc_html_e( 'Class', 'result-management-system-for-institutions' ); ?></label>
									<select name="hiddenclassid" id="hiddenclassid" class="form-control" required>
										<option value="" disabled selected><?php esc_html_e( 'Select a Class', 'result-management-system-for-institutions' ); ?></option>
										<?php foreach ( $classes as $class ) : ?>
											<option value="<?php echo esc_attr( $class['id'] ); ?>" data-class-name="<?php echo esc_attr( $class['class'] ); ?>">
												<?php echo esc_html( $class['class'] ); ?>
											</option>
										<?php endforeach; ?>
									</select>
									<input type="hidden" name="hiddenclassname" id="hiddenclassname">
								</div>

								<div class="form-group">
									<label for="departmentadd"><?php esc_html_e( 'Department', 'result-management-system-for-institutions' ); ?></label>
									<select name="departmentadd" id="selectDepartmentId"
										class="form-control" required>
										<option value="" disabled selected>
											<?php esc_html_e( 'Select a Department', 'result-management-system-for-institutions' ); ?>
										</option>
                                                                                <?php foreach ( $departments as $department ) : ?>
                                                                                        <option value="<?php echo esc_attr( $department['id'] ); ?>">
                                                                                                <?php echo esc_html( $department['department'] ); ?>
                                                                                        </option>
                                                                                <?php endforeach; ?>
                                                                        </select>
								</div>

								<div class="form-group">
									<label for="exam_year"><?php esc_html_e( 'Exam Year', 'result-management-system-for-institutions' ); ?></label>
									<select name="exam_year" id="ExamYearId"
										class="form-control">
										<option value="" disabled selected>
											<?php esc_html_e( 'Select Exam Year', 'result-management-system-for-institutions' ); ?>
										</option>
										<?php foreach ( $exam_years as $exam_year ) : ?>
											<option value="<?php echo esc_attr( $exam_year['exam_year'] . '-' . $exam_year['exam_year_id'] ); ?>">
												<?php echo esc_html( $exam_year['exam_year'] ); ?>
											</option>
										<?php endforeach; ?>
									</select>
								</div>

                                                                <!-- Assessment Format -->
                                                                <div class="form-group mt-3">
                                                                        <label for="exam_type"><?php esc_html_e( 'Assessment Format', 'result-management-system-for-institutions' ); ?></label>
                                                                        <select class="form-control" name="exam_type" id="exam_type">
                                                                                <option value="single"><?php esc_html_e( 'Single Assessment', 'result-management-system-for-institutions' ); ?></option>
                                                                                <option value="composite"><?php esc_html_e( 'Two-Part Assessment', 'result-management-system-for-institutions' ); ?></option>
                                                                                <option value="triple"><?php esc_html_e( 'Three-Part Assessment', 'result-management-system-for-institutions' ); ?></option>
                                                                        </select>
                                                                </div>
                                                                <div class="form-group assessment-label-field" data-exam-types="single,composite,triple">
                                                                        <label for="first_assessment_display_name"><?php esc_html_e( 'First Assessment Display Name', 'result-management-system-for-institutions' ); ?></label>
                                                                        <input type="text"
                                                                                class="form-control assessment-display-input"
                                                                                id="first_assessment_display_name"
                                                                                name="first_assessment_display_name"
                                                                                value="<?php echo esc_attr( $new_assessment_defaults['first_assessment_display_name'] ?? '' ); ?>"
                                                                                data-default-single="<?php echo esc_attr( $assessment_defaults_map['single']['first_assessment_display_name'] ?? '' ); ?>"
                                                                                data-default-composite="<?php echo esc_attr( $assessment_defaults_map['composite']['first_assessment_display_name'] ?? '' ); ?>"
                                                                                data-default-triple="<?php echo esc_attr( $assessment_defaults_map['triple']['first_assessment_display_name'] ?? '' ); ?>"
                                                                        >
                                                                </div>
                                                                <div class="form-group assessment-label-field" data-exam-types="composite,triple">
                                                                        <label for="second_assessment_display_name"><?php esc_html_e( 'Second Assessment Display Name', 'result-management-system-for-institutions' ); ?></label>
                                                                        <input type="text"
                                                                                class="form-control assessment-display-input"
                                                                                id="second_assessment_display_name"
                                                                                name="second_assessment_display_name"
                                                                                value="<?php echo esc_attr( $new_assessment_defaults['second_assessment_display_name'] ?? '' ); ?>"
                                                                                data-default-single="<?php echo esc_attr( $assessment_defaults_map['single']['second_assessment_display_name'] ?? '' ); ?>"
                                                                                data-default-composite="<?php echo esc_attr( $assessment_defaults_map['composite']['second_assessment_display_name'] ?? '' ); ?>"
                                                                                data-default-triple="<?php echo esc_attr( $assessment_defaults_map['triple']['second_assessment_display_name'] ?? '' ); ?>"
                                                                        >
                                                                </div>
                                                                <div class="form-group assessment-label-field" data-exam-types="triple">
                                                                        <label for="third_assessment_display_name"><?php esc_html_e( 'Third Assessment Display Name', 'result-management-system-for-institutions' ); ?></label>
                                                                        <input type="text"
                                                                                class="form-control assessment-display-input"
                                                                                id="third_assessment_display_name"
                                                                                name="third_assessment_display_name"
                                                                                value="<?php echo esc_attr( $new_assessment_defaults['third_assessment_display_name'] ?? '' ); ?>"
                                                                                data-default-single="<?php echo esc_attr( $assessment_defaults_map['single']['third_assessment_display_name'] ?? '' ); ?>"
                                                                                data-default-composite="<?php echo esc_attr( $assessment_defaults_map['composite']['third_assessment_display_name'] ?? '' ); ?>"
                                                                                data-default-triple="<?php echo esc_attr( $assessment_defaults_map['triple']['third_assessment_display_name'] ?? '' ); ?>"
                                                                        >
                                                                </div>
                                                                <div class="form-group assessment-label-field" data-exam-types="single,composite,triple">
                                                                        <label for="total_display_name"><?php esc_html_e( 'Total Display Name', 'result-management-system-for-institutions' ); ?></label>
                                                                        <input type="text"
                                                                                class="form-control assessment-display-input"
                                                                                id="total_display_name"
                                                                                name="total_display_name"
                                                                                value="<?php echo esc_attr( $new_assessment_defaults['total_display_name'] ?? '' ); ?>"
                                                                                data-default-single="<?php echo esc_attr( $assessment_defaults_map['single']['total_display_name'] ?? '' ); ?>"
                                                                                data-default-composite="<?php echo esc_attr( $assessment_defaults_map['composite']['total_display_name'] ?? '' ); ?>"
                                                                                data-default-triple="<?php echo esc_attr( $assessment_defaults_map['triple']['total_display_name'] ?? '' ); ?>"
                                                                        >
                                                                </div>

                                                                <!-- Exam Type -->
                                                                <div class="form-group mt-3">
                                                                        <label for="exam_category"><?php esc_html_e( 'Exam Type', 'result-management-system-for-institutions' ); ?></label>
                                                                        <select class="form-control" name="exam_category" id="exam_category">
                                                                                <?php foreach ( $this->get_exam_category_options() as $category_key => $category_label ) : ?>
                                                                                        <option value="<?php echo esc_attr( $category_key ); ?>" <?php selected( 'general_exam', $category_key ); ?>>
                                                                                                <?php echo esc_html( $category_label ); ?>
                                                                                        </option>
                                                                                <?php endforeach; ?>
                                                                        </select>
                                                                </div>

                                                                <!-- Combined Result Sources -->
                                                                <div class="form-group mt-3 combined-exam-options" id="combined-exam-options" style="display: none;"
                                                                        data-placeholder="<?php echo esc_attr__( 'Select a class and department to load exams.', 'result-management-system-for-institutions' ); ?>"
                                                                        data-class-tests-placeholder="<?php echo esc_attr__( 'Select Class Test exams to include.', 'result-management-system-for-institutions' ); ?>"
                                                                        data-general-placeholder="<?php echo esc_attr__( 'Select a General Exam to include.', 'result-management-system-for-institutions' ); ?>"
                                                                        data-loading="<?php echo esc_attr__( 'Loading exams…', 'result-management-system-for-institutions' ); ?>"
                                                                        data-empty-class-tests="<?php echo esc_attr__( 'No Class Test exams available for the selected class and department.', 'result-management-system-for-institutions' ); ?>"
                                                                        data-empty-general="<?php echo esc_attr__( 'No General exams available for the selected class and department.', 'result-management-system-for-institutions' ); ?>"
                                                                        data-selected-class-tests=""
                                                                        data-selected-general="">
                                                                        <label><strong><?php esc_html_e( 'Combined Result Sources', 'result-management-system-for-institutions' ); ?></strong></label>
                                                                        <p class="description mb-2"><?php esc_html_e( 'Select the Class Test exams and the General Exam whose marks should be averaged for this Combined Result.', 'result-management-system-for-institutions' ); ?></p>
                                                                        <label for="combined-class-tests"><?php esc_html_e( 'Class Test Exams', 'result-management-system-for-institutions' ); ?></label>
                                                                        <select id="combined-class-tests" name="combined_class_tests[]" class="form-control" multiple size="5">
                                                                                <option value="" disabled><?php esc_html_e( 'Select a class and department first.', 'result-management-system-for-institutions' ); ?></option>
                                                                        </select>
                                                                        <small class="form-text text-muted"><?php esc_html_e( 'Hold Ctrl (Windows) or Command (Mac) to select multiple exams.', 'result-management-system-for-institutions' ); ?></small>
                                                                        <label for="combined-general-exam" class="mt-3"><?php esc_html_e( 'General Exam', 'result-management-system-for-institutions' ); ?></label>
                                                                        <select id="combined-general-exam" name="combined_general_exam" class="form-control">
                                                                                <option value="" disabled selected><?php esc_html_e( 'Select a class and department first.', 'result-management-system-for-institutions' ); ?></option>
                                                                        </select>
                                                                </div>

                                                                <!-- Student Seeding Options -->
                                                                <div class="form-group mt-3">
                                                                        <div class="custom-control custom-switch">
                                                                                <input type="checkbox" class="custom-control-input" id="auto-seed-students" name="auto_seed_students" value="1" checked>
                                                                                <label class="custom-control-label" for="auto-seed-students"><?php esc_html_e( 'Auto-assign students from Student Database', 'result-management-system-for-institutions' ); ?></label>
                                                                        </div>
                                                                        <small class="form-text text-muted"><?php esc_html_e( 'Create exam result rows for active students enrolled in the selected class, department, and exam year.', 'result-management-system-for-institutions' ); ?></small>
                                                                </div>

                                                                <div class="form-group mt-3" id="section-filter-options">
                                                                        <div class="custom-control custom-switch">
                                                                                <input type="checkbox" class="custom-control-input" id="filter-by-section" name="filter_by_section" value="1">
                                                                                <label class="custom-control-label" for="filter-by-section"><?php esc_html_e( 'Filter by section', 'result-management-system-for-institutions' ); ?></label>
                                                                        </div>
                                                                        <select name="section_filter[]" id="section-filter-select" class="form-control selectSection mt-2" multiple size="5" disabled>
                                                                                <option value="" disabled><?php esc_html_e( 'Select a department first.', 'result-management-system-for-institutions' ); ?></option>
                                                                        </select>
                                                                        <small class="form-text text-muted"><?php esc_html_e( 'When enabled, only students from the selected section(s) will be assigned to this exam.', 'result-management-system-for-institutions' ); ?></small>
                                                                </div>

                                                                <div class="form-group mt-3">
                                                                        <label for="seed_source_exam" style="display:none;"><strong><?php esc_html_e( 'Legacy source exam selection', 'result-management-system-for-institutions' ); ?></strong></label>
                                                                        <select name="seed_source_exam" id="seed_source_exam" class="form-control" style="display:none;">
                                                                                <option value=""><?php esc_html_e( 'Use the most recent matching exam automatically', 'result-management-system-for-institutions' ); ?></option>
                                                                                <?php if ( ! empty( $exam_names ) ) : ?>
                                                                                        <?php foreach ( $exam_names as $exam_option ) :
                                                                                                $option_id = isset( $exam_option['id'] ) ? intval( $exam_option['id'] ) : 0;

                                                                                                if ( $option_id <= 0 ) {
                                                                                                        continue;
                                                                                                }

                                                                                                $label = sprintf(
                                                                                                        '%1$s — %2$s / %3$s / %4$s',
                                                                                                        $exam_option['exam_name'] ?? '',
                                                                                                        $exam_option['class'] ?? '',
                                                                                                        $exam_option['department'] ?? '',
                                                                                                        $exam_option['exam_year'] ?? ''
                                                                                                );
                                                                                                ?>
                                                                                                <option value="<?php echo esc_attr( $option_id ); ?>"><?php echo esc_html( $label ); ?></option>
                                                                                        <?php endforeach; ?>
                                                                                <?php else : ?>
                                                                                        <option value="" disabled><?php esc_html_e( 'No exams available yet.', 'result-management-system-for-institutions' ); ?></option>
                                                                                <?php endif; ?>
                                                                        </select>
                                                                        <small class="form-text text-muted" style="display:none;"><?php esc_html_e( 'Legacy source exam selection is ignored when assigning students from the Student Database.', 'result-management-system-for-institutions' ); ?></small>
                                                                </div>

                                                                <!-- Subjects & Full Marks -->
                                                                <div class="form-group mt-3 exam-subjects-wrapper" id="exam-subjects-wrapper" data-field-prefix="exam_subjects" data-placeholder="<?php echo esc_attr__( 'Select a department and class to load subjects.', 'result-management-system-for-institutions' ); ?>" data-loading="<?php echo esc_attr__( 'Loading subjects…', 'result-management-system-for-institutions' ); ?>" data-empty="<?php echo esc_attr__( 'No subjects available for the selected department.', 'result-management-system-for-institutions' ); ?>" data-error="<?php echo esc_attr__( 'Failed to load subjects. Please try again.', 'result-management-system-for-institutions' ); ?>">
                                                                        <label><strong><?php esc_html_e( 'Subjects & Full Marks', 'result-management-system-for-institutions' ); ?></strong></label>
                                                                        <?php $this->render_subjects_table( array(), 'exam_subjects', 'exam-subjects-table', __( 'Select a department and class to load subjects.', 'result-management-system-for-institutions' ) ); ?>
                                                                </div>

                                                                <div class="form-group">
                                                                        <center>
                                                                                <h4 class='heading text-center mt-4'><?php esc_html_e( 'To be Shown on the Result Marksheet', 'result-management-system-for-institutions' ); ?></h4>
                                                                        </center>
								</div>

								<div class="form-group">
									<!-- Result Title -->
									<label for="result-title"><?php esc_html_e( 'Result Title', 'result-management-system-for-institutions' ); ?></label>
									<input type="text" class="form-control" name="result_title" required>
									<!-- Result Subtitle -->
									<label for="result-subtitle"><?php esc_html_e( 'Result Subtitle', 'result-management-system-for-institutions' ); ?></label>
									<input type="text" class="form-control" name="result_subtitle" required>
                                                                        <!-- Result footer text -->
                                                                        <label for="result-footer-text"><?php esc_html_e( 'Result Footer Text', 'result-management-system-for-institutions' ); ?></label>
                                                                        <input type="text" class="form-control" name="result_footer_text" required>
                                                                        <label for="principal_signature"><?php esc_html_e( 'Principal Signature', 'result-management-system-for-institutions' ); ?></label>
                                                                        <input type="file" class="form-control" name="principal_signature" accept="image/*">
                                                                        <small><?php esc_html_e( 'Recommended size: 150x80 pixels.', 'result-management-system-for-institutions' ); ?></small>
                                                                        <label for="office_seal" class="mt-3"><?php esc_html_e( 'Office Seal', 'result-management-system-for-institutions' ); ?></label>
                                                                        <input type="file" class="form-control" name="office_seal" accept="image/*">
                                                                        <small><?php esc_html_e( 'Recommended size: 80x80 pixels.', 'result-management-system-for-institutions' ); ?></small>
                                                                        <div class="form-group mt-3">
                                                                                <div class="custom-control custom-switch">
                                                                                        <input type="checkbox" class="custom-control-input" id="include-qr-code" name="include_qr_code" value="1" checked>
                                                                                        <label class="custom-control-label" for="include-qr-code"><?php esc_html_e( 'Include QR Code on Result Card', 'result-management-system-for-institutions' ); ?></label>
                                                                                </div>
                                                                        </div>
                                                                        <!-- Publish Toggle -->
                                                                        <div class="form-group mt-3">
                                                                                <div class="custom-control custom-switch">
                                                                                        <input type="checkbox"
                                                                                                class="custom-control-input"
                                                                                                id="result-publish-status"
                                                                                                name="result_publish_status"
                                                                                                value="0">
                                                                                        <label class="custom-control-label" for="result-publish-status">
                                                                                                <?php esc_html_e( 'Publish Exam', 'result-management-system-for-institutions' ); ?>
                                                                                        </label>

                                                                                </div>
                                                                        </div>
                                                                        <!-- Restrict Non Logged In Users -->
                                                                        <div class="form-group mt-3">
                                                                                <div class="custom-control custom-switch">
                                                                                        <input type="checkbox"
                                                                                                class="custom-control-input"
                                                                                                id="restrict-non-logged-in"
                                                                                                name="restrict_non_logged_in"
                                                                                                value="1">
                                                                                        <label class="custom-control-label" for="restrict-non-logged-in">
                                                                                                <?php esc_html_e( 'Restrict Non Logged In Users', 'result-management-system-for-institutions' ); ?>
                                                                                        </label>
                                                                                </div>
                                                                                <p class="description mb-0"><?php esc_html_e( 'Require visitors to sign in before searching for this exam result.', 'result-management-system-for-institutions' ); ?></p>
                                                                        </div>
                                                                        <!-- Check Only Own Result -->
                                                                        <div class="form-group mt-3">
                                                                                <div class="custom-control custom-switch">
                                                                                        <input type="checkbox"
                                                                                                class="custom-control-input"
                                                                                                id="check-only-own-result"
                                                                                                name="check_only_own_result"
                                                                                                value="1">
                                                                                        <label class="custom-control-label" for="check-only-own-result">
                                                                                                <?php esc_html_e( 'Check Only Own Result', 'result-management-system-for-institutions' ); ?>
                                                                                        </label>
                                                                                </div>
                                                                                <p class="description mb-0"><?php esc_html_e( 'Allow logged-in students to view only their own result for this exam.', 'result-management-system-for-institutions' ); ?></p>
                                                                        </div>
                                                                        <!-- Fail on Single Subject Toggle -->
                                                                        <div class="form-group mt-3">
                                                                                <div class="custom-control custom-switch">
                                                                                        <input type="checkbox"
                                                                                        class="custom-control-input"
											id="fail-on-single-subject"
											name="fail_on_single_subject"
											value="1">
											<label class="custom-control-label" for="fail-on-single-subject">
												<?php esc_html_e( 'Mark a Student result as failed if failed in one or more subjects (excluding fourth subject)', 'result-management-system-for-institutions' ); ?>
											</label>
										</div>
									</div>
									<div>
										<center>
											<h4 class='heading text-center mt-4'>
												<?php esc_html_e( 'Custom Fields', 'result-management-system-for-institutions' ); ?>
											</h4>
										</center>
									</div>
									<!-- Custom Field 1 -->
									<div class="form-group row">
										<div class="col-sm-6 mb-2">
											<label for="custom_field_name1"><?php esc_html_e( 'Field1 Name', 'result-management-system-for-institutions')?></label>
											<input type="text" class="form-control" name="custom_field_name1" id="custom_field_name1"
												placeholder="<?php esc_html_e( 'Enter Field1 Name', 'result-management-system-for-institutions' ); ?>">
										</div>
										<div class="col-sm-6 mb-2">
											<label for="custom_field_value1"><?php esc_html_e('Field1 Value', 'result-management-system-for-institutions')?></label>
											<input type="text" class="form-control" name="custom_field_value1" id="custom_field_value1"
												placeholder="<?php esc_html_e( 'Enter Field1 Value', 'result-management-system-for-institutions' ); ?>">
										</div>
									</div>
									<!-- Custom Field 2 -->
									<div class="form-group row">
										<div class="col-sm-6 mb-2">
											<label for="custom_field_name2"><?php esc_html_e( 'Field2 Name', 'result-management-system-for-institutions')?></label>
											<input type="text" class="form-control" name="custom_field_name2" id="custom_field_name2"
												placeholder="<?php esc_html_e( 'Enter Field2 Name', 'result-management-system-for-institutions' ); ?>">
										</div>
										<div class="col-sm-6 mb-2">
											<label for="custom_field_value2"><?php esc_html_e('Field2 Value', 'result-management-system-for-institutions')?></label>
											<input type="text" class="form-control" name="custom_field_value2" id="custom_field_value2"
												placeholder="<?php esc_html_e( 'Enter Field2 Value', 'result-management-system-for-institutions' ); ?>">
										</div>
									</div>
									<!-- Custom Field 3 -->
									<div class="form-group row">
										<div class="col-sm-6 mb-2">
											<label for="custom_field_name3"><?php esc_html_e( 'Field3 Name', 'result-management-system-for-institutions')?></label>
											<input type="text" class="form-control" name="custom_field_name3" id="custom_field_name3"
												placeholder="<?php esc_html_e( 'Enter Field3 Name', 'result-management-system-for-institutions' ); ?>">
										</div>
										<div class="col-sm-6 mb-2">
											<label for="custom_field_value3"><?php esc_html_e('Field3 Value', 'result-management-system-for-institutions')?></label>
											<input type="text" class="form-control" name="custom_field_value3" id="custom_field_value3"
												placeholder="<?php esc_html_e( 'Enter Field3 Value', 'result-management-system-for-institutions' ); ?>">
										</div>
									</div>
								</div>
								<!-- Hidden Input Fields  -->
								<input type="hidden" name="hiddenExamYearId" id="hiddenExamYearId">

								<!-- Buttons for Submit and Cancel -->
								<div class="modal-footer">
									<button type="submit" name="addsubmit" class="btn btn-primary">
										<?php esc_html_e( 'Add Exam Name', 'result-management-system-for-institutions' ); ?>
									</button>
									<button type="button" class="btn btn-danger"
										onclick="document.getElementById('addmodal').style.display='none'">
										<?php esc_html_e( 'Cancel', 'result-management-system-for-institutions' ); ?>
									</button>
								</div>
							</form>
						</div>
					</div>
				</div>
			</div>
		</div>
		<?php
	}
}

/**
 * Initializes the ASTGDRMSYS_ExamName_Manager and sets it up for use.
 *
 * Usage:
 * $exam_manager = new ASTGDRMSYS_ExamName_Manager();
 * $exam_manager->astgdrmsys_initialize();
 */
$exam_manager = new ASTGDRMSYS_ExamName_Manager();
$exam_manager->astgdrmsys_initialize();
?>
