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


<h4 class="fw-bold py-3 mb-4"><span class="text-muted fw-light">Visitor /</span>All Appointment</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 'gate_keeper_visitor_add' %}" class="btn btn-primary" style="margin: 10px;">
            Add Appointment</a>
        </div>

        <div class="table-responsive" style="margin: 10px;">
          <table class="table table-bordered table-striped dataTable dtr-inline" id="appointment_table" style="width: 100%;">
            <thead>
              <tr>
                <th>Id</th>
                <th>Request Id</th>
                <th>Name</th>
                <th>Employee Name</th>
                <th>Appointment Date</th>
                <th>Appointment Time</th>
                <th>Type</th>
                <th>Image</th>
                <th>Mobile</th>
                <th>Status</th>
                <th>Employee Approval</th>
                <th>Timing</th>
                <th>Created By</th>
                <th>Check In Time</th>
                <th>Check Out Time</th>
                <th>Purpose</th>
                <th>Detail</th>
                <th>Created At</th>
                <th>Actions</th>
              </tr>
            </thead>
          </table>
          {% csrf_token %}
        </div>
      </div>
    </div>
</div>
<!-- ================= STOP TIME MODAL ================= -->
<div class="modal fade" id="stopTimeModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">

      <div class="modal-header">
        <h5 class="modal-title">Check Out Time</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>

      <div class="modal-body">
        <input type="hidden" id="stop_appointment_id">

        <div class="form-check">
          <input class="form-check-input" type="radio" name="time_type" value="auto" checked>
          <label class="form-check-label">
            Automatic (Current Date & Time)
          </label>
        </div>

        <div class="form-check mt-2">
          <input class="form-check-input" type="radio" name="time_type" value="manual">
          <label class="form-check-label">
            Manual Select
          </label>
        </div>

        <div class="mt-3">
          <input type="datetime-local" id="manual_datetime" class="form-control" disabled>
        </div>
      </div>

      <div class="modal-footer">
        <button class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button class="btn btn-primary" id="submitStopTime">Submit</button>
      </div>

    </div>
  </div>
