{% extends 'dashboard/admin_dashboard/main.html' %}
{% load static %}
{% block content %}


<h4 class="fw-bold py-3 mb-4"><span class="text-muted fw-light">Masters / Location /</span> All Location</h4>
<div style="padding: 10px;">
  {% if messages %}
    {% for message in messages %}
      <div class="alert {% if 'success' in message.tags %}alert-success{% elif 'danger' in message.tags %}alert-danger{% elif 'warning' in message.tags %}alert-warning{% elif 'info' in message.tags %}alert-info{% endif %} alert-dismissible" role="alert" id="success-alert">
        {{ message }}
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close">
        </button>
      </div>
    {% endfor %}
  {% endif %}
</div>
<div class="row">
    <div class="col-lg-12 col-md-12">
      <div class="card">
        <div class="mt-3 d-flex justify-content-start">
        <a href="{% url 'admin_location_add' %}" class="btn btn-primary" style="margin: 10px;">
            Add Locations</a>
        </div>
        <div class="table-responsive" style="margin: 10px;">
          <table class="table table-bordered table-striped" id="location_table">
            <thead>
              <tr>
                <th>ID</th>
                <th>COUNTRY</th>
                <th>STATE</th>
                <th>CITY</th>
                <th>LOCATION</th>
                <th>STATUS</th>
                <th>ACTIONS</th>
              </tr>
            </thead>
          </table>
          {% csrf_token %}
        </div>
      </div>
    </div>
</div>
<!-- Gate Pass Modal -->
<div class="modal fade" id="gatePassModal" tabindex="-1" role="dialog" aria-labelledby="gatePassModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Select Gate Pass Template</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"  id="modalCloseBtn"></button>
<!--          <span>&times;</span>-->
<!--        </button>-->
      </div>
      <div class="modal-body">
        <div class="row" id="gatePassContainer">
          <!-- Template cards will be loaded here -->
        </div>
      </div>
      <div class="modal-footer">
        <input type="hidden" id="selectedLocationId">
        <button type="button" class="btn btn-primary" id="saveGatePassBtn">Save</button>
      </div>
    </div>
  </div>
</div>
<script src="{% static 'plugins/jQuery/jQuery-2.1.3.min.js' %}" type="text/javascript"></script>
<script src="{% static 'dist/js/pages/location_delete.js' %}" type="text/javascript"></script>
<script>
  $(document).ready(function() {
    // Retrieve CSRF token value from the hidden input
    var csrfToken = $('input[name=csrfmiddlewaretoken]').val();
    console.log("CSRF Token: ", csrfToken);

    // Set up AJAX to include the CSRF token in the headers for non-GET requests
    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrfToken);
                console.log("CSRF Token set in header: ", csrfToken);
            }
        }
    });

    // Define the AJAX URL, ensure it's correctly rendered
    var ajaxUrl = "{% url 'admin_location_ajax_page_ajax' %}";
    console.log("AJAX URL: ", ajaxUrl);

    // Initialize DataTable with server-side processing
    $('#location_table').DataTable({
        "ajax": {
            "url": ajaxUrl,
            "type": "POST"
        },
        "columns": [
            { data: 'id'},
            { data : 'countries_name'},
            { data : 'states_name'},
            { data : 'cities_name'},
            { data : 'location_name'},
            {
                data: 'status',
                render: function(data, type, row) {
                    return data === 1 ? 'Active' : 'Inactive';
                }
            },
            {
                data: null,
                render: function(data, type, row) {
                    var editUrl = "{% url 'admin_location_edit' 0 %}".replace('0', row.id);
                    var deleteUrl = "{% url 'admin_location_delete' 0 %}".replace('0', row.id);

                    var editButton = '<a title="EDIT" href="' + editUrl + '" class="btn btn-primary" data-toggle="tooltip" data-placement="top" title="Edit"><i class="bx bx-pencil"></i></a>';
                    var deleteButton = '<button title="DELETE" class="btn btn-danger delete-link" data-id="' + row.id + '" value="' + deleteUrl + '"><i class="bx bx-trash"></i></button>';
                    {% if setting.is_gate_pass_template_active %}
                      var gatePassBtn = '<button title="GATE PASS" class="btn btn-warning gate-pass-btn" data-id="' + row.id + '"><i class="bx bx-list-ul"></i></button>';

                      return editButton + ' ' + deleteButton + ' ' + gatePassBtn;
                    {% else %}
                       return editButton + ' ' + deleteButton;
                    {% endif %}
                }

            }


        ],
        "processing": true,
        "serverSide": true,
        "responsive": true,
        "ordering": false,
        lengthMenu: [
            [10, 25, 50, 100],
            [10, 25, 50, 100]
        ],
        layout: {
            topStart: {
                buttons: ['csv','pageLength']
            }
       },
    });
    // Open Gate Pass Modal
    $(document).on('click', '.gate-pass-btn', function() {
        var locationId = $(this).data('id');
        console.log('locationId:', locationId);
        $('#selectedLocationId').val(locationId);
        console.log('selectedLocationId:', selectedLocationId);
        $.ajax({
            url: "{% url 'admin_get_gate_pass_templates' %}",
            type: "GET",
            data: {
                location_id: locationId
            },
            success: function(response) {
                console.log("AJAX Success Response:", response);
                var container = $('#gatePassContainer');
                container.empty();

                $.each(response.templates, function(index, template) {
                    console.log("Template:", template);
                    var checked = (template.id == response.selected_template_id) ? 'checked' : '';
                    var cardHtml = `
                        <div class="col-md-12">
                            <div class="card mb-12" style="border: 1px solid #ddd; padding: 10px;">
                                <div class="card-body">
                                    <input type="radio" name="gatePassTemplate" value="${template.id}" id="template${template.id}" ${checked}>
                                    <strong>${template.gate_pass_name}</strong><br>
                                    <label for="template${template.id}">${template.template_html}</label>
                                </div>
                            </div>
                        </div>
                    `;
                    container.append(cardHtml);
                });

                $('#gatePassModal').modal('show');
            },
            error: function() {
                alert("Error fetching templates.");
            }
        });
    });

    // Save Selected Template
    $('#saveGatePassBtn').click(function() {
        var selectedTemplateId = $('input[name="gatePassTemplate"]:checked').val();
        var locationId = $('#selectedLocationId').val();

        if (!selectedTemplateId) {
            alert("Please select a template.");
            return;
        }

        $.ajax({
            url: "{% url 'admin_save_location_gate_pass' %}",
            type: "POST",
            data: {
                'location_id': locationId,
                'template_id': selectedTemplateId
            },
            success: function(response) {
                $('#gatePassModal').modal('hide');
                alert("Gate Pass Template saved successfully!");
                $('#location_table').DataTable().ajax.reload();
            },
            error: function() {
                alert("Error saving Gate Pass Template.");
            }
        });
    });
});
  </script>
<script>
document.getElementById('modalCloseBtn').addEventListener('click', function() {
    location.reload(); // refreshes the page
});
</script>
{% endblock %}


