{% extends "cms/admin_home.html" %}
{% load sekizai_tags i18n %}

{% block content %}

<h3>{{ event.name }}</h3>

<dl>
	<dt>{% trans "Total Students" %}:</dt><dd>{{ event.numRegistered }}</dd>
	<dt>{% trans "Location" %}:</dt><dd>{{ event.location.name }}{% if event.room.name %} - {{ event.room.name }}{% endif %}</dd>
	<dt>{% trans "Time" %}:</dt><dd>{{ event.startTime|date:'l, h:i A' }}</dd>
	<dt>{% trans "Partner Required" %}:</dt><dd>{{ event.partnerRequired|yesno }}</dd>
</dl>

{% if 'core.checkin_customers' in perms %}
<form id="checkin_form">

<div class="form-group">
	<label for="occurrenceSelect">{% trans "Select Event Occurrence for Check-In" %}</label>
	<select id="occurrenceSelect" class="form-control">
		{% for occ in event.eventoccurrence_set.all %}
		<option value="{{ occ.id }}" {% if occ.id == event.nextOccurrenceForToday.id %}selected{% endif %}>{{ occ }}</option>
		{% endfor %}
		<option value="event">{% trans "Event-level check-in" %}</option>
	</select>
</div>

{% endif %}

<table class="classregsummary table table-striped table-responsive">
<thead>
	<tr>
		{% if 'core.checkin_customers' in perms %}
		<th>{% trans "Check In" %}</th>
		{% endif %}
		<th>{% trans "Customer" %}</th>
		<th>{% trans "Reg. Details" %}</th>
		{% if event.partnerRequired %}<th>{% trans "Partner" %}</th>{% endif %}
		<th>{% trans "Event Pricing" %}</th>
		<th>{% trans "Total Payment" %}</th>
		<th>{% trans "All-Time Classes" %}</th>
		<th>{% trans "Links" %}</th>
	</tr>
