<?php

/**
 * Ajax module.
 *
 * @package northmill-online-shared
 */
declare (strict_types=1);
namespace Northmill_Online_Shared_Sync\Northmill_Online_Shared\Modules;

use Northmill_Online_Shared_Sync\Northmill_Online_Shared\Modules\Ajax\Models\Request_Model;
use Northmill_Online_Shared_Sync\Northmill_Online_Shared\Modules\Assets\Asset_Location_Enum;
defined('ABSPATH') || exit;
/**
 * Class for handling ajax actions.
 */
class Ajax_Module extends Abstract_Module
{
    /**
     * Module setup.
     *
     * @return void
     */
    public function setup(): void
    {
        $script_registered = $this->shared->globals->get('ajax_script_registered');
        if (!$script_registered) {
            $this->shared->assets->enquer->register_script('ajax', Asset_Location_Enum::BOTH, array(), array($this, 'get_script_localization'), \true, \true);
            $this->shared->globals->set('ajax_script_registered', \true);
        }
    }
    /**
     * All ajax actions.
     *
     * @var Request_Model[]
     */
    private array $ajax_actions = array();
    /**
     * Add action.
     *
     * @param string       $key Unique key for action.
     * @param array        $callback AJAX callback.
     * @param bool         $is_public Whether action is public.
     * @param string|null  $nonce Nonce name.
     * @param false|string $nonce_query_param Nonce query parameter.
     */
    public function add_action(string $key, array $callback, bool $is_public = \false, ?string $nonce = null, false|string $nonce_query_param = \false): void
    {
        $this->ajax_actions[$key] = new Request_Model($key, $callback, $is_public, $nonce, $nonce_query_param);
    }
    /**
     * Get action.
     *
     * @param string $key Key.
     *
     * @return Request_Model|null
     */
    public function get_action(string $key): ?Request_Model
    {
        return $this->ajax_actions[$key] ?? null;
    }
    /**
     * Get localized script data.
     *
     * @return array
     */
    public function get_script_localization(): array
    {
        return array('ajaxurl' => admin_url('admin-ajax.php'), 'l10n' => array('done' => __('Done', 'northmill-online-shared'), 'error' => __('Error message', 'northmill-online-shared')));
    }
}