</div>
<!-- =================================================== -->
<script src="{% static 'plugins/jQuery/jQuery-2.1.3.min.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: 'request_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: 'date' },
                { data: 'time' },
                { data: 'visitors_type' },
                {
                    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: 'employee_approval',className: 'none' },

                { data: 'visitors_timing',className: 'none'},
                {
                    data: null, // Use null data to indicate that we are not using a direct field
                    className: 'none',
                    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: 'purpose',className: 'none' },
                { data: 'detail',className: 'none' },
                { data: 'created_at' ,className: 'none'},
                {
                    data: null,
                    className: 'none',
                    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 visitorprintUrl ="{% url 'gate_keeper_print_gate_pass' 0 %}".replace('0', row.id);

                        var startButtonIcon = row.start_time ? 'bx bx-pause' : 'bx bx-play';
                        var stopButtonIcon = row.start_time && !row.stop_time ? 'bx bx-stop' : 'bx bx-stop disabled';

                        // Base button classes
                        var editButtonClass = 'btn btn-primary custom-btn';
                        var startButtonClass = 'btn btn-success custom-btn';
                        var stopButtonClass = 'btn btn-warning custom-btn';
                        var printButtonClass = 'btn btn-info custom-btn';

                        // Button enable/disable logic
                        if (row.start_time) {
                            startButtonClass += ' disabled';
                        }
                        if (!row.start_time || row.stop_time) {
                            stopButtonClass += ' disabled';
                        }


                        // if (row.employees_allow_check_in !== 0 && row.employee_approval !== 'accepted') {
                        //     startButtonClass += ' disabled';
                        //     stopButtonClass += ' disabled';
                        // }

                        if (row.employees_allow_check_in == 1) {
                            if (row.employee_approval === 'accepted') {
                                // ✅ Start enabled, Stop stays enabled
                                // do nothing (keep classes as is)
                            } else {
                                // ❌ Not accepted → disable both
                                startButtonClass += ' disabled';
                                stopButtonClass += ' disabled';
                            }
                        } else {
                            if (row.employee_approval === 'rejected') {
                                // ❌ Explicit reject → disable both
                                startButtonClass += ' disabled';
                                stopButtonClass += ' disabled';
                            } else {
                                // ✅ Any other case → both enabled
                                // do nothing (keep classes as is)
                            }
                        }


                        let disabled = row.visitors_name.trim() === '' ? 'disabled' : '';

                        // Buttons HTML
                        var editButton = `<a title="EDIT" href="${editUrl}" class="${editButtonClass}" ${disabled}>
                                            <i class="bx bx-pencil"></i>
                                            <span>Edit</span>
                                          </a>`;

                        var startButton = `<button title="CHECK IN" class="${startButtonClass} start-link" data-id="${row.id}" data-url="${startUrl}">
                                              <i class="${startButtonIcon}"></i>
                                              <span>Check In</span>
                                           </button>`;

                        var stopButton = `<button title="CHECK OUT" class="${stopButtonClass} stop-link" data-id="${row.id}" data-url="${stopUrl}">
                                              <i class="${stopButtonIcon}"></i>
                                              <span>Check Out</span>
                                          </button>`;

                        var printButton = `<button title="PRINT GATE PASS" id="printButton" class="${printButtonClass} print-link" data-id="${row.id}" data-url="${printUrl}" ${disabled}>
                                              <i class="bx bx-printer"></i>
                                              <span>Print</span>
                                          </button>`;

                        var visitorprintButton = '<button title="VISITOR PRINT PASS" id="visitorprintButton" class="btn btn-info visitorprint-link" data-id="' + row.id + '" data-url="' + visitorprintUrl + '" data-pass-type="visitor_pass" ' + disabled + '><i class="bx bx-printer"></i><span>Visitor Gate Pass</span></button>';

                        return editButton + startButton + stopButton + printButton + visitorprintButton;
                    }
                }

            ],
            "processing": true,
            "serverSide": true,
            "responsive": true,
            "ordering": false,
            "lengthMenu": [
                [10, 25, 50, 100],
                [10, 25, 50, 100]
            ],
            "layout": {
                "topStart": {
                    "buttons": [
                {
                    extend: 'csv',
                    text: 'Export' // Change this to your desired label
                },
                '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);-->
<!--                }-->
<!--            });-->
<!--        });-->
<!--          // ================= OPEN MODAL =================-->
<!--          $(document).on('click', '.stop-link', function () {-->
<!--              $('#stop_appointment_id').val($(this).data('id'));-->
<!--              setAutomaticDatetime(); // set local current time-->
<!--              $('#stopTimeModal').modal('show');-->
<!--          });-->

<!--          // ================= RADIO CHANGE =================-->
<!--          $('input[name="time_type"]').on('change', function () {-->
<!--              let minDatetime = getLocalDateTimeForInput();-->

<!--              if ($(this).val() === 'manual') {-->
<!--                  $('#manual_datetime')-->
<!--                      .prop('disabled', false)-->
<!--                      .attr('min', minDatetime)  // block past dates-->
<!--                      .val(minDatetime);-->
<!--              } else {-->
<!--                  setAutomaticDatetime();-->
<!--              }-->
<!--          });-->

<!--          // ================= SET AUTOMATIC DATETIME =================-->
<!--          function setAutomaticDatetime() {-->
<!--              let formattedDateTime = getLocalDateTimeForInput();-->

<!--              $('#manual_datetime')-->
<!--                  .prop('disabled', true)-->
<!--                  .removeAttr('min')-->
<!--                  .val(formattedDateTime);-->
<!--          }-->

<!--          // ================= LOCAL DATETIME FOR INPUT =================-->
<!--          // yyyy-MM-ddTHH:mm required for <input type="datetime-local">-->
<!--          function getLocalDateTimeForInput() {-->
<!--              let now = new Date();-->
<!--              let offset = now.getTimezoneOffset() * 60000;-->
<!--              let localTime = new Date(now - offset);-->
<!--              return localTime.toISOString().slice(0, 16);-->
<!--          }-->

