<?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 a new exam year in the WordPress admin menu.
 *
 * The script ensures that it is being run within the WordPress context 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_ExamYear_Manager
 *
 * This class is responsible for managing exam years within the All in One Result Management System plugin.
 *
 * @package ResultManagementSystem
 * @subpackage Menu_Files/Exam_Year
 * @since 1.0.0
 */
class ASTGDRMSYS_ExamYear_Manager {

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

	const SUCCESS_MESSAGES = array(
		'edit' => 'Exam Year Updated Successfully',
		'del'  => 'Exam Year Deleted Successfully',
		'add'  => 'Exam Year Added Successfully',
	);

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

		$this->handle_actions();
	}

	/**
	 * Handles various actions related to exam year management.
	 *
	 * This function processes different actions such as adding, updating, or deleting exam years.
	 * It ensures that the appropriate action is taken based on the request parameters.
	 *
	 * @return void
	 */
	private function handle_actions() {
		// Check if this is a POST request
		if ( isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD'] === 'POST' ) {
			check_admin_referer( 'astgdrmsys_exam_year_action', 'astgdrmsys_nonce' );
			if ( ! current_user_can( 'manage_options' ) ) {
				wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'result-management-system-for-institutions' ) );
			}
		}

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

			if ( wp_verify_nonce( $nonce, 'astgdrmsys_exam_year_action' ) && current_user_can( 'manage_options' ) ) {
				$this->delete_exam_year( $delid );
			} else {
				wp_die( esc_html__( 'Unauthorized delete attempt.', 'result-management-system-for-institutions' ) );
			}
		} elseif ( isset( $_POST['updatesubmit'] ) ) {
			$this->update_exam_year();
		} elseif ( isset( $_POST['addsubmit'] ) ) {
			$this->add_exam_year();
		}

		// display 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() {
		foreach ( self::SUCCESS_MESSAGES as $key => $text ) {
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			if ( isset( $_GET[ $key ] ) && $_GET[ $key ] === 'true' ) {
				$this->add_message( 'success', $text );
			}
		}
	}

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

	/**
	 * Deletes an exam year entry from the database.
	 *
	 * @param int $id The ID of the exam year to be deleted.
	 */
	private function delete_exam_year( $id ) {
		// Transaction handling and error catching
		$this->wpdb->query( 'START TRANSACTION' );

		try {
			$this->wpdb->delete( $this->prefix . 'astgdrmsys_exam_year', array( 'id' => $id ), array( '%d' ) );
			$this->wpdb->delete( $this->prefix . 'astgdrmsys_class', array( 'exam_year' => $id ), array( '%d' ) );
			$this->wpdb->query( 'COMMIT' );
			$this->redirect_with_message( 'del' );
		} catch ( Exception $e ) {
			$this->wpdb->query( 'ROLLBACK' );
			$this->add_message( 'error', __( 'Error deleting exam year', 'result-management-system-for-institutions' ) );
		}
	}

	/**
	 * Redirects to a specified action with a message.
	 *
	 * @param string $action The action to redirect to.
	 */
	private function redirect_with_message( $action ) {
		wp_safe_redirect(
			add_query_arg(
				array(
					$action => 'true',
					'page'  => 'astgdrmsys-exam-year',
				),
				admin_url( 'admin.php' )
			)
		);
		exit;
	}

	/**
	 * Updates the exam year in the database.
	 *
	 * This function is responsible for updating the exam year information
	 * in the database. It performs necessary validation and ensures that
	 * the data is correctly updated.
	 *
	 * @return void
	 */
	private function update_exam_year() {
		if ( isset( $_POST['updateexam_year'], $_GET['editid'], $_POST['_wpnonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ), 'astgdrmsys_update_exam_year' ) ) {
			// Sanitize and validate the input
			$id        = absint( wp_unslash( $_GET['editid'] ) );
			$exam_year = sanitize_text_field( wp_unslash( $_POST['updateexam_year'] ) );

			$updated = $this->wpdb->update(
				$this->prefix . 'astgdrmsys_exam_year',
				array( 'exam_year' => $exam_year ),
				array( 'id' => $id ),
				array( '%s' ),
				array( '%d' )
			);

			if ( $updated !== false ) {
				wp_safe_redirect(
					add_query_arg(
						array(
							'page' => 'astgdrmsys-exam-year',
							'edit' => 'true',
						),
						admin_url( 'admin.php' )
					)
				);
				exit;
			}
		} else {
			wp_die( esc_html__( 'Invalid or expired request.', 'result-management-system-for-institutions' ) );
		}
	}


	/**
	 * Adds a new exam year to the system.
	 *
	 * This function handles the logic for adding a new exam year, including
	 * any necessary validation and database operations.
	 *
	 * @return void
	 */
	private function add_exam_year() {
		if (
			isset( $_POST['exam_year'], $_POST['_wpnonce'] ) &&
			wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ), 'astgdrmsys_add_exam_year' )
		) {
			$exam_year = sanitize_text_field( wp_unslash( $_POST['exam_year'] ) );

			$inserted = $this->wpdb->insert(
				$this->prefix . 'astgdrmsys_exam_year',
				array( 'exam_year' => $exam_year ),
				array( '%s' )
			);

			if ( $inserted ) {
				wp_safe_redirect(
					add_query_arg(
						array(
							'page' => 'astgdrmsys-exam-year',
							'add'  => 'true',
						),
						admin_url( 'admin.php' )
					)
				);
				exit;
			}
		} else {
			wp_die( esc_html__( 'Invalid request. Please try again.', 'result-management-system-for-institutions' ) );
		}
	}


	/**
	 * Renders the add exam year page.
	 *
	 * This function is responsible for rendering the user interface for adding a new exam year
	 * within the Result Management System plugin.
	 *
	 * @return void
	 */
	public function render() {
		// Display messages
		foreach ( $this->messages as $message ) {
			printf(
				'<div class="notice notice-%1$s is-dismissible"><p>%2$s</p></div>',
				esc_attr( $message['type'] ),
				esc_html( $message['text'] )
			);
		}

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

	/**
	 * Renders the form for editing an exam year.
	 *
	 * This function generates and displays the HTML form used for editing
	 * an existing exam year in the system.
	 *
	 * @return void
	 */
	private function astgdrmsys_render_edit_form() {
		global $wpdb;

		if ( isset( $_GET['editid'], $_GET['_wpnonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'astgdrmsys_edit_exam_year' ) ) {
			// Sanitize and validate the input
			$id = absint( wp_unslash( $_GET['editid'] ) );

			// Try to get the exam year from the cache
			$cache_key = 'exam_year_' . $id;
			$exam_year = wp_cache_get( $cache_key );

			if ( $exam_year === false ) {
                // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery
				$exam_year = $wpdb->get_row(
					$wpdb->prepare(
						"SELECT * FROM {$wpdb->prefix}astgdrmsys_exam_year WHERE id = %d",
						$id
					)
				);

				wp_cache_set( $cache_key, $exam_year );
			}

			// Check if the exam year exists
			if ( ! $exam_year ) {
				wp_die( esc_html__( 'Exam year not found', 'result-management-system-for-institutions' ) );
			}
		} else {
			wp_die( esc_html__( 'Invalid request.', 'result-management-system-for-institutions' ) );
		}

		?>
		<div class="wrap astgdrmsys-premium-wrap">
			<h1><?php esc_html_e( 'Edit Exam Year', 'result-management-system-for-institutions' ); ?></h1>
			<form method="post" action="">
				<?php wp_nonce_field( 'astgdrmsys_exam_year_action', 'astgdrmsys_nonce' ); ?>
				<?php wp_nonce_field( 'astgdrmsys_update_exam_year' ); ?>
				<table class="form-table">
					<tr>
						<th><label for="updateexam_year"><?php esc_html_e( 'Exam Year', 'result-management-system-for-institutions' ); ?></label></th>
						<td>
							<input type="text"
								name="updateexam_year"
								id="updateexam_year"
								value="<?php echo esc_attr( $exam_year->exam_year ); ?>"
								class="regular-text"
								required>
						</td>
					</tr>
				</table>
				<?php submit_button( __( 'Update Exam Year', '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 view for the exam year.
	 *
	 * This function is responsible for generating and displaying the list view
	 * of exam years in the admin panel.
	 *
	 * @return void
	 */
	private function astgdrmsys_render_list_view() {
		global $wpdb;
		// Try to get the exam years from the cache
		$cache_key  = 'astgdrmsys_exam_years_all';
		$exam_years = wp_cache_get( $cache_key );

		if ( $exam_years === false ) {
			$sanitized_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 * FROM `$sanitized_table` ORDER BY exam_year ASC",
				ARRAY_A
			);

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

		?>
		<div class="wrap astgdrmsys-premium-wrap">
			<div class="premium-page-header">
				<div class="page-header-text">
					<h1><?php esc_html_e( 'Exam Years', 'result-management-system-for-institutions' ); ?></h1>
					<p>Manage the academic/exam years.</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>

			<?php if ( ! empty( $exam_years ) ) : ?>
				<table class="styled-table">
					<thead class="thead-dark">
						<tr>
							<th><?php esc_html_e( 'ID', 'result-management-system-for-institutions' ); ?></th>
							<th><?php esc_html_e( 'Exam Year', 'result-management-system-for-institutions' ); ?></th>
							<th><?php esc_html_e( 'Actions', 'result-management-system-for-institutions' ); ?></th>
						</tr>
					</thead>
					<tbody>
						<?php
						foreach ( $exam_years as $year ) :
							// check if exam year is an object
							if ( is_object( $year ) ) {
								$year = (array) $year;
							}
							?>
							<tr>
								<td><?php echo esc_html( $year['id'] ); ?></td>
								<td><?php echo esc_html( $year['exam_year'] ); ?></td>
								<td>
									<!-- Edit Button -->
									<a href="
									<?php
									echo esc_url(
										wp_nonce_url(
											add_query_arg(
												array(
													'page' => 'astgdrmsys-exam-year',
													'editid' => $year['id'],
												),
												admin_url( 'admin.php' )
											),
											'astgdrmsys_edit_exam_year'
										)
									);
									?>
												"
										class="button button-small">
										<span class="dashicons dashicons-edit"></span>
									</a>
									<!-- Delete Button -->
									<a href="
									<?php
									echo esc_url(
										wp_nonce_url(
											add_query_arg(
												array(
													'page' => 'astgdrmsys-exam-year',
													'delid' => $year['id'],
												),
												admin_url( 'admin.php' )
											),
											'astgdrmsys_exam_year_action',
											'astgdrmsys_nonce'
										)
									);
									?>
												"
										onclick="return confirm('<?php esc_attr_e( 'Are you sure you want to delete this exam year?', '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 exam years found.', 'result-management-system-for-institutions' ); ?></p>
				</div>
			<?php endif; ?>

			<?php $this->astgdrmsys_render_add_modal(); ?>
		</div>
		<?php
	}

	/**
	 * Renders the modal for adding a new exam year.
	 *
	 * This function generates the HTML and necessary scripts for displaying
	 * a modal dialog where users can input details to add a new exam year.
	 *
	 * @return void
	 */
	private function astgdrmsys_render_add_modal() {
		?>
		<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 Exam Year', 'result-management-system-for-institutions' ); ?></h2>
				<form method="post" action="">
					<?php wp_nonce_field( 'astgdrmsys_exam_year_action', 'astgdrmsys_nonce' ); ?>
					<?php wp_nonce_field( 'astgdrmsys_add_exam_year' ); ?>
					<div class="form-field">
						<label for="exam_year"><?php esc_html_e( 'Exam Year:', 'result-management-system-for-institutions' ); ?></label>
						<input type="text" name="exam_year" id="exam_year" required>
					</div>
					<div class="button-group">
						<?php submit_button( __( 'Add Exam Year', '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 ASTGDRMSYS_ExamYear_Manager class.
 *
 * The ASTGDRMSYS_ExamYear_Manager class is responsible for managing exam years within the plugin.
 * The render method is called to display the relevant interface or data.
 *
 * @package ResultManagementSystemResultManagement
 * @subpackage Menu_Files
 * @since 1.0.0
 */
$exam_year_manager = new ASTGDRMSYS_ExamYear_Manager();
$exam_year_manager->render();
?>