<?php

namespace Inoby\WPBS;

use Inoby_Config;

class WPBS_Search {
  public function init_hooks() {
    add_filter("wpbs_search_resuts_html", [$this, "set_search_results"], 10, 2);
    add_filter("wpbs_shortcode_search_widget_output", [$this, "add_enable_filter_input"]);

    if ((Inoby_Config::wpbs_post_search()["capacity_filter"] ?? false) && (Inoby_Config::wpbs_extend() ?? false)) {
      add_filter("wpbs_shortcode_search_widget_output", [$this, "add_enable_maximum_capacity_filter_input"]);
      add_filter("inoby_accommodation_card_wrapper_attributes", [$this, "add_accomodation_capacity_to_card"], 10, 2);
      add_action("inoby_accommodation_card_before_image", [$this, "add_max_capacity_message_to_card"]);
    }
  }

  public function set_search_results($output, $data) {
    $post_id = $data["post_id"];
    $output = "";

    if ($post_id) {
      $output = "<input class=\"wpbs-post-id\" type=\"hidden\" value=\"$post_id\"/>";
    }

    return $output;
  }

  public function add_enable_filter_input($output) {
    $output .= "<input class=\"wpbs-enable-search-posts\" type=\"hidden\" value=\"true\"/>";
    return $output;
  }

  public function add_enable_maximum_capacity_filter_input($output) {
    $output .= "<input class=\"wpbs-enable-maximum-capacity-filter\" type=\"hidden\" value=\"true\"/>";
    return $output;
  }

  public function add_max_capacity_message_to_card(int $post_id) {
    $capacity = rwmb_meta("accommodation_maximum_capacity", [], $post_id);
    if (empty($capacity ?? "")) {
      $capacity = 1;
    }
    echo '<div class="max-capacity-message">' . __("Max. kapacita je ", "inoby") . " $capacity " . ($capacity < 5 ? __("osoby", "inoby") : __("osôb", "inoby")) . "</div>";
  }

  public function add_accomodation_capacity_to_card(array $attrs, int $post_id) {
    $capacity = rwmb_meta("accommodation_maximum_capacity", [], $post_id);
    if (empty($capacity ?? "")) {
      $capacity = 1;
    }
    $attrs["wpbs-maximum-capacity"] = $capacity;

    return $attrs;
  }
}