</thead>
<tbody>
{% for reg in registrations %}
	<tr>
		{% if 'core.checkin_customers' in perms %}
		<td>
			<input type="checkbox" class="checkInCheckBox" id="reg_id_{{ reg.id }}" name="reg_id_{{ reg.id }}" value="{{ reg.id }}" 
				{% if reg.dropIn %}data-drop-in="true" data-occurrence-ids="{% for occ in reg.occurrences.all %}{{ occ.id }}{% if not forloop.last %}|{% endif %}{% endfor %}"{%endif %}
			/>
		</td>
		{% endif %}
		<td>
			{% if reg.customer %}
				{{ reg.customer.fullName }}
				<br />{{ reg.customer.email }}
			{% elif reg.registration.invoice.fullName or reg.registration.invoice.email %}
				{{ reg.registration.invoice.fullName }}
				{% if reg.registration.invoice.fullName %}<br />{% endif %}
				{{ reg.registration.invoice.email }}
			{% else %}
				{% trans "N/A" %}
			{% endif %}
		</td>

		<td>
		<strong>{% trans "Role" %}:</strong> {% if reg.role %}{{ reg.role }}{% else %}{% trans "N/A" %}{% endif %}<br />
			{% if reg.dropIn %}
				<strong>{% trans "Drop-in" %}{% if reg.occurrences.all %}:{% endif %}</strong>
				{% for occ in reg.occurrences.all %}
					{{ occ.startTime|date:"SHORT_DATE_FORMAT" }}{% if not forloop.last %}, {%endif %}
				{% endfor %}<br />
			{% endif %}
			{% if reg.registration.payAtDoor %}<strong>{% trans "Door registration" %}</strong><br />{% endif %}
			{% if reg.registration.student %}<strong>{% trans "Student status" %}</strong>{% endif %}
		</td>

		{% if event.partnerRequired %}
		<td>
			{% if reg.data.partner %}
				{{ reg.data.partner.firstName }} {{ reg.data.partner.lastName }}
			{% else %}
				{% trans "N/A" %}
			{% endif %}
		</td>
		{% endif %}

		<td {% if reg.warningFlag %}class="warning"{% elif reg.refundFlag %}class="info"{% endif %}>
			{% if reg.discounted or reg.warningFlag %}
				<strong>{% trans "Gross" %}:</strong> {{ reg.invoiceItem.grossTotal|floatformat:2 }} <br />
				<strong>{% trans "Net" %}:</strong> {{ reg.invoiceItem.total|floatformat:2 }}
				{% if reg.refundFlag %}<br />
				<strong>{% trans "Adjustments/Refunds" %}:</strong> {{ reg.invoiceItem.adjustments|floatformat:2 }}
				{% endif %}
				{% if reg.invoiceItem.revenueMismatch or reg.invoiceItem.revenueNotYetReceived %}<br />
				<strong>{% trans "Recorded Revenue" %}:</strong> {{ reg.invoiceItem.revenueReported|floatformat:2 }}<br />
				<strong>{% trans "Received Revenue" %}:</strong> {{ reg.invoiceItem.revenueReceived|floatformat:2 }}<br />
				{% endif %}
			{% else %}
				{{ reg.invoiceItem.total|floatformat:2 }}
			{% endif %}
		</td>

		
		{% with reg.registration.invoiceDetails as details %}
		<td 
		{% if reg.warningFlag %}
			class="warning"
		{% elif reg.refundFlag %}
			class="info"
		{% endif %}>
			{% if reg.registration.warningFlag or reg.registration.refundFlag %}
				<strong>{% trans "Gross Price" %}:</strong> {{ details.grossTotal|floatformat:2 }} <br />
				<strong>{% trans "Net Price" %}:</strong>
				{% if details.grossTotal != details.total %}
					<a href="javascript://" data-toggle="popover" title="{% trans 'Gross vs. Net Price' %}" data-container="body" data-placement="top" data-content="
					{% for d in reg.registration.registrationdiscount_set.all %}
						{% if d.discountAmount > 0 %}
							{% trans 'Discount' %}: {{ d.discount.name }} = -{{ d.discountAmount }}, 
						{% endif %}					
					{% endfor %}
					{% for v in reg.registration.invoice.voucheruse_set.all %}
						{% if v.amount > 0 %}
					 		{% trans 'Voucher' %}: {{ v.voucher.voucherId }} = -{{ v.amount }}, 
						{% endif %}
					{% endfor %}">
					{{ details.total|floatformat:2 }}</a>
				{% else %}
				 	{{ details.total|floatformat:2 }}
				{% endif %}
				{% if reg.registration.refundFlag %}<br />
				<strong>{% trans "Adjustments/Refunds" %}:</strong> {{ details.adjustments|floatformat:2 }}
				{% endif %}
				{% if reg.registration.invoice.outstandingBalance != 0 %}<br />
				<strong>{% trans "Invoice Status" %}:</strong> {{ reg.registration.invoice.get_status_display }}<br />
				<strong>{% trans "Outstanding Balance" %}:</strong> {{ reg.registration.invoice.outstandingBalance|floatformat:2 }}<br />
				{% endif %}
			{% else %}
				{% if details.grossTotal != details.total %}
					<strong>{% trans "Gross Price" %}:</strong> {{ details.grossTotal|floatformat:2 }} <br />
					<strong>{% trans "Net Price" %}:</strong>
					<a href="javascript://" data-toggle="popover" title="{% trans 'Gross vs. Net Price' %}" data-container="body" data-placement="top" data-content="
					{% for d in reg.registration.registrationdiscount_set.all %}
						{% if d.discountAmount > 0 %}
							{% trans 'Discount' %}: {{ d.discount.name }} = -{{ d.discountAmount }}, 
						{% endif %}					
					{% endfor %}
					{% for v in reg.registration.invoice.voucheruse_set.all %}
						{% if v.amount > 0 %}
					 		{% trans 'Voucher' %}: {{ v.voucher.voucherId }} = -{{ v.amount }}, 
						{% endif %}
					{% endfor %}">
					{{ details.total|floatformat:2 }}</a>
				{% else %}
					{{ details.total|floatformat:2 }}
				{% endif %}
			{% endif %}
		</td>
		{% endwith %}

		<td>{{ reg.customer.numClassSeries }}</td>
		<td>
		<div class="dropdown show">
			<a class="btn btn-light btn-sm dropdown-toggle" href="#" role="button" id="itemsLink_{{ reg.id }}" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
				{% trans "Related Items" %}
			</a>			
			<div class="dropdown-menu" aria-labelledby="itemsLink_{{ reg.id }}">
				{% if 'core.view_all_invoices' in perms and reg.registration.invoice %}
					<a class="dropdown-item" href="{% url 'viewInvoice' reg.registration.invoice.id %}">{% trans "Invoice" %}</a>
				{% endif %}
				{% if 'core.change_registration' in perms %}
					<a class="dropdown-item" href="{% url 'admin:core_registration_change' reg.registration.id %}">{% trans "Registration" %}</a>
				{% endif %}
				{% if 'core.process_refunds' in perms and reg.registration.invoice %}
					<a class="dropdown-item" href="{% url 'refundProcessing' reg.registration.invoice.id %}">{% trans "Refund" %}</a>
				{% endif %}
				{% if 'financial.change_revenueitem' in perms and reg.invoiceItem.revenueitem %}
					<a class="dropdown-item" href="{% url 'admin:financial_revenueitem_change' reg.invoiceItem.revenueitem.id %}">{% trans "Revenue Item" %}</a>
				{% endif %}
			</div>
		</div>
		</td>
	</tr>
{% endfor %}
</tbody>
</table>

{% if 'core.checkin_customers' in perms %}
	<input class="btn btn-primary" type="submit" value="{% trans 'Submit Checkins' %}" />
	</form>

	<div id="update_ok" style="display:none; font-size: 1.5em; color: #0a0; background-color: #ddd; padding: 0.5em; width: 95%;">{% trans "Check-ins submitted successfully!" %}</div>
	<div id="update_error" style="display:none; font-size: 1.5em; color: #a00; background-color: #ddd; padding: 0.5em; width: 95%;">{% trans "Error submitting class check-in data." %}</div>
{% endif %}

