
    {% load static %}
    {% include 'dashboard/gate_keeper_dashboard/header.html' %}
    {% include 'dashboard/gate_keeper_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>STATUS</th>
                        <th>EMPLOYEE APPROVAL</th>
                        <th>DETAIL</th>
                        <th>VISITOR TIMING</th>
                        <th>EMPLOYEE CREATED BY</th>
                        <th> CHECK IN TIME </th>
                        <th> CHECK OUT TIME </th>
                        <th> CREATED AT</th>
                        <th>ACTIONS</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 'gate_keeper_visitor_verification_page_ajax' %}",
                    "type": "POST"
                },
                "columns": [
                    { data: 'id' },
                    {
                        data: null, // Use null data to indicate that we are not using a direct field
                        render: function(data, type, row) {
                            return row.visitors_name + ' ' + row.visitors_last_name;
                        }
                    },
                    {
                        data: null, // Use null data to indicate that we are not using a direct field
                        render: function(data, type, row) {
                            return row.employee_name + ' ' + row.employee_last_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: 'status' },
                    /*{
                    data: 'employees_allow_check_in',
                    render: function(data, type, row) {
                        return data == 1 ? 'Yes' : 'No';
                    }
                },*/
                    { data: 'employee_approval' },
                    { data: 'detail' },
                    { data: 'visitors_timing' },
                    {
                        data: null, // Use null data to indicate that we are not using a direct field
                        render: function(data, type, row) {
                            return row.created_by_first_name + ' ' + row.created_by_last_name;
                        }
                    },
                    { data: 'check_in_time'},
                    {data: 'check_out_time'},
                    { data: 'created_at' },
                    /*{
                        data: null,
                        render: function(data, type, row) {
                            var editUrl = "{% url 'gate_keeper_visitor_edit' 0 %}".replace('0', row.id);
                            var startUrl = "{% url 'gate_keeper_start_time' 0 %}".replace('0', row.id);
                            var stopUrl = "{% url 'gate_keeper_stop_time' 0 %}".replace('0', row.id);
                            var printUrl = "{% url 'gate_keeper_print_gate_pass' 0 %}".replace('0', row.id);

                            var startButtonIcon = row.start_time ? 'fa fa-pause' : 'fa fa-play';
                            var stopButtonIcon = row.start_time && !row.stop_time ? 'fa fa-stop' : 'fa fa-stop disabled';
                            var startButtonClass = 'btn btn-success';
                            var stopButtonClass = 'btn btn-warning';

                            // Disable start and stop buttons if status is 'pending' or 'rejected'
                            if (row.status === 'pending' || row.status === 'rejected') {
                                startButtonClass += ' disabled';
                                stopButtonClass += ' disabled';
                            } else {
                                // If start_time is set, disable start button
                                if (row.start_time) {
                                    startButtonClass += ' disabled';
                                }
                                // If stop_time is set or start_time is not set, disable stop button
                                if (!row.start_time || row.stop_time) {
                                    stopButtonClass += ' disabled';
                                }
                            }
                            let disabled = row.visitors_name.trim() === '' ? 'disabled' : '';
                            var editButton = '<a title="EDIT" href="' + editUrl + '" class="btn btn-primary" data-toggle="tooltip" data-placement="top" title="Edit"' + disabled + '><i class="fa fa-pencil"></i></a>';
                            var startButton = '<button title="CHECK IN" class="' + startButtonClass + ' start-link" data-id="' + row.id + '" data-url="' + startUrl + '"><i class="' + startButtonIcon + '"></i></button>';
                            var stopButton = '<button title="CHECK OUT" class="' + stopButtonClass + ' stop-link" data-id="' + row.id + '" data-url="' + stopUrl + '"><i class="' + stopButtonIcon + '"></i></button>';
                            var printButton = '<button title="PRINT GATE PASS" id="printButton" class="btn btn-info print-link" data-id="' + row.id + '" data-url="' + printUrl + '" ' + disabled + '><i class="fa fa-print"></i></button>';

                            return editButton + ' ' + startButton + ' ' + stopButton + ' ' + printButton;
                        }
                    }*/
                    {
                        data: null,
                        render: function(data, type, row) {
                            var editUrl = "{% url 'gate_keeper_visitor_edit' 0 %}".replace('0', row.id);
                            var startUrl = "{% url 'gate_keeper_start_time' 0 %}".replace('0', row.id);
                            var stopUrl = "{% url 'gate_keeper_stop_time' 0 %}".replace('0', row.id);
                            var printUrl = "{% url 'gate_keeper_print_gate_pass' 0 %}".replace('0', row.id);

                            var startButtonIcon = row.start_time ? 'fa fa-pause' : 'fa fa-play';
                            var stopButtonIcon = row.start_time && !row.stop_time ? 'fa fa-stop' : 'fa fa-stop disabled';
                            var startButtonClass = 'btn btn-success';
                            var stopButtonClass = 'btn btn-warning';

                            // Logic to disable buttons based on start_time and stop_time
                            if (row.start_time) {
                                startButtonClass += ' disabled';
                            }
                            if (!row.start_time || row.stop_time) {
                                stopButtonClass += ' disabled';
                            }
                            if (row.employees_allow_check_in !== 1 && row.employee_approval !== 'accepted') {
                                startButtonClass += ' disabled';
                                stopButtonClass += ' disabled';
                            }

                            let disabled = row.visitors_name.trim() === '' ? 'disabled' : '';
                            var editButton = '<a title="EDIT" href="' + editUrl + '" class="btn btn-primary" data-toggle="tooltip" data-placement="top" title="Edit"' + disabled + '><i class="fa fa-pencil"></i></a>';
                            var startButton = '<button title="CHECK IN" class="' + startButtonClass + ' start-link" data-id="' + row.id + '" data-url="' + startUrl + '"><i class="' + startButtonIcon + '"></i></button>';
                            var stopButton = '<button title="CHECK OUT" class="' + stopButtonClass + ' stop-link" data-id="' + row.id + '" data-url="' + stopUrl + '"><i class="' + stopButtonIcon + '"></i></button>';
                            var printButton = '<button title="PRINT GATE PASS" id="printButton" class="btn btn-info print-link" data-id="' + row.id + '" data-url="' + printUrl + '" ' + disabled + '><i class="fa fa-print"></i></button>';

                            return editButton + ' ' + startButton + ' ' + stopButton + ' ' + printButton;
                        }
                    }
                ],
                "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 + ' " 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) {
                        showAlert('Start time recorded successfully!', 'success');
                        console.log('Start response:', response);  // Log the entire response
                        if (response.status === '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
                            }, 3000);
                        } 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
                            }, 3000);
                        } 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;
            // Prepare complete HTML document
            printWindow.document.write(`
                <html>
                <head>
                    <title>Gate Pass</title>
                    <style>
                        @media print {
                            @page {
                                size: A4 landscape;
                                margin: 0;
                            }
                            html, body {
                                margin: 0;
                                padding: 0;
                                width: 100%;
                                height: 100%;
                                overflow: hidden;
                                font-family: Arial, sans-serif;
                                font-size: 12px;
                            }
                            .gate-pass-template-preview {
                                width: 100%;
                                padding: 10px;
                                box-sizing: border-box;
                                page-break-inside: avoid;
                                break-inside: avoid;
                            }
                            .no-print, .btn, .print-link, .modal, .modal-footer, .modal-header {
                                display: none !important;
                            }
                        }

                        body {
                            margin: 0;
                            padding: 0;
                        }
                    </style>
                </head>
                <body>
                    ${printContent}
                </body>
                </html>
            `);


            printWindow.document.close();
            printWindow.focus();

            // Slight delay ensures styles and DOM are loaded before printing
            setTimeout(function() {
                printWindow.document.body.style.transform = 'rotate(90deg)';
<!--                printWindow.document.body.style.transformOrigin = 'top right';-->
                printWindow.document.body.style.width = '85vh';
                printWindow.document.body.style.height = '120vw';


                // Optional: Remove default margin/padding
                printWindow.document.body.style.marginTop = '82px';      // Adds 20px margin on top
                printWindow.document.body.style.paddingTop = '10px';

                printWindow.print();
                printWindow.close();
            }, 500);
        },
        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>
