
{% load static %}
{% include 'dashboard/admin_dashboard/header.html' %}
{% include 'dashboard/admin_dashboard/body.html' %}
<!-- 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">
              {{message}}
              <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                  <span aria-hidden="true">×</span>
              </button>
          </div>
          {% endfor %}
      {% endif %}
    </div>
    <section class="content-header">
      <h1>
        User Management
        <small>Control panel</small>
      </h1>
      <ol class="breadcrumb">
        <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
        <li class="active">User Management</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>
            <a href="{% url 'admin_user_add' %}" class="btn btn-primary" style="margin: 10px;">Add User</a>
            <button id="upload-csv" class="btn btn-success" style="margin: 10px;" data-toggle="modal" data-target="#csvUploadModal">Import User</button>
            <div class="table-responsive" style="margin: 10px;">
              <table id="user_table" class="table table-bordered table-striped" style="width:100%;">
                <thead>
                  <tr>
                    <th>ID</th>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Employee Code</th>
                    <th>Email</th>
                    <th>Image</th>
                    <th>Company</th>
                    <th>Department</th>
                    <th>Location</th>
                    <th>Role</th>
                    <th>Designation</th>
                    <th>Status</th>
                    <th>Action</th>
                  </tr>
                </thead>
              </table>
              {% csrf_token %}
            </div>
          </div>
        </div>
      </div>
    </section>
</div>

<!-- CSV Upload Modal -->
<div class="modal fade" id="csvUploadModal" tabindex="-1" role="dialog" aria-labelledby="csvUploadModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content custom-modal">
      <div class="modal-header">
        <h5 class="modal-title" id="csvUploadModalLabel">Upload Users via CSV</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <div class="modal-body">
        <div class="csv-info mb-3">
          <p class="text-muted">Upload a CSV file in the correct format. <a href="{% static 'csv/demo_users.csv' %}" class="text-primary font-weight-bold">Download sample CSV</a> to see the required format.</p>
        </div>
        <form id="csvUploadForm" enctype="multipart/form-data">
          <div class="form-group">
            <label for="csvFile" class="form-label">Select CSV File</label>
            <div class="custom-file-upload">
              <input type="file" class="form-control-file" id="csvFile" name="csv_file" accept=".csv" required>
              <span class="file-name">No file chosen</span>
              <button type="button" class="btn btn-outline-secondary btn-sm choose-file">Choose File</button>
            </div>
            <small class="form-text text-muted mt-2">Only .csv files are accepted (max size: 5MB).</small>
          </div>
          {% csrf_token %}
          <button type="submit" class="btn btn-primary btn-upload w-100">Upload CSV</button>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline-secondary" data-dismiss="modal">Cancel</button>
      </div>
    </div>
  </div>
</div>

{% include 'dashboard/visitors_dashboard/footer.html' %}

<!-- Custom CSS for Modal -->
<link rel="stylesheet" href="{% static 'css/custom.css' %}">

