<% layout('layouts/boilerplate') %>
<% const dayNames = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]; %>
<% if (eventBookings.length === 0) { %>
<div class="mt-5 pt-5">
  <h3 class="text-center mt-5">You haven't booked for any events yet!</h3>
</div>

<% } else { %>
<div class="row row-cols-1 row-cols-md-2 g-4">

  <% for (eventBooking of eventBookings) { %>
  <div class="col">
    <div class="card shadow h-100">
      <div class="card-body">
        <div class="row h-100 g-0 pb-0">
          <div class="col-4 col-md-4 mt-2">
            <div class="img align-middle text-center ms-2">
              <img id="eventImg<%= eventBooking._id %>" aria-label="event-logo" class="rounded event-logo" src="<%= typeof eventBooking.event.img.url === 'undefined' ? eventBooking.event.eventHost.img : eventBooking.event.imgThumbnail %>" class="img-fluid rounded-start py-3 px-3" alt="...">
              <% if (eventBooking.event.img?.url) { %>
                <img style="top:-60px !important; left:0px !important;" id="hostImg<%= eventBooking._id %>" aria-label="host-logo" src="<%= eventBooking.event.eventHost.img.url %>" class="host-logo-fade" alt="">
              <% } %>
              <% if (eventBooking.event.eventHost.eventSystem.img?.url) { %>
                <img  id="hostSystemImg<%= eventBooking._id %>" src="<%= eventBooking.event.eventHost.eventSystem.img.url %>" class="img-fluid mt-3" alt=""> 
              <% } %>
            </div>
          </div>
          <div class="col-md-8">
            <div class="card-body pb-0">
              <div class="text-center" style="position:absolute;top:1em;right:1em;">
                <% if (eventBooking.paid) { %>
                  <i title="Payment Complete" class="bi bi-check2-circle text-success display-4"></i>
                <% } else { %>
                  <% if (new Date(eventBooking.event.eventEnd) < Date.now()) { %>
                    <i title="Event missed. This event is no longer available to book" class="bi bi-x-circle text-danger display-4"></i><br><span class="text-danger">Event missed</span>
                  <% } else if (eventBooking.payOnGate || eventBooking.inQueue || !((eventBooking.event.playerSpaces == 0 && eventBooking.bookingType == 'player') || (eventBooking.event.monsterSpaces == 0 && eventBooking.bookingType == 'monster') || (eventBooking.event.staffSpaces == 0 && eventBooking.bookingType == 'staff'))) { %>
                    <a class="link-danger" href="/account/pay/<%= eventBooking._id %>"><i title="Payment Due" class="bi bi-exclamation-circle text-danger display-4"></i><br>Pay Now</a></span>
                  <% } %>
                <% }%>
              </div>
              <h5 class="card-title">
                <a class="link-dark" href="/events/<%= eventBooking.event._id %>">
                  <%= eventBooking.event.name %>
                </a>
              </h5>
              <p class="card-text">
                <i>
                  <%= dateOutput(eventBooking.event.eventStart) %>
            <% if (dateOutput(eventBooking.event.eventStart) != dateOutput(eventBooking.event.eventEnd)) { %> to
            <%= dateOutput(eventBooking.event.eventEnd) %>
            <% } %><br /><small>
                    <a class="link-dark" target="_blank" href="https://www.google.com/maps/search/?api=1&query=<%= encodeURI(eventBooking.event.location) %>"><%= eventBooking.event.location.split(',')[0] %></a>
                  </small>
                </i>
              <p class="card-text">
              <ul class="list-group list-group-flush">
                <% for (eventTicket of eventBooking.eventTickets) { %>
                <li class="list-group-item">
                  <% if (['player','playerchild'].includes(eventTicket.ticketType)) { %> <i class="fa fa-ticket" aria-hidden="true"></i>
                  <% } %>
                  <% if (['monster','monsterchild'].includes(eventTicket.ticketType)) { %> <i class='bi bi-bug-fill nav_icon'></i>
                  <% } %>
                  <% if (['staff'].includes(eventTicket.ticketType)) { %> <i class="fa fa-clock-o" aria-hidden="true"></i>
                  <% } %>
                  <% if (['mealticket','mealticketchild'].includes(eventTicket.ticketType)) { %> <i class="fa fa-cutlery me-1" aria-hidden="true"> </i>
                  <% } %>
                  <% if (['playerbunk','monsterbunk','staffbunk'].includes(eventTicket.ticketType)) { %><i class="fa fa-bed me-1" aria-hidden="true"> </i>
                  <% } %>
                  <%= eventTicket.cost > 0 ? `${currencyOutput(eventTicket.cost)} - ` : '' %><%= eventTicket.description %>
                </li>
                <% } %>
                <% if (eventBooking.paid || eventBooking.payOnGate) { %>
                <li class="list-group-item"><small class="text-muted">
                  Paid: <%= dateOutput(eventBooking.bookingPaid) %><br>
                  <%= eventBooking.paypalPayer %></small>
                </li>
                <% if (eventBooking.event.catering?.choiceRequired && eventBooking.cateringChoices.length > 0) { %>
                  <li class="list-group-item px-0">
                    <div class="accordion accordion-flush" id="accordionCatering<%= eventBooking._id %>">
                      <div class="accordion-item">
                        <h6 class="accordion-header " id="cateringHeader">
                          <button class="accordion-button py-1 collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#accordionCateringTab<%= eventBooking._id %>" aria-expanded="false" aria-controls="accordingCateringTab<%= eventBooking._id %>">
                            Catering Choices
                          </button>
                        </h6>
                        <div id="accordionCateringTab<%= eventBooking._id %>" class="accordion-collapse collapse" aria-labelledby="cateringHeader" data-bs-parent="#accordionCatering<%= eventBooking._id %>">
                          <div class="accordion-body px-0">
                            <small>
                            <% for (var d = new Date(eventBooking.event.eventStart); d <= new Date(eventBooking.event.eventEnd); d.setDate(d.getDate() + 1)) { %>
                              <p><b><%=  dayNames[new Date(d).getDay()] %></b><br/>
                              <% for (day of eventBooking.cateringChoices.filter(a => a.day == dayNames[new Date(d).getDay()])){ %>
                                  <b><%= day.meal %></b> - <%= day.choice %><br/>
                              <% } %></p>
                          <% } %>
                            </small>
                          </div>
                        </div>
                      </div>
                    </div>
                  </li>
                  <% } %>
                <li class="list-group-item">
                  <a href="/events/booking/<%= eventBooking._id %>" class="link-dark"><small><i class="bi bi-ticket-detailed"></i> Update Booking</small></a><br/>
                  <% if (eventBooking.event.catering?.choiceRequired) { %>
                  <a href="/events/booking/<%=eventBooking._id %>/catering" class="link-dark"><small><i class="fa fa-cutlery me-1" aria-hidden="true"> </i> Submit Catering Choices</small></a><br/>
                  <% } %>
                  <a href="/events/booking/<%=eventBooking._id %>/ticket" class="link-dark"><small><i class="bi bi-filetype-pdf"></i> Download Ticket</small></a><br/>
                  <% if ((eventBooking.event.playerSpaces == 0 && eventBooking.bookingType == 'player') || (eventBooking.event.monsterSpaces == 0 && eventBooking.bookingType == 'monster') || (eventBooking.event.staffSpaces == 0 && eventBooking.bookingType == 'staff')) { %>
                    <br><small class="text-danger"><em>This event is fully booked and tickets can no longer be transfered.</em></small>
                  <% } else { %>
                    <a href="" onclick="document.getElementById('giftBookingId').value = '<%= eventBooking._id %>'" data-bs-toggle="modal" data-bs-target="#giftModal" class="link-dark link-muted"><small><i class="bi bi-gift"></i> Gift this booking to another user</small></a>
                    <% } %>
                </li>
                <% } else { %>
                <li class="list-group-item"><a href="/events/booking/<%= eventBooking._id %>" class="link-info">
                  <small>Update Booking</small></a><br />
                  <a href="#" onclick="cancelBooking('<%= eventBooking._id %>','<%= eventBooking.event.name %>')" data-bs-toggle="modal" data-bs-target="#cancelModal" class="link-danger"><small>Cancel Booking</small></a>
                </li>
                <% } %>
              </ul>
              </p>
            </div>
          </div>
        </div>
      </div>
      <div class="card-footer eventFooter mt-0">
        <div class="row h-100 mt-0">
          <div class="col text-muted mt-0">
            <% if ((!eventBooking.paid && !eventBooking.payOnGate) && ((eventBooking.event.playerSpaces == 0 && eventBooking.bookingType == 'player') || (eventBooking.event.monsterSpaces == 0 && eventBooking.bookingType == 'monster') || (eventBooking.event.staffSpaces == 0 && eventBooking.bookingType == 'staff'))) { %>
            <div class="alert alert-danger py-1 text-center">Event is fully booked. <br> You are on the waiting list.</div>
            <% } %>
            <small>
              <%- !eventBooking.originalUser.equals(eventBooking.user) ? '<i class="bi bi-gift"></i> This was a gift!' : '' %>
            </small>
          </div>
          <div class="col">
            <p class="card-text text-end"><% if (eventBooking.event.eventHost.display) { %><small class="text-muted">Hosted by the <%= eventBooking.event.eventHost.name %></small><% } %></p>
          </div>
        </div>
      </div>
    </div>

  </div>
  <% } %>
</div>
<% } %>

