<?php

/**
 * Oznacit bookingy ako volne ked admin vymaze rezervaciu
 */
add_action(
  "wpbs_update_booking",
  function ($booking_id, $data) {
    if (($data["status"] ?? "") != "trash") {
      return;
    }

    global $wpdb;
    $db = new WPBS_Object_DB_Events();
    $legends_db = new WPBS_Object_DB_Legend_Items();
    $table = $db->table_name;

    $results = $wpdb->get_results("SELECT id FROM $table WHERE booking_id = $booking_id", OBJECT);
    $ids = $results
      ? array_map(function ($row) {
        return $row->id;
      }, $results)
      : [];

    if (count($ids)) {
      $booking = wpbs_get_booking($booking_id);
      $legends = $legends_db->get_legend_items(["calendar_id" => $booking->get("calendar_id")]);
      $default_legend_item = array_first_or_default($legends, fn($item) => $item->get("is_default"));

      if ($default_legend_item) {
        foreach ($ids as $event_id) {
          $db->update($event_id, ["legend_item_id" => $default_legend_item->get("id")]);
        }
      }
    }
  },
  10,
  2
);

/**
 * Zobrazovanie datumov v prehlade terminov.
 */
if (Inoby_Config::wpbs_overview()["show_dates"] ?? false) {
  $legend_items = array_reduce(
    wpbs_get_legend_items(),
    function ($res, $item) {
      $res[$item->get("id")] = $item;
      return $res;
    },
    []
  );

  add_filter(
    "wpbs_calendar_overview_output_display_day",
    function ($output, $year, $month, $day, $event) use ($legend_items) {
      $booked = false;
      $legend_item_id = $event ? $event->get("legend_item_id") : 0;
      $legend_item = $legend_items[$legend_item_id] ?? null;

      if (new DateTime() > DateTime::createFromFormat("Y-m-d H:i:s", "$year-$month-$day 23:59:59")) {
        $booked = true;
      } elseif ($legend_item) {
        $booked = !$legend_item->get("is_bookable");
      } else {
        $booked = false;
      }
      return ($booked ? '<div class="booked"></div>' : "") . '<div class="wpbs-date-inner ' . ($booked ? "" : "bookable") . '">' . $day . "</div>";
    },
    10,
    5
  );
}

/**
 * Uzivatelske prava pre editora.
 */
add_filter("wpbs_submenu_page_capability_bookings", function ($cap) {
  return "edit_posts";
});

add_filter("wpbs_submenu_page_capability_settings", function ($cap) {
  return "edit_posts";
});
