<?php

namespace Elementor_Pay_Addons\Editor\API;

if (!defined('ABSPATH')) {
  exit();
}

use Elementor_Pay_Addons\Stripe\Stripe_API;
use Elementor_Pay_Addons\Stripe\Stripe_Helper;

class Ajax_API_Handler
{
  public function __construct()
  {
    add_action('wp_ajax_epa_search_stripe_prices', [$this, 'ajax_search_prices']);
    add_action('wp_ajax_nopriv_epa_search_stripe_prices', [$this, 'ajax_search_prices']);
  }

  public function ajax_search_prices()
  {
    check_ajax_referer('epa_search_stripe_prices_nonce', 'nonce');

    if (!current_user_can('edit_posts')) {
      wp_send_json_error('Unauthorized');
    }

    $search_term = isset($_GET['term']) ? sanitize_text_field($_GET['term']) : '';

    $results = Stripe_Helper::get_price_item_list($search_term);  

    wp_send_json([ 'results' => $results ]);
  }
}
