{% load static %}
{% include 'dashboard/admin_dashboard/header.html' %}
{% include 'dashboard/admin_dashboard/body.html' %}

<div class="content-wrapper">
    <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{% endif %}" role="alert" id="success-alert">
                    {{ message }}
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span>&times;</span>
                    </button>
                </div>
            {% endfor %}
        {% endif %}
    </div>

    <section class="content-header">
        <h1>Location Management <small>Control panel</small></h1>
        <ol class="breadcrumb">
            <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
            <li class="active">All Locations</li>
        </ol>
    </section>

    <section class="content">
        <div class="row">
            <div class="col-xs-12">
                <div class="box">
                    <div class="box-header"></div>
                    <a href="{% url 'admin_location_add' %}" class="btn btn-primary" style="margin: 10px;">ADD LOCATIONS</a>

                    <div class="table-responsive" style="margin: 10px;">
                        <table id="location_table" class="table table-bordered table-striped" style="width:100%;">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>COUNTRY</th>
                                    <th>STATE</th>
                                    <th>CITY</th>
                                    <th>LOCATION NAME</th>
                                    <th>ADDRESS</th>
                                    <th>STATUS</th>
                                    <th>ACTIONS</th>
                                </tr>
                            </thead>
                        </table>
                        {% csrf_token %}
                    </div>
                </div>
            </div>
        </div>
    </section>
</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="close" data-dismiss="modal" aria-label="Close">
          <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>

{% include 'dashboard/visitors_dashboard/footer.html' %}

<script src="{% static 'dist/js/pages/location_delete.js' %}" type="text/javascript"></script>
<script>
$(document).ready(function() {
    var csrfToken = $('input[name=csrfmiddlewaretoken]').val();

    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrfToken);
            }
        }
    });

    var ajaxUrl = "{% url 'admin_location_ajax_page_ajax' %}";

    $('#location_table').DataTable({
        "ajax": {
            "url": ajaxUrl,
            "type": "POST"
        },
        "columns": [
            { data: 'id' },
            { data: 'countries_name' },
            { data: 'states_name' },
            { data: 'cities_name' },
            { data: 'location_name' },
            { data: 'address' },
            {
                data: 'status',
                render: function(data) {
                    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 gatePassBtn = '<button title="GATE PASS" class="btn btn-warning gate-pass-btn" data-id="' + row.id + '"><i class="fa fa-list-alt"></i></button>';

                    var editButton = '<a title="EDIT" href="' + editUrl + '" class="btn btn-primary"><i class="fa fa-pencil"></i></a>';
                    var deleteButton = '<button title="DELETE" class="btn btn-danger delete-link" data-id="' + row.id + '" value="' + deleteUrl + '"><i class="fa fa-trash-o"></i></button>';

                    return editButton + ' ' + deleteButton + ' ' + gatePassBtn;
                }
            }
        ],
        "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');
        $('#selectedLocationId').val(locationId);

        $.ajax({
            url: "{% url 'admin_get_gate_pass_templates' %}",
            type: "GET",
            data: {
                location_id: locationId
            },
            success: function(response) {
                var container = $('#gatePassContainer');
                container.empty();

                $.each(response.templates, function(index, 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>
