<?php

function inoby_register_newsletter_widget() {
  register_widget("Inoby_Newsletter_Widget");
}

function inoby_rest_newsletter_subscribe() {
  /**
   * Sluzi na prepisanie prihlasenia na newsletter na nejaku inu sluzbu ako je mailchimp
   * Staci v hooku zavolat @see wp_send_json_success alebo @see wp_send_json_error
   * @package inobydoc
   */
  do_action("inoby_newsletter_subscribe");

  // Validate reCAPTCHA if configured
  $recaptcha_token = $_POST["recaptcha_token"] ?? "";
  $recaptcha_validation = inoby_validate_recaptcha($recaptcha_token);
  
  if (is_wp_error($recaptcha_validation)) {
    wp_send_json_error([
      "message" => $recaptcha_validation->get_error_message(),
    ], 400);
  }

  $email = $_POST["email"];
  $lname = $_POST["lname"] ?? "";
  $fname = $_POST["fname"] ?? "";
  $merge_fields = [];
  
  // Handle merge fields from the form
  if (isset($_POST["merge_fields"]) && is_array($_POST["merge_fields"])) {
    $merge_fields = $_POST["merge_fields"];
  }
  
  $result = inoby_mailchimp_subscribe($email, $lname, $fname, $merge_fields);
  if (is_wp_error($result)) {
    wp_send_json_error($result->errors, 400);
  } else {
    wp_send_json_success();
  }
}

if (Inoby_Config::newsletter_widget()) {
  require_once INOBY_BASE .
    "/inoby-plugins/newsletter/class-newsletter-widget.php";

  add_action("widgets_init", "inoby_register_newsletter_widget");
  add_action(
    "wp_ajax_nopriv_inoby_newsletter_subscribe",
    "inoby_rest_newsletter_subscribe",
  );
  add_action(
    "wp_ajax_inoby_newsletter_subscribe",
    "inoby_rest_newsletter_subscribe",
  );

  function inoby_newsletter() {
    $widget = new Inoby_Newsletter_Widget();
    $widget->widget(null, null);
  }
}
