<?php

function wpbs_get_current_post_calendar_id() {
  global $wpdb;
  global $post;
  $post_id = $post->ID;
  return $wpdb->get_row("SELECT * FROM {$wpdb->prefix}wpbs_calendar_meta WHERE meta_key = 'calendar_link_internal' AND meta_value = $post_id LIMIT 1;", OBJECT)->calendar_id ?? null;
}

if (!current_user_can("manage_options") && !is_admin()) {
  // do not display test calendars for common users
  add_action(
    "wpbs_get_calendars",
    function ($calendars, $args, $count) {
      return array_reduce(
        $calendars,
        function ($result, $cal) {
          if (!str_starts_with($cal->get("name"), "test")) {
            $result[] = $cal;
          }
          return $result;
        },
        []
      );
    },
    10,
    3
  );
}

function wpbs_get_booking_from_order($order) {
  if ($order instanceof WC_Order) {
    $order_id = $order->get_id();
  } elseif (is_numeric($order)) {
    $order_id = $order;
  } else {
    return;
  }

  $wpbs_payments = wpbs_get_payments(["order_id" => $order_id]);
  $payment = reset($wpbs_payments);
  if (!$payment) {
    return;
  }

  $booking_id = $payment->get("booking_id");
  if (!$booking_id) {
    return;
  }

  return wpbs_get_booking($booking_id);
}

function wpbs_booking_start_date_output($booking) {
  return wp_date(wc_date_format(), strtotime($booking->get("start_date")));
}

function wpbs_booking_end_date_output($booking) {
  return wp_date(wc_date_format(), strtotime($booking->get("end_date")));
}

function wpbs_get_booking_details($booking) {
  $details = [];
  foreach ($booking->get("fields") as $field) {
    $type = $field["type"];
    if (in_array($type, ["capacity", "product_checkbox"])) {
      $label = $field["values"]["default"]["label"] ?? "";
      $value = $field["user_value"] ?? false;
      if (is_array($value)) {
        $value = count($value) ? " " : null;
      }

      if ($value) {
        $details[] = ["label" => $label, "value" => $value];
      }
    }
  }
  return $details;
}
