<?php
/**
 * Base Action Handler Class
 *
 * This base class provides common functionality for handling admin actions,
 * including nonce verification and permission checks for form submissions
 * and AJAX requests.
 *
 * @package miniorange-sms-order-notification-otp-verification/objects
 */

namespace WCSMSOTP\Objects;

use WCSMSOTP\Helper\MoConstants;
use WCSMSOTP\Helper\MoMessages;
use WCSMSOTP\Helper\MoUtility;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

if ( ! class_exists( 'BaseActionHandler' ) ) {
	/**
	 * Base Action Handler Class
	 *
	 * This is the base class that provides common functionality for handling
	 * admin actions with proper security checks including nonce verification
	 * and capability checks.
	 */
	class BaseActionHandler {

		/**
		 * Nonce value to check if a valid submission has been made.
		 *
		 * @var string
		 */
		protected $nonce;

		/**
		 * Constructor
		 */
		protected function __construct() {}

		/**
		 * Checks if the request made is a valid request or not.
		 *
		 * The user trying to make the request should have the manage_options
		 * capability set and the nonce should be valid. This is to make sure
		 * only admins are able to save settings.
		 *
		 * @return bool True if the request is valid, otherwise calls wp_die().
		 */
		protected function is_valid_request() {
			if ( ! current_user_can( 'manage_options' ) || ! check_admin_referer( $this->nonce ) ) {
				wp_die( esc_html( MoMessages::showMessage( MoMessages::INVALID_OP ) ) );
			}
			return true;
		}

		/**
		 * Checks if the request made is a valid ajax request or not.
		 *
		 * Only checks the nonce value for now.
		 *
		 * @param string $key The key which has the nonce value.
		 * @return void Calls wp_send_json() if invalid, otherwise returns nothing.
		 */
		protected function is_valid_ajax_request( $key ) {
			if ( ! check_ajax_referer( $this->nonce, $key ) ) {
				wp_send_json(
					MoUtility::create_json(
						MoMessages::showMessage( MoMessages::INVALID_OP ),
						MoConstants::ERROR_JSON_TYPE
					)
				);
			}
		}

		/**
		 * Getter for nonce value.
		 *
		 * @return string The nonce value.
		 */
		public function get_nonce_value() {
			return $this->nonce;
		}
	}
}
