<?php

namespace Tourfic\Core;

// do not allow direct access
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

abstract class TF_Notice {

    protected string $type;
    protected string $notice_id;

	public function __construct() {

		if ( $this->type == 'admin_notice' ) {
			add_action( 'admin_notices', array( $this, 'tf_plugin_admin_notice' ) );
			add_action( 'wp_ajax_tf_disable_critical_update_admin_notice', array( $this, 'tf_disable_critical_update_admin_notice' ) );
		} else if ( $this->type == 'update_notice' ) {
			add_action( 'in_plugin_update_message-tourfic/tourfic.php', array( $this, 'tf_in_plugin_update_message' ), 10, 2 );
		} else if ( $this->type == 'plugin_row_notice' ) {
			add_action( 'after_plugin_row_tourfic/tourfic.php', array( $this, 'tf_in_plugin_update_message' ), 10, 2 );
		}
	}

	protected function tf_notice_ajax_nonce_action() {
		return 'tf_notice_nonce';
	}

	protected function tf_validate_notice_ajax_request() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error(
				array( 'message' => esc_html__( 'Unauthorized request.', 'tourfic' ) ),
				403
			);
		}

		$nonce = isset( $_REQUEST['nonce'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['nonce'] ) ) : '';
		if ( empty( $nonce ) || ! wp_verify_nonce( $nonce, $this->tf_notice_ajax_nonce_action() ) ) {
			wp_send_json_error(
				array( 'message' => esc_html__( 'Invalid security token.', 'tourfic' ) ),
				403
			);
		}
	}

	function tf_disable_critical_update_admin_notice() {
		$this->tf_validate_notice_ajax_request();

		$notice_id = ! empty( $this->notice_id ) ? $this->notice_id : 'tf_dismiss_222';
		update_option( $notice_id, 1 );

		wp_die();
	}

    abstract function tf_plugin_admin_notice( );
    abstract function tf_in_plugin_update_message( $data, $response );

}