<hr />

<p>
<a class="btn btn-secondary btn-sm" href="{% url 'registration' %}">{% trans "Class Registration Page" %}</a>
<a class="btn btn-secondary btn-sm" href="{% url 'viewregistrations_selectevent' %}">{% trans "Select Another Class" %}</a>
</p>


{% addtoblock "js" %}
	<script type="text/javascript">

	var $ = django.jQuery;

	regParams = {
		event: "{{ event.id }}",
		ajaxUrl: "{% url 'ajax_checkin' %}",
	}

	function getCheckIns() {

		$('.checkInCheckBox').removeAttr('disabled');
		$('.checkInCheckBox').show();

		var this_request = {
			request: "get_all",
			event_id: regParams.event,
			checkin_type: "E",
		};

		var thisOccurrence = $("#occurrenceSelect").children("option:selected").val();
		if (thisOccurrence !== "event") {
			this_request["checkin_type"] = "O";
			this_request["occurrence_id"] = thisOccurrence;

			var mismatched = $('.checkInCheckBox[data-drop-in="true"][data-occurrence-ids!=""]').not('[data-occurrence-ids*="' + thisOccurrence + '"]');
			$(mismatched).attr('disabled', true);
			$(mismatched).hide();

		}

	    $.ajax(
	    {
	        url : regParams.ajaxUrl,
	        type: "POST",
            contentType: "application/json",
            data: JSON.stringify(this_request),
			success: function(data, textStatus, jqXHR)
	        {
				if (data["status"] !== "success") {
					$('#update_error').slideDown();
				}
				else {
					$('.checkInCheckBox').prop('checked', false);
					$.each(data['checkins'], function() {
						var this_element = $('#reg_id_' + this.eventRegistration);
						this_element.prop('checked', (this.cancelled == false));
						this_element.data('existing',"true");
					});
				}
			},
	        error: function(jqXHR, textStatus, errorThrown)
	        {
	        	$('#update_error').slideDown();
	        }
	    });

	}

	$(function () {
	  $('[data-toggle="popover"]').popover();
	  getCheckIns();
	});

	$('.checkInCheckBox').click(function(){
		$('#update_ok').slideUp();
		$('#update_error').slideUp();
	});

	$('#occurrenceSelect').change(function() {
		$('.checkInCheckbox').removeData('existing');
		getCheckIns();
	});

	// Use Jquery to get the cookie value of the CSRF token
	function getCookie(name) {
	    var cookieValue = null;
	    if (document.cookie && document.cookie !== '') {
	        var cookies = document.cookie.split(';');
	        for (var i = 0; i < cookies.length; i++) {
	            var cookie = django.jQuery.trim(cookies[i]);
	            // Does this cookie string begin with the name we want?
	            if (cookie.substring(0, name.length + 1) === (name + '=')) {
	                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
	                break;
	            }
	        }
	    }
	    return cookieValue;
	}
	var csrftoken = getCookie('csrftoken');

	function csrfSafeMethod(method) {
	    // these HTTP methods do not require CSRF protection
	    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
	}

	// Ensure that CSRF token is passed
	$.ajaxSetup({
	    beforeSend: function(xhr, settings) {
	        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
	            xhr.setRequestHeader("X-CSRFToken", csrftoken);
	        }
	    }
	});


	$('#checkin_form').submit(function(e) {
		e.preventDefault(); //STOP default action

		var this_request = {
			request: "update",
			event_id: regParams.event,
			checkin_type: "E",
			registrations: [],
		};

		var thisOccurrence = $("#occurrenceSelect").children("option:selected").val();
		if (thisOccurrence !== "event") {
			this_request["checkin_type"] = "O";
			this_request["occurrence_id"] = thisOccurrence;
		}

		$.each($('.checkInCheckBox'), function() {
			if ($(this).is(':checked') || $(this).data('existing') == "true") {
				this_request.registrations.push({
					id: $(this).val(),
					cancelled: ($(this).prop('checked') == false),
				});
				$(this).data('existing',"true");
			}
		});

	    $.ajax(
	    {
	        url : regParams.ajaxUrl,
	        type: "POST",
            contentType: "application/json",
            data: JSON.stringify(this_request),
			success: function(data, textStatus, jqXHR)
	        {
				if (data["status"] !== "success") {
					$('#update_error').slideDown();
				}
				else {
					$('#update_ok').slideDown();
					$.each($('.checkInCheckBox'), function() {
						if ($(this).is(':checked') || $(this).data('existing') == "true") {
							$(this).data('existing',"true");
						}
					});
				}
			},
	        error: function(jqXHR, textStatus, errorThrown)
	        {
				console.log(textStatus);
				$('#update_error').slideDown();
	        }
	    });
	});
	</script>
{% endaddtoblock %}

{% endblock %}
