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


<h4 class="fw-bold py-3 mb-4">VISITOR </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="table-responsive" style="margin: 10px;">
          <table class="table table-bordered table-striped" id="appointment_table" style="width:100%">
            <thead>
              <tr>
                 <th>ID</th>
                  <th>NAME</th>
                  <th>EMPLOYEE NAME</th>
                  <th>APPOINTMENT DATE</th>
                  <th>APPOINTMENT TIME</th>
                  <th>TYPE</th>
                  <th>UNI ID</th>
                  <th>IMAGE</th>
                  <th>MOBILE</th>
                  <th>CHECK IN TIME</th>
                  <th>CHECK OUT TIME</th>
                  <th>PURPOSE</th>
                  <th>DETAIL</th>
                  <th>CREATED AT</th>
              </tr>
            </thead>
          </table>
          {% csrf_token %}
        </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/company_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 table = $('#appointment_table').DataTable({
            "ajax": {
                "url": "{% url 'admin_visitor_verification_page_ajax' %}",
                "type": "POST"
            },
            "columns": [
                { data: 'id' },
                { data: 'visitors_name' },
                { data: 'employee_name' },
                { data: 'date' },
                { data: 'time' },
                { data: 'visitors_type' },
                { data: 'visitors_uni_id' },
                {
                    data: 'visitors_image',
                    render: function(data, type, row) {
                        let imageUrl = data ? '{{IMAGEPATH}}' + data : '{{DEFAULT_IMAGE}}';
                        return '<img src="' + imageUrl + '" alt="Visitor Image" width="50" height="50"/>';
                    }
                },
                { data : 'visitors_mobile' },
                { data: 'check_in_time'},
                {data: 'check_out_time'},
                { data: 'purpose' },
                { data: 'detail' },
                { data: 'created_at' },


            ],
            "processing": true,
            "serverSide": true,
            "responsive": true,
            "ordering": false,
            "autoWidth": true,
            "lengthMenu": [
                [10, 25, 50, 100],
                [10, 25, 50, 100]
            ],
            "layout": {
                "topStart": {
                    "buttons": [
                {
                    extend: 'csv',
                    text: 'Export' // Change this to your desired label
                },
                'pageLength'
            ]
                }
            }
        });
        
        // ✅ Adjust column sizes after initialization
        table.columns.adjust().draw();
        
        function showAlert(message, type) {
            var alertHtml = '<div class="alert alert-' + type + ' alert-dismissible fade show" role="alert">' +
                message +
                '<button type="button" class="close" data-dismiss="alert" aria-label="Close">' +
                '<span aria-hidden="true">&times;</span>' +
                '</button>' +
                '</div>';
            $('.success-alert').html(alertHtml);
        }
        $(document).on('click', '.start-link', function(e) {
            e.preventDefault();
            var $startButton = $(this);
            var $stopButton = $startButton.next('.stop-link');

            $.ajax({
                url: $startButton.data('url'),
                type: 'POST',
                data: {
                    'csrfmiddlewaretoken': csrfToken
                },
                success: function(response) {

                    console.log('Start response:', response);  // Log the entire response
                    if (response.status === 'success') {
                        showAlert('Start time recorded successfully!', 'success');
                        // Update button states
                        $startButton.addClass('disabled').find('i').removeClass('fa-play').addClass('fa-pause');
                        $stopButton.removeClass('disabled');
                        /*setTimeout(function() {
                            location.reload(); // Refresh the page
                        }, 100);*/
                    } else {
                        showAlert('Failed to update start time: ' + (response.message || 'No message'), 'danger');
                        console.error('Failed to update start time:', response.message || 'No message');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error recording start time:', error);
                }
            });
        });

        $(document).on('click', '.stop-link', function(e) {
            e.preventDefault();
            var $stopButton = $(this);
            var $startButton = $stopButton.prev('.start-link');

            $.ajax({
                url: $stopButton.data('url'),
                type: 'POST',
                data: {
                    'csrfmiddlewaretoken': csrfToken
                },
                success: function(response) {
                    showAlert('Stop time recorded successfully!', 'success');
                    console.log('Stop response:', response);  // Log the entire response
                    if (response.status === 'success') {
                        $stopButton.addClass('disabled');
                        $startButton.addClass('disabled');
                        /*setTimeout(function() {
                            location.reload(); // Refresh the page
                        }, 100);*/
                    } else {
                        showAlert('Failed to update stop time: ' + (response.message || 'No message'), 'danger');
                        console.error('Failed to update stop time:', response.message || 'No message');
                    }
                },
                error: function(xhr, status, error) {
                    showAlert('Error recording stop time: ' + error, 'danger');
                    console.error('Error recording stop time:', error);
                }
            });
        });

        $(document).on('click', '.print-link', function(e) {
            e.preventDefault();
            var id = $(this).data('id');
            var detailsUrl = $(this).data('url');

            $.ajax({
                url: detailsUrl,
                type: 'GET',
                success: function(response) {
                    var printWindow = window.open('', '_blank');
                    var printContent = response.html;
                    printWindow.document.write('<html><head><title>Gate Pass</title></head><body>');
                    printWindow.document.write(printContent);
                    printWindow.document.write('</body></html>');
                    printWindow.document.close();
                    printWindow.focus();
                    printWindow.print();
                },
                error: function(xhr, status, error) {
                    console.error('Error loading visitor details:', error);
                }
            });
        });
    });

  </script>
  <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Add event listener to the "Close" button inside the modal
        document.getElementById('closeModalButton').addEventListener('click', function() {
            location.reload(); // Refresh the page
        });
    });
</script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Add event listener to the "Close" button inside the modal
        document.getElementById('closeModalButtones').addEventListener('click', function() {
            location.reload(); // Refresh the page
        });
    });
</script>
{% endblock %}


