{% load static %}
{% include 'dashboard/admin_dashboard/header.html' %}
{% include 'dashboard/admin_dashboard/body.html' %}
<div class="modal fade" id="visitorDetailsModal" tabindex="-1" role="dialog" aria-labelledby="visitorDetailsModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="visitorDetailsModalLabel">Visitor Details</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close" id="closeModalButton">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body" id="visitorDetailsContent">
                <!-- Content will be loaded here by AJAX -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal" id="closeModalButtones">Close</button>
            </div>
        </div>
    </div>
</div>
<!-- Right side column. Contains the navbar and content of the page -->
<div class="content-wrapper">
    
    <!-- Content Header (Page header) -->
    <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">
  <!--                            <div class="alert alert-success" role="alert" id="success-alert">-->
              {{message}}
              <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
              </button>
          </div>
          {% endfor %}
      {% endif %}

          <div class="success-alert">
          </div>  

    </div>
    
    <section class="content-header">
        
      <h1>
        VISITOR
        <small>Control panel</small>
      </h1>
      <ol class="breadcrumb">
        <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
        <li class="active">VISITOR</li>
      </ol>
    </section>
    <section class="content">
    <!-- Small boxes (Stat box) -->
      <div class="row">
        <div class="col-xs-12">
          
          <div class="box">
          <div class="box-header">
          </div>

          <div class="table-responsive" style="margin: 10px;">
            <table id="appointment_table" class="table table-bordered table-striped" style="width:100%;">
                <thead>
                  <tr>
                    <th>ID</th>
                    <th>VISITOR NAME</th>
                    <th>EMPLOYEE NAME</th>
                    <th>PURPOSE</th>
                    <th>APPOINTMENT DATE</th>
                    <th>APPOINTMENT TIME</th>
                    <th>VISITORS TYPE</th>
                    <th>VISITORS UNI ID</th>
                    <th>VISITORS IMAGE</th>
                    <th>VISITORS MOBILE</th>
                    <th>DETAIL</th>
                    <th> CHECK IN TIME </th>
                    <th> CHECK OUT TIME </th> 
                    <th>CREATED AT</th>                       

                  </tr>
                </thead>

            </table>
            {% csrf_token %}

      </div>
      
</section>
</div>
</div>









{% include 'dashboard/visitors_dashboard/footer.html' %}
<!--<script type="text/javascript">-->
<!--  $(function () {-->
<!--    $('#appointment_table').dataTable();-->
<!--  });-->
<!--</script>-->

<script src="{% static 'dist/js/pages/delete_1.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);
                }
            }
        });
    
        $('#appointment_table').DataTable({
            "ajax": {
                "url": "{% url 'admin_visitor_verification_page_ajax' %}",
                "type": "POST"
            },
            "columns": [
                { data: 'id' },
                { data: 'visitors_name' },
                { data: 'employee_name' },
                { data: 'purpose' },
                { 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: 'detail' },
                { data: 'check_in_time'},
                {data: 'check_out_time'},
                { data: 'created_at' },
                
                
            ],
            "processing": true,
            "serverSide": true,
            "responsive": true,
            "ordering": false,
            "lengthMenu": [
                [10, 25, 50, 100],
                [10, 25, 50, 100]
            ],
            "layout": {
                "topStart": {
                    "buttons": ['csv', 'pageLength']
                }
            }
        });
        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>