<!--          // ================= SUBMIT STOP TIME =================-->
<!--          $('#submitStopTime').on('click', function () {-->
<!--              let appointmentId = $('#stop_appointment_id').val();-->
<!--              let timeType = $('input[name="time_type"]:checked').val();-->
<!--              let stopDatetime = $('#manual_datetime').val(); // e.g., "2026-01-02T11:30"-->

<!--              // Convert T → space for backend-->
<!--              if (stopDatetime) {-->
<!--                  stopDatetime = stopDatetime.replace('T', ' ');-->
<!--              }-->

<!--              console.log("Sending Data →", {-->
<!--                  time_type: timeType,-->
<!--                  manual_datetime: stopDatetime-->
<!--              });-->

<!--              $.ajax({-->
<!--                  url: `/gate_keeper/stop/${appointmentId}/`,-->
<!--                  type: 'POST',-->
<!--                  data: {-->
<!--                      time_type: timeType,-->
<!--                      manual_datetime: stopDatetime-->
<!--                  },-->
<!--                  success: function (res) {-->
<!--                      if (res.status === 'success') {-->
<!--                          $('#stopTimeModal').modal('hide');-->
<!--                          location.reload();-->
<!--                      } else {-->
<!--                          alert(res.message);-->
<!--                      }-->
<!--                  }-->
<!--              });-->
<!--          });-->
        // ================= OPEN MODAL =================
        $(document).on('click', '.stop-link', function () {
            $('#stop_appointment_id').val($(this).data('id'));

            // Check which radio is selected
            let selectedTimeType = $('input[name="time_type"]:checked').val();

            if (selectedTimeType === 'manual') {
                let minDatetime = getLocalDateTimeForInput();
                $('#manual_datetime')
                    .prop('disabled', false)
                    .attr('min', minDatetime);
            } else {
                setAutomaticDatetime();
            }

            $('#stopTimeModal').modal('show');
        });

        // ================= RADIO CHANGE =================
        $('input[name="time_type"]').on('change', function () {
            let minDatetime = getLocalDateTimeForInput();

            if ($(this).val() === 'manual') {
                $('#manual_datetime')
                    .prop('disabled', false)
                    .attr('min', minDatetime)
                    .val(minDatetime); // optionally prefill with current datetime
            } else {
                setAutomaticDatetime();
            }
        });

        // ================= SET AUTOMATIC DATETIME =================
        function setAutomaticDatetime() {
            let formattedDateTime = getLocalDateTimeForInput();

            $('#manual_datetime')
                .prop('disabled', true) // disable only for Automatic
                .removeAttr('min')
                .val(formattedDateTime);
        }

        // ================= LOCAL DATETIME FOR INPUT =================
        // yyyy-MM-ddTHH:mm required for <input type="datetime-local">
        function getLocalDateTimeForInput() {
            let now = new Date();
            let offset = now.getTimezoneOffset() * 60000;
            let localTime = new Date(now - offset);
            return localTime.toISOString().slice(0, 16);
        }

        // ================= SUBMIT STOP TIME =================
        $('#submitStopTime').on('click', function () {
            let appointmentId = $('#stop_appointment_id').val();
            let timeType = $('input[name="time_type"]:checked').val();
            let stopDatetime = $('#manual_datetime').val(); // e.g., "2026-01-02T11:30"

            // Convert T → space for backend
            if (stopDatetime) {
                stopDatetime = stopDatetime.replace('T', ' ');
            }

            console.log("Sending Data →", {
                time_type: timeType,
                manual_datetime: stopDatetime
            });

            $.ajax({
                url: `/gate_keeper/stop/${appointmentId}/`,
                type: 'POST',
                data: {
                    time_type: timeType,
                    manual_datetime: stopDatetime
                },
                success: function (res) {
                    if (res.status === 'success') {
                        $('#stopTimeModal').modal('hide');
                        location.reload();
                    } else {
                        alert(res.message);
                    }
                }
            });
        });

        $(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();

                    // Wait for the document to load and then print
                    printWindow.onload = function() {
                        printWindow.focus();
                        printWindow.print();
                    };

                },
                error: function(xhr, status, error) {
                    console.error('Error loading visitor details:', error);
                }
            });
        });
        $(document).on('click', '.visitorprint-link', function(e) {
            e.preventDefault();
            var id = $(this).data('id');
            var detailsUrl = $(this).data('url');
            var passType = $(this).data('pass-type');

            $.ajax({
                url: detailsUrl,
                type: 'GET',
                data: {
                    pass_type: passType  // Send the pass type as part of the GET request
                },
                success: function(response) {
                    var printWindow = window.open('', '_blank');
                    var printContent = response.html;
                    printWindow.document.write('<html><head><title>Visitor Pass</title></head><body>');
                    printWindow.document.write(printContent);
                    printWindow.document.write('</body></html>');
                    printWindow.document.close();
                    printWindow.onload = function() {
                        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 %}