<?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 ensures that the file is not accessed directly by checking if the ABSPATH constant is defined.
 * If ABSPATH is not defined, the script exits to prevent unauthorized access.
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

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

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

	/**
	 * Constructor for the class.
	 *
	 * This method is called when an instance of the class is created.
	 */
	public function __construct() {
		global $wpdb;
		$this->wpdb   = $wpdb;
		$this->prefix = $wpdb->prefix;

		$this->handle_actions();
	}

	/**
	 * Handles various actions related to sections.
	 *
	 * This function processes different actions that can be performed on sections,
	 * such as adding, updating, or deleting sections. It ensures that the appropriate
	 * action is taken based on the input parameters and performs necessary validations
	 * and operations.
	 *
	 * @return void
	 */
	private function handle_actions() {
		// Correctly check if REQUEST_METHOD is set and equals POST
		if ( isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD'] === 'POST' ) {
			check_admin_referer( 'astgdrmsys_section_action', 'astgdrmsys_section_nonce' );
		}

		// Handle delete action
		if ( isset( $_GET['delid'], $_GET['astgdrmsys_nonce'] ) ) {
			$delid = absint( $_GET['delid'] );
			$nonce = sanitize_text_field( wp_unslash( $_GET['astgdrmsys_nonce'] ) );

			// Verify nonce and user capability before deleting
			if ( wp_verify_nonce( $nonce, 'astgdrmsys_section_action' ) && current_user_can( 'manage_options' ) ) {
				$this->delete_section( $delid );
			} else {
				wp_die( esc_html__( 'Unauthorized delete attempt.', 'result-management-system-for-institutions' ) );
			}
		}

		// Handle form submissions
		if ( isset( $_POST['updatesubmit'] ) ) {
			$this->update_section();
		} elseif ( isset( $_POST['addsubmit'] ) ) {
			$this->add_section( $this->wpdb );
		}

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


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

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

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

	/**
	 * Retrieves the list of departments.
	 *
	 * This function fetches and returns an array of departments.
	 *
	 * @return array The list of departments.
	 */
	private function get_departments() {

        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery
		$sql = "SELECT id, department
              FROM {$this->prefix}astgdrmsys_department
              ORDER BY department ASC";
        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery
		return $this->wpdb->get_results( $sql, ARRAY_A );
	}

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

	/**
	 * Retrieves the list of sections.
	 *
	 * This function fetches and returns an array of sections.
	 *
	 * @return array The list of sections.
	 */
	private function get_sections( int $department_id = 0, string $class_name = '' ) {
		$where  = array( '1=1' );
		$params = array();

		if ( $department_id > 0 ) {
			$where[]  = 's.department = %d';
			$params[] = $department_id;
		}

		if ( '' !== $class_name ) {
			$where[]  = 's.classname = %s';
			$params[] = $class_name;
		}

		$sql = "SELECT s.id, s.section, s.classname, d.department
				FROM {$this->prefix}astgdrmsys_section s
				JOIN {$this->prefix}astgdrmsys_department d ON s.department = d.id
				WHERE " . implode( ' AND ', $where ) . '
				ORDER BY s.id ASC';

		if ( ! empty( $params ) ) {
			$sql = $this->wpdb->prepare( $sql, $params );
		}

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

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

		try {
			$this->wpdb->delete(
				$this->prefix . 'astgdrmsys_section',
				array( 'id' => $id ),
				array( '%d' )
			);

			$this->wpdb->query( 'COMMIT' );
			wp_safe_redirect(
				add_query_arg(
					array(
						'page' => 'astgdrmsys-section',
						'del'  => 'true',
					),
					admin_url( 'admin.php' )
				)
			);
			exit;
		} catch ( Exception $e ) {
			$this->wpdb->query( 'ROLLBACK' );
			$this->add_message( 'error', 'Error deleting section: ' . esc_html( $e->getMessage() ) );
		}
	}

	/**
	 * Updates a section with new data.
	 *
	 * This function is responsible for updating the details of a section
	 * in the database or any other storage mechanism used by the plugin.
	 *
	 * @return void
	 */
	private function update_section() {
		// check if the required fields are set and nonce is valid
		if (
			! isset( $_POST['section_id'], $_POST['updatesection'], $_POST['updatedepartment'], $_POST['updateHiddenClassname'], $_POST['_wpnonce'] ) ||
			! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ), 'astgdrmsys_update_section' )
		) {
			wp_die( esc_html__( 'Invalid request.', 'result-management-system-for-institutions' ) );
		}
		// Validate and sanitize input data
		$id         = absint( wp_unslash( $_POST['section_id'] ) );
		$section    = sanitize_text_field( wp_unslash( $_POST['updatesection'] ) );
		$department = absint( wp_unslash( $_POST['updatedepartment'] ) );
		$classname  = sanitize_text_field( wp_unslash( $_POST['updateHiddenClassname'] ) );

		$updated = $this->wpdb->update(
			$this->prefix . 'astgdrmsys_section',
			array(
				'section'    => $section,
				'department' => $department,
				'classname'  => $classname,
			),
			array( 'id' => $id ),
			array( '%s', '%d', '%s' ),
			array( '%d' )
		);

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


	/**
	 * Adds a new section.
	 *
	 * This function is responsible for adding a new section to the system.
	 *
	 * @return void
	 */
	private function add_section( $wpdb ) {
		if (
			! isset( $_POST['section'], $_POST['departmentadd'], $_POST['hiddenclassname'], $_POST['_wpnonce'] ) ||
			! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ), 'astgdrmsys_add_section' )
		) {
			wp_die( esc_html__( 'Invalid form submission.', 'result-management-system-for-institutions' ) );
		}

		$section    = sanitize_text_field( wp_unslash( $_POST['section'] ) );
		$department = absint( wp_unslash( $_POST['departmentadd'] ) );
		$classname  = sanitize_text_field( wp_unslash( $_POST['hiddenclassname'] ) );

		// Check for duplicates based on section name, department, and class name
		$existingSection = $wpdb->get_row( // phpcs:ignore WordPress.DB.DirectDatabaseQuery
			$wpdb->prepare(
				"SELECT * FROM {$wpdb->prefix}astgdrmsys_section WHERE section = %s AND department = %d AND classname = %s",
				$section,
				$department,
				$classname
			)
		);

		if ( $existingSection ) {
			// Duplicate found, return an error message
			$this->add_message( 'error', 'Error: A section with the same name already exists in this department and class.' );
			return; // Stop further execution
		}

		// Proceed to insert the new section
		$inserted = $this->wpdb->insert(
			$this->prefix . 'astgdrmsys_section',
			array(
				'section'    => $section,
				'department' => $department,
				'classname'  => $classname,
			),
			array(
				'%s', // section
				'%d', // department
				'%s',  // classname
			)
		);

		if ( $inserted ) {
			wp_safe_redirect(
				add_query_arg(
					array(
						'page' => 'astgdrmsys-section',
						'add'  => 'true',
					),
					admin_url( 'admin.php' )
				)
			);
			exit;
		} else {
			$this->add_message( 'error', 'Failed to add section' );
		}
	}

	/**
	 * Renders the section.
	 *
	 * This function is responsible for rendering the section in the plugin.
	 *
	 * @return void
	 */
	public function astgdrmsys_renderSection() {
		// Display messages
		foreach ( $this->messages as $message ) { ?>
			<div class="notice notice-<?php echo esc_attr( $message['type'] ); ?> is-dismissible">
				<p><?php echo esc_html( $message['message'] ); ?></p>
			</div>
			<?php
		}

        // phpcs:ignore WordPress.Security.NonceVerification
		if ( isset( $_GET['editid'] ) ) {
			$this->astgdrmsys_render_edit_form();
		} else {
			$this->astgdrmsys_render_section_list();
		}
	}

	/**
	 * Renders the edit form for the section.
	 *
	 * This function generates and displays the HTML form used for editing a section.
	 *
	 * @return void
	 */
	private function astgdrmsys_render_edit_form() {

		global $wpdb;

		if ( ! isset( $_GET['astgdrmsys_section_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['astgdrmsys_section_nonce'] ) ), 'astgdrmsys_section_action' ) ) {
			$this->add_message( 'error', __( 'Invalid request. Please try again.', 'result-management-system-for-institutions' ) );
			return;
		}

		// $id = absint(wp_unslash($_GET['editid']));
		$id            = isset( $_GET['editid'] ) ? absint( $_GET['editid'] ) : 0;
		$section_table = esc_sql( $this->prefix . 'astgdrmsys_section' );
		// Fetch the section details
		$section = $wpdb->get_row( // phpcs:ignore WordPress.DB.DirectDatabaseQuery
			$wpdb->prepare(
                // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
				"SELECT * FROM $section_table WHERE id = %d",
				$id
			),
			ARRAY_A
		);

		if ( ! $section ) {
			wp_die( 'Section not found' );
		}

		$departments = $this->get_departments();
		$classes     = $this->get_classes();
		?>
		<div class="wrap astgdrmsys-premium-wrap">
			<h1><?php esc_html_e( 'Edit Section', 'result-management-system-for-institutions' ); ?></h1>
			<form method="post" action="">
				<?php wp_nonce_field( 'astgdrmsys_section_action', 'astgdrmsys_section_nonce' ); ?>
				<?php wp_nonce_field( 'astgdrmsys_update_section' ); ?>
				<input type="hidden" name="section_id" value="<?php echo esc_attr( $id ); ?>">

				<table class="form-table">
					<tr>
						<th><label for="updatesection"><?php esc_html_e( 'Section Name', 'result-management-system-for-institutions' ); ?></label></th>
						<td>
							<input type="text" name="updatesection" id="updatesection"
								value="<?php echo esc_attr( $section['section'] ); ?>"
								class="regular-text" required>
						</td>
					</tr>
					<tr>
						<th><label for="updateHiddenClassname"><?php esc_html_e( 'Class', 'result-management-system-for-institutions' ); ?></label></th>
						<td>
							<select name="updateHiddenClassname" id="updateHiddenClassname" 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['class'] ); ?>" <?php selected( $section['classname'], $class['class'] ); ?>>
										<?php echo esc_html( $class['class'] ); ?>
									</option>
								<?php endforeach; ?>
							</select>
						</td>
					</tr>
					<tr>
						<th><label for="updatedepartment"><?php esc_html_e( 'Department', 'result-management-system-for-institutions' ); ?></label></th>
						<td>
							<select name="updatedepartment" id="updatedepartment" required>
								<?php
								foreach ( $departments as $dept ) :
									// Convert $dept to array if it's an object
									if ( is_object( $dept ) ) {
										$dept = (array) $dept;
									}
									?>
									<option value="<?php echo esc_attr( $dept['id'] ); ?>"
										<?php selected( $section['department'], $dept['id'] ); ?>>
										<?php echo esc_html( $dept['department'] ); ?>
									</option>
								<?php endforeach; ?>
							</select>
						</td>
					</tr>
				</table>
				<?php submit_button( __( 'Update Section', 'result-management-system-for-institutions' ), 'primary', '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>
			</form>
		</div>
		<?php
	}

	/**
	 * Renders the list of sections.
	 *
	 * This private method is responsible for generating and displaying
	 * the list of sections in the plugin's admin menu.
	 *
	 * @return void
	 */
	private function astgdrmsys_render_section_list() {
		$departments = $this->get_departments();
		$classes     = $this->get_classes();
		$filter_department = isset( $_GET['filter_department'] ) ? absint( wp_unslash( $_GET['filter_department'] ) ) : 0;
		$filter_class      = isset( $_GET['filter_class'] ) ? sanitize_text_field( wp_unslash( $_GET['filter_class'] ) ) : '';
		$sections          = $this->get_sections( $filter_department, $filter_class );
		?>
		<div class="wrap astgdrmsys-premium-wrap">
			<div class="premium-page-header">
				<div class="page-header-text">
					<h1><?php esc_html_e( 'Sections', 'result-management-system-for-institutions' ); ?></h1>
					<p>Manage the sections across all classes.</p>
				</div>
				<div class="page-header-actions">
					<button onclick="document.getElementById('addmodal').style.display='block'" 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>

			<form method="get" class="astgdrmsys-section-filter premium-filter-form">
				<input type="hidden" name="page" value="astgdrmsys-section">
				<div class="filter-group">
					<label><?php esc_html_e( 'Department', 'result-management-system-for-institutions' ); ?></label>
					<select name="filter_department" class="premium-input">
						<option value="0"><?php esc_html_e( 'All Departments', 'result-management-system-for-institutions' ); ?></option>
						<?php foreach ( $departments as $department ) : ?>
							<option value="<?php echo esc_attr( $department['id'] ); ?>" <?php selected( $filter_department, (int) $department['id'] ); ?>>
								<?php echo esc_html( $department['department'] ); ?>
							</option>
						<?php endforeach; ?>
					</select>
				</div>
				<div class="filter-group">
					<label><?php esc_html_e( 'Class', 'result-management-system-for-institutions' ); ?></label>
					<select name="filter_class" class="premium-input">
						<option value=""><?php esc_html_e( 'All Classes', 'result-management-system-for-institutions' ); ?></option>
						<?php foreach ( $classes as $class ) : ?>
							<option value="<?php echo esc_attr( $class['class'] ); ?>" <?php selected( $filter_class, $class['class'] ); ?>>
								<?php echo esc_html( $class['class'] ); ?>
							</option>
						<?php endforeach; ?>
					</select>
				</div>
				<div class="filter-actions">
					<?php submit_button( __( 'Filter', 'result-management-system-for-institutions' ), 'secondary', '', false, array('class' => 'hero-btn primary-btn', 'style' => 'margin:0;') ); ?>
					<a class="hero-btn secondary-btn" style="background:#e2e8f0;color:#334155;border:none;margin:0;" href="<?php echo esc_url( admin_url( 'admin.php?page=astgdrmsys-section' ) ); ?>">
						<?php esc_html_e( 'Reset', 'result-management-system-for-institutions' ); ?>
					</a>
				</div>
			</form>

			<?php if ( ! empty( $sections ) ) : ?>
				<table class="styled-table">
					<thead>
						<tr>
							<th><?php esc_html_e( 'ID', 'result-management-system-for-institutions' ); ?></th>
							<th><?php esc_html_e( 'Section', 'result-management-system-for-institutions' ); ?></th>
							<th><?php esc_html_e( 'Department', 'result-management-system-for-institutions' ); ?></th>
							<th><?php esc_html_e( 'Class', 'result-management-system-for-institutions' ); ?></th>
							<th><?php esc_html_e( 'Actions', 'result-management-system-for-institutions' ); ?></th>
						</tr>
					</thead>
					<tbody>
						<?php
						foreach ( $sections as $section ) :
							// Convert $section to array if it's an object
							if ( is_object( $section ) ) {
								$section = (array) $section;
							}
							$cache_key = wp_create_nonce( 'astgdrmsys_section_action' );
							?>
							<tr>
								<td><?php echo esc_html( $section['id'] ); ?></td>
								<td><?php echo esc_html( $section['section'] ); ?></td>
								<td><?php echo esc_html( $section['department'] ); ?></td>
								<td><?php echo esc_html( $section['classname'] ); ?></td>
								<td>
									<a href="
									<?php
									echo esc_url(
										add_query_arg(
											array(
												'page'   => 'astgdrmsys-section',
												'editid' => $section['id'],
												'astgdrmsys_section_nonce' => $cache_key,
											)
										)
									);
									?>
												"
										class="button button-small">
										<span class="dashicons dashicons-edit"></span>
									</a>
									<a href="
									<?php
									echo esc_url(
										add_query_arg(
											array(
												'page'  => 'astgdrmsys-section',
												'delid' => $section['id'],
												'astgdrmsys_nonce' => $cache_key,
											),
											admin_url( 'admin.php' )
										)
									);
									?>
												"
										onclick="return confirm('<?php echo esc_attr__( 'Are you sure you want to delete this section?', 'result-management-system-for-institutions' ); ?>');"
										class="button button-small button-link-delete">
										<span class="dashicons dashicons-trash"></span>
									</a>
								</td>
							</tr>
						<?php endforeach; ?>
					</tbody>
				</table>
			<?php else : ?>
				<div class="notice notice-warning">
					<p><?php esc_html_e( 'No sections found.', 'result-management-system-for-institutions' ); ?></p>
				</div>
			<?php endif; ?>

			<!-- Add Section Modal -->
			<?php $this->astgdrmsys_render_add_modal( $departments, $classes ); ?>
		</div>
		<?php
	}

	/**
	 * Renders the modal for adding a new section.
	 *
	 * @param array $departments An array of departments to be included in the modal.
	 */
	private function astgdrmsys_render_add_modal( $departments, $classes ) {
		?>
		<div id="addmodal" class="modal">
			<div class="modal-content">
				<span class="close"
					onclick="document.getElementById('addmodal').style.display='none'">&times;</span>
				<h2><?php esc_html_e( 'Add Section', 'result-management-system-for-institutions' ); ?></h2>
				<form method="post" action="">
					<?php wp_nonce_field( 'astgdrmsys_section_action', 'astgdrmsys_section_nonce' ); ?>
					<?php wp_nonce_field( 'astgdrmsys_add_section' ); ?>
					<div class="form-field">
						<label for="section"><?php esc_html_e( 'Section Name:', 'result-management-system-for-institutions' ); ?></label>
						<input type="text" name="section" id="section" required class="regular-text">
					</div>
					<div class="form-field">
						<label for="hiddenclassname"><?php esc_html_e( 'Class:', 'result-management-system-for-institutions' ); ?></label>
						<select name="hiddenclassname" id="hiddenclassname" required>
							<option value="" selected 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['class'] ); ?>"><?php echo esc_html( $class['class'] ); ?></option>
							<?php endforeach; ?>
						</select>
					</div>
					<div class="form-field">
						<label for="departmentadd"><?php esc_html_e( 'Department:', 'result-management-system-for-institutions' ); ?></label>
						<select name="departmentadd" id="departmentadd"
							required>
							<option value="" selected disabled><?php esc_html_e( 'Select a Department', 'result-management-system-for-institutions' ); ?></option>
							<?php
							foreach ( $departments as $dept ) :
								// Convert $dept to array if it's an object
								if ( is_object( $dept ) ) {
									$dept = (array) $dept;
								}
								?>
								<option value="<?php echo esc_attr( $dept['id'] ); ?>">
									<?php echo esc_html( $dept['department'] ); ?>
								</option>
							<?php endforeach; ?>
						</select>
					</div>
					<div class="button-group">
						<?php submit_button( __( 'Add Section', 'result-management-system-for-institutions' ), 'primary', 'addsubmit' ); ?>
						<button type="button" class="button"
							onclick="document.getElementById('addmodal').style.display='none'">
							<?php esc_html_e( 'Cancel', 'result-management-system-for-institutions' ); ?>
						</button>
					</div>
				</form>
			</div>
		</div>
		<?php
	}
}

/**
 *
 * This script initializes and renders the section management page.
 *
 * It creates an instance of the ASTGDRMSYS_Section_Manager class and calls its render method.
 *
 * @package ResultManagementSystem
 * @subpackage Section
 */
// Initialize and render the page
$section_manager = new ASTGDRMSYS_Section_Manager();
$section_manager->astgdrmsys_renderSection();
?>
