<?php

namespace Salesloo;

use WP_Error;

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

/**
 * Salesloo Admin Ajax
 */
class Admin_Ajax
{
    private $url;

    /**
     * construct
     */
    public function __construct()
    {
        $this->url = admin_url('admin-ajax.php');
    }

    /**
     * url
     *
     * @param  string $key
     * @return string
     */
    public function url($key = false)
    {
        $args = [];

        if ($key && is_string($key)) {
            $args = [
                'action' => $key,
                'nonce' => wp_create_nonce($key)
            ];
        }

        if ($key && is_array($key)) {
            $args = (array)$key;
        }

        if ($args) return add_query_arg($args, $this->url);

        return $this->url;
    }

    /**
     * verify_nonce
     *
     * @param  string $nonce
     * @param  string $key
     * @return void
     */
    public function verify_nonce($nonce, $key)
    {
        if (!wp_verify_nonce($nonce, $key)) {
            $data = new WP_Error('500', 'Invalid nonce');
            wp_send_json_error($data, 500);
        }
    }
}
