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

/**
 * Class ASTGDRMSYS_Delete_Record
 *
 * This class handles the deletion of records in the RMS (Result Management System for Institutions) plugin.
 *
 * @package ResultManagementSystem
 * @subpackage Menu_Files
 * @since 1.0.0
 */
class ASTGDRMSYS_Delete_Record {

	private $wpdb;
	private $prefix;

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

	/**
	 * Deletes a record with the given ID.
	 *
	 * @param int $id The ID of the record to delete.
	 * @return void
	 */
	public function deleteRecord( $id ) {
		// Sanitize and validate the student ID
		$id = filter_var( $id, FILTER_SANITIZE_NUMBER_INT );
		
		if ( $id ) {
			// Delete the associated marks first
			$deleted_marks = $this->wpdb->delete( "{$this->prefix}astgdrmsys_mark", array( 'sid' => $id ) );
	
			// Delete the student record
			$deleted_student = $this->wpdb->delete( "{$this->prefix}astgdrmsys_student_result", array( 'sid' => $id ) );
	
			// A successful delete returns the number of rows affected (0 or more). A failure returns boolean false.
			// check if either operation was successful
			if ( $deleted_marks !== false || $deleted_student !== false ) {
				// The operation was successful, even if 0 rows were affected.
				$this->redirectWithMessage( 'astgdrmsys-all-students', true );
			} else {
				// Both operations failed with a database error.
				$this->redirectWithMessage( 'astgdrmsys-all-students', false );
			}
		} else {
			// The ID was invalid from the start
			$this->redirectWithMessage( 'astgdrmsys-all-students', 'invalid' );
		}
	}

	/**
	 * Redirects the user with a status message.
	 *
	 * @param string      $page_slug The slug of the admin page to redirect to.
	 * @param bool|string $status    The status of the operation (true for success, false for failure, 'invalid' for bad ID).
	*/
	private function redirectWithMessage( string $page_slug, $status ): void {
		$status_param = '';
		if ( $status === true ) {
			$status_param = 'del=true';
		} elseif ( $status === false ) {
			$status_param = 'del=false';
		} elseif ( $status === 'invalid' ) {
			$status_param = 'del=invalid';
		}
		// redirect safely
		$redirect_url = admin_url( "admin.php?page={$page_slug}&{$status_param}" );
		wp_safe_redirect( $redirect_url );
		exit;
	}
}

/**
 * Deletes a student record based on the provided ID.
 *
 * This script initializes an instance of the ASTGDRMSYS_Delete_Record class and calls the deleteRecord method
 * to remove a student record from the database. The ID of the student record to be deleted is retrieved
 * from the URL parameters ($_GET['id']).
 *
 * @package ResultManagementSystem
 * @subpackage Menu_Files
 * @since 1.0.0
 *
 * @see ASTGDRMSYS_Delete_Record::deleteRecord()
 *
 * @param int $_GET['id'] The ID of the student record to be deleted.
 */
$astgdrmsys_studentManager = new ASTGDRMSYS_Delete_Record();

if ( isset( $_GET['id'], $_GET['_wpnonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'astgdrmsys_delete_record' ) ) {
	$id = absint( wp_unslash( $_GET['id'] ) );
	$astgdrmsys_studentManager->deleteRecord( $id );
} else {
	wp_die( esc_html( __( 'Invalid or unauthorized request. Please refresh and try again.', 'result-management-system-for-institutions' ) ) );
}
