<?php
/**
 * WeCodeArt Framework.
 *
 * WARNING: This file is part of the core WeCodeArt Framework. DO NOT edit this file under any circumstances.
 * Please do all modifications in the form of a child theme.
 *
 * @package 	WeCodeArt Framework
 * @subpackage 	Notifications/Ajax
 * @copyright   Copyright (c) 2025, WeCodeArt Framework
 * @since 		5.0.0
 * @version		6.3.7
 */

namespace WeCodeArt\Admin\Notifications;

defined( 'ABSPATH' ) || exit;

use WeCodeArt\Admin\Request\Async;
use WeCodeArt\Admin\Notifications;
use WeCodeArt\Admin\Notifications\Notification;
use WeCodeArt\Config\Traits\Singleton;

/**
 * This class handles a post request being send to a given endpoint.
 */
class Ajax extends Async {

    /**
     * Prefix
     *
     * @var     string
     * @access  protected
     */
    protected $prefix = 'wca';

    /**
     * Action
     *
     * @var     string
     * @access  protected
     */
    protected $action = 'dismiss_notification';

    /**
     * Handle
     * 
     * @return  mixed
     */
    protected function handle() {
        $notification_id = filter_input( INPUT_POST, 'notification' );

		if ( empty( $notification_id ) ) {
            wp_send_json_error( [
                'message' => esc_html__( 'Missing notification id', 'wecodeart' )
            ] );
        }

        check_ajax_referer( $notification_id, 'nonce' );
            
        $notification_center = Notifications::get_instance();
        $notification = $notification_center->get_notification_by_id( $notification_id );
        
		if ( ( $notification instanceof Notification ) === false ) {
			// Permit legacy.
			$notification = new Notification( '', [
				'id'            => $notification_id,
				'dismissal_key' => $notification_id,
			] );
		}

		if ( $notification_center::maybe_dismiss_notification( $notification ) ) {
			wp_send_json_success( [
                'message' => esc_html__( 'Notification dismissed', 'wecodeart' )
            ] );
		}

		wp_send_json_error( [
            'message' => esc_html__( 'Failed to dismiss notification', 'wecodeart' )
        ] );
    }
}