<!-- JavaScript -->
<script src="{% static 'dist/js/pages/user_delete.js' %}" type="text/javascript"></script>
<script>

  $(document).ready(function() {
  // Retrieve CSRF token value from the hidden input
  var csrfToken = $('input[name=csrfmiddlewaretoken]').val();
  console.log("CSRF Token: ", csrfToken);

  // Set up AJAX to include the CSRF token in the headers for non-GET requests
  $.ajaxSetup({
    beforeSend: function(xhr, settings) {
      if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
        xhr.setRequestHeader("X-CSRFToken", csrfToken);
        console.log("CSRF Token set in header: ", csrfToken);
      }
    }
  });

  // Define the AJAX URL for user data
  var ajaxUrl = "{% url 'admin_user_ajax_page_ajax' %}";
  console.log("AJAX URL: ", ajaxUrl);

  // Initialize DataTable with server-side processing
  var table = $('#user_table').DataTable({
    "ajax": {
      "url": ajaxUrl,
      "type": "POST"
    },
    "columns": [
      { data: 'id' },
      { data: 'first_name' },
      { data: 'last_name' },
      { data: 'employee_code' },
      { data: 'email' },
      {
        data: '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: 'company_name' },
      { data: 'department_name' },
      { data: 'location_name' },
      { data: 'type' },
      {
        data: 'allow_check_in',
        render: function(data, type, row) {
          return data == 1 ? 'Yes' : 'No';
        }
      },
      {
        data: 'is_active',
        render: function(data, type, row) {
          return data == 1 ? 'Active' : 'Inactive';
        }
      },
      {
        data: null,
        render: function(data, type, row) {
          var editUrl = "{% url 'admin_user_edit' 0 %}".replace('0', row.id);
          var deleteUrl = "{% url 'admin_user_delete' 0 %}".replace('0', row.id);
          var editButton = '<a title="EDIT" href="' + editUrl + '" class="btn btn-primary" data-toggle="tooltip" data-placement="top" title="Edit"><i class="fa fa-pencil"></i></a>';
          var deleteButton = '<button title="DELETE" class="btn btn-danger delete-link" data-id="' + row.id + '" value="' + deleteUrl + '"><i class="fa fa-trash-o"></i></button>';
          return editButton + ' ' + deleteButton;
        }
      }
    ],
    "processing": true,
    "serverSide": true,
    "responsive": true,
    "ordering": false,
    lengthMenu: [
      [10, 25, 50, 100],
      [10, 25, 50, 100]
    ],
    layout: {
      topStart: {
        buttons: ['csv', 'pageLength']
      }
    }
  });

  // Function to clear file input
  function clearFileInput() {
    $('#csvFile').val('');
    $('.file-name').text('No file chosen');
  }

  // Handle CSV file upload
  $('#csvUploadForm').on('submit', function(e) {
    e.preventDefault();
    var formData = new FormData(this);
    $.ajax({
      url: "{% url 'admin_user_csv_upload' %}",
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      success: function(response, status, xhr) {
        console.log("AJAX Response:", response); // Debug response
        $('#csvUploadModal').modal('hide');
        clearFileInput();
        table.ajax.reload(); // Refresh table to show new users

        // Handle success response (with or without failed rows)
        if (response.status === 'success') {
          var countMessage = response.count !== undefined ? ` (${response.count} users added)` : '';
          $('<div class="alert alert-success" role="alert">' + response.message + countMessage + '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button></div>')
            .insertBefore('.content-header')
            .delay(5000)
            .fadeOut();

          // Handle failed rows Excel download
          if (response.failed_rows_excel) {
            var binary = atob(response.failed_rows_excel);
            var array = new Uint8Array(binary.length);
            for (var i = 0; i < binary.length; i++) {
              array[i] = binary.charCodeAt(i);
            }
            var blob = new Blob([array], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
            var link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = response.failed_rows_filename || 'failed_uploads.xlsx';
            link.click();
            window.URL.revokeObjectURL(link.href); // Clean up
            $('<div class="alert alert-warning" role="alert">Some rows failed to upload. Downloaded error report (Excel).<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button></div>')
              .insertBefore('.content-header')
              .delay(5000)
              .fadeOut();
          }
        } else {
          $('<div class="alert alert-danger" role="alert">' + response.message + '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button></div>')
            .insertBefore('.content-header')
            .delay(5000)
            .fadeOut();
        }
      },
      error: function(xhr, status, error) {
        var errorMessage = xhr.responseJSON && xhr.responseJSON.message ? xhr.responseJSON.message : 'An error occurred while uploading the file.';
        $('#csvUploadModal').modal('hide');
        clearFileInput();
        $('<div class="alert alert-danger" role="alert">' + errorMessage + '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button></div>')
          .insertBefore('.content-header')
          .delay(5000)
          .fadeOut();
      }
    });
  });

  // Clear file input when modal is closed
  $('#csvUploadModal').on('hidden.bs.modal', function() {
    clearFileInput();
  });

  // Update file name display when a file is selected
  $('#csvFile').on('change', function() {
    var fileName = this.files.length > 0 ? this.files[0].name : 'No file chosen';
    $(this).siblings('.file-name').text(fileName);
  });

  // Trigger file input click when "Choose File" button is clicked
  $('.choose-file').on('click', function() {
    $(this).siblings('#csvFile').click();
  });
});
</script>