<div class="modal fade" id="giftModal" tabindex="-1" aria-labelledby="giftModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h1 class="modal-title fs-5" id="giftModalLabel">Gift this booking</h1>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <p>Gift an event booking to a very lucky friend!</p>
        <p>It is possible to gift your paid booking to someone else, however they need to be registered to be eligible.</p>
        <hr>
        <form id="giftBooking" action="/events/booking/gift">
          <div class="row">
            <div class="col-8">
              <label for="exampleFormControlInput1" class="form-label">Email address</label>
              <input class="form-control form-control-sm" type="email" id="giftEmail" name="username" required>
              <div id="giftInvalid" class="invalid-feedback">
                Username was not found
              </div>
              <script>
                document.getElementById('giftEmail').setCustomValidity("Invalid field.")
              </script>
              <input type="hidden" id="giftBookingId" name="eventBooking" value="">
            </div>
            <div class="col-4">
              <a href="#" class="btn btn-primary mt-4" onclick="submitGift()"><i class="bi bi-gift"></i> Send Gift</a>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="cancelModal" tabindex="-1" aria-labelledby="cancelModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h1 class="modal-title fs-5" id="cancelModalLabel">Cancel Event Booking</h1>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        Are you sure you want to cancel your event booking for <span id="cancelEventName"></span>?
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <form id="cancelBookingForm" action="" method="POST">
        <button type="submit" class="btn btn-danger">Cancel Booking</button>
      </form>
      </div>
    </div>
  </div>
</div>

<script src="/js/eventLogo.js"></script>
<script>
  function cancelBooking(eventId,eventName){
    document.getElementById('cancelBookingForm').action = `/events/booking/${eventId}?_method=DELETE`;
    document.getElementById('cancelEventName').innerText = eventName;
  }

  async function submitGift() {
    try {
      await fetch('/events/booking/gift', {
          method: 'POST',
          headers: {
            "Content-Type": "application/json"
          },
          body: JSON.stringify({
            username: document.getElementById('giftEmail').value,
            eventBooking: document.getElementById('giftBookingId').value,
          })
        })
        .then(response => {
          switch (response.status) {
            case 404:
              document.getElementById('giftEmail').classList.add('is-invalid');
              document.getElementById('giftInvalid').innerText = 'Username was not found';
              break;
            case 418:
              document.getElementById('giftEmail').classList.add('is-invalid');
              document.getElementById('giftInvalid').innerText = 'You can not give a gift to yourself!';
              break;
            case 200:
              document.getElementById('giftEmail').classList.add('is-valid');
              window.location.href = window.origin;
              break;
          }
        })
    } catch (error) {
      console.log(error);
      document.getElementById('giftEmail').classList.add('is-invalid')
    }
  }
</script>