{% extends 'dashboard/employee_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 alert-dismissible{% elif 'danger' in message.tags %}alert-danger alert-dismissible{% endif %}" 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="all_visitor">
            <thead>
              <tr>
                <th>ID</th>
                <th>First Name</th>
                <th>Email</th>
                <th>Image</th>
                <th>Mobile</th>
                <th>Date</th>
                <th>Time</th>
                <th>Status</th>
                <th>Created At</th>
                <th>Updated At</th>
                <th>Purpose</th>
                <th>Details</th>
                <th>Visitor Type</th>
                <th>Visitor Timing</th>
                <th>Action</th>
              </tr>
            </thead>
          </table>
          {% csrf_token %}
        </div>
      </div>
    </div>
</div>

<!-- Rejection Modal -->
<div class="modal fade" id="openRejectionModal" tabindex="-1" aria-labelledby="rejectionModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="rejectionModalLabel">Reject Appointment</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="rejectionForm">
                    <input type="hidden" id="appointmentId" name="appointment_id">
                    <div class="form-group">
                        <label for="reason">Reason</label>
                        <input type="text" class="form-control" id="reason" name="reason" required>
                    </div>
                    <div class="form-group">
                        <label for="date">Date</label>
                        <input type="date" class="form-control" id="datepicker" name="date" required>
                    </div>
                    <div class="form-group">
                        <label for="time">Time</label>
                        <input type="text" class="form-control" id="timepicker" name="time" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="submitRejection">Submit</button>
            </div>
        </div>
    </div>
</div>

<!-- Scripts -->
<script src="{% static 'plugins/fastclick/fastclick.min.js' %}"></script>
<link rel="stylesheet" href="{% static 'default/header/flatpickr.min.css' %}">
<script src="{% static 'default/header/flatpickr.js' %}"></script>
<script src="{% static 'plugins/jQuery/jquery-3.6.0.min.js' %}"></script>
<script src="{% static 'select2/js/select2.min.js' %}"></script>
<script src="{% static 'plugins/dataTables.buttons.min.js' %}"></script>
<script src="{% static 'plugins/buttons.html5.min.js' %}"></script>
<script>
function openRejectionModal(appointmentId) {
    console.log('Opening rejection modal for appointment ID:', appointmentId);
    $('#appointmentId').val(appointmentId);
    $('#openRejectionModal').modal('show');
}

$(document).ready(function() {
    // Retrieve CSRF token
    var csrfToken = $('input[name=csrfmiddlewaretoken]').val();

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

    // Initialize DataTable
    var ajaxUrl = "{% url 'employee_visitore_ajax_page_ajax' %}";
    $('#all_visitor').DataTable({
        "ajax": {
            "url": ajaxUrl,
            "type": "POST"
        },
        "columns": [
            { data: 'id' },
            { data: 'visitors_first_name' },
            { data: 'visitors_email' },
            {
                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: 'date' },
            { data: 'time' },
            { data: 'status' },
            { data: 'created_at' },
            { data: 'updated_at' },
            {
                data: 'purpose',
                render: function(data) {
                    return data ? data : '';
                }
            },
            {
                data: 'detail',
                render: function(data) {
                    return data ? data : '';
                }
            },
            { data: 'visitors_type' },
            { data: 'visitors_timing' },
            {
                data: null,
                render: function(data, type, row) {
                    let disabled = row.visitors_first_name.trim() === '' ? 'disabled' : '';
                    return `
                        <button class="btn btn-info accept-btn" data-id="${row.id}" ${disabled}>
                            <i class="bx bx-check-square" title="Accept"></i>
                        </button>
                        <button class="btn btn-danger reject-btn" data-id="${row.id}">
                            <i class="bx bxs-x-circle" title="Reject"></i>
                        </button>
                    `;
                }
            }
        ],
        "processing": true,
        "serverSide": true,
        "responsive": true,
        "ordering": false,
        lengthMenu: [
            [10, 25, 50, 100],
            [10, 25, 50, 100]
        ],
        layout: {
            topStart: {
                buttons: ['csv', 'pageLength']
            }
        }
    });

    // Initialize Flatpickr for timepicker
    flatpickr("#timepicker", {
        enableTime: true,
        noCalendar: true,
        dateFormat: "h:i K",
        time_24hr: false
    });

    // Set minimum date for datepicker
    var dateInput = document.getElementById('datepicker');
    var today = new Date().toISOString().split('T')[0];
    dateInput.setAttribute('min', today);

    // Event delegation for accept and reject buttons
    $('#all_visitor').on('click', '.accept-btn', function() {
        let appointmentId = $(this).data('id');
        changeStatus(appointmentId, 'accepted');
    });

    $('#all_visitor').on('click', '.reject-btn', function() {
        let appointmentId = $(this).data('id');
        $('#appointmentId').val(appointmentId);
        $('#openRejectionModal').modal('show');
    });

    // Reset form on modal close
    $('#openRejectionModal').on('hidden.bs.modal', function() {
        $('#rejectionForm')[0].reset();
        $('#appointmentId').val('');
    });

    // Change status AJAX
    function changeStatus(appointmentId, status) {
        $.ajax({
            url: '/api/status_changes',
            type: 'POST',
            data: {
                'appointment_id': appointmentId,
                'status': status
            },
            success: function(response) {
                if (response.status === 'true') {
                    alert('Status updated successfully.');
                    location.reload();
                } else {
                    alert('Error: ' + response.message);
                }
            },
            error: function(xhr, status, error) {
                alert('An error occurred: ' + error);
            }
        });
    }

    // Submit rejection form
    $('#submitRejection').click(function() {
        var appointmentId = $('#appointmentId').val();
        var reason = $('#reason').val();
        var date = $('#datepicker').val();
        var time = $('#timepicker').val();

        $.ajax({
            url: '/api/status_changes',
            type: 'POST',
            data: {
                'appointment_id': appointmentId,
                'status': 'rejected',
                'reason': reason,
                'date': date,
                'time': time
            },
            success: function(response) {
                if (response.status === 'true') {
                    alert('Status updated successfully.');
                    location.reload();
                } else {
                    alert('Error: ' + response.message);
                }
            },
            error: function(xhr, status, error) {
                alert('An error occurred: ' + error);
            }
        });

        $('#openRejectionModal').modal('hide');
    });
});
</script>
{% endblock %}