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

<h4 class="fw-bold py-3 mb-4"><span class="text-muted fw-light">Masters / Department /</span> All Department</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="mt-3 d-flex justify-content-start">
               <a href="{% url 'admin_department_add' %}" class="btn btn-primary" style="margin: 10px;">
            Add Department</a>
            <!-- Updated for Bootstrap 5: data-bs-toggle and data-bs-target -->
            <button id="upload-csv" class="btn btn-info" style="margin: 10px;" data-bs-toggle="modal" data-bs-target="#csvUploadModal">Import Department</button>
          </div>

        <div class="table-responsive" style="margin: 10px;">
          <table class="table table-bordered table-striped" id="department_table" style="width: 100%;">
            <thead>
              <tr>
                <th>ID</th>
                <th>DEPARTMENT NAME</th>
                <th>DEPARTMENT CODE</th>
                <th>DEPARTMENT COLOR CODE</th>
                <th>COMPANY</th>
                <th>LOCATION</th>
                <th>CREATED AT</th>
                <th>UPDATED AT</th>
                <th>ACTION</th>
              </tr>
            </thead>
          </table>
          {% csrf_token %}
        </div>
      </div>
    </div>
</div>
<!-- CSV Upload Modal -->
<div class="modal fade" id="csvUploadModal" tabindex="-1" aria-labelledby="csvUploadModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content custom-modal">
      <div class="modal-header">
        <h5 class="modal-title" id="csvUploadModalLabel">Upload Departments via CSV</h5>
        <!-- Updated for Bootstrap 5: data-bs-dismiss -->
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</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_department.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">
        <!-- Updated for Bootstrap 5: data-bs-dismiss -->
        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
      </div>
    </div>
  </div>
</div>

<!-- Ensure jQuery is loaded before Bootstrap and DataTables -->
<script src="{% static 'plugins/jQuery/jQuery-2.1.3.min.js' %}" type="text/javascript"></script>
<script src="{% static 'dist/js/pages/department_delete.js' %}" type="text/javascript"></script>
<!-- Custom CSS for Modal -->
<link rel="stylesheet" href="{% static 'css/custom.css' %}">
<script>
$(document).ready(function() {
    var csrfToken = $('input[name=csrfmiddlewaretoken]').val();

    // Set up CSRF token for AJAX requests
    $.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 'admin_department_ajax_page_ajax' %}";
    var table = $('#department_table').DataTable({
        "ajax": {
            "url": ajaxUrl,
            "type": "POST"
        },
        "columns": [
            { data: 'id' },
            { data: 'department_name' },
            { data: 'department_code' },
            {
              data: 'department_color_code',
              render: function(data, type, row) {
                  // If the data is a valid color code, render a color box
                  return `<div style="width: 30px; height: 30px; background-color: ${data}; border: 1px solid #000;" title="${data}"></div>`;
              }
            },
            { data: 'company_name' },
            { data: 'location_name' },
            { data: 'created_at' },
            { data: 'updated_at' },
            { data: null,
             render: function(data, type, row) {
                    var editUrl = "{% url 'admin_department_edit' 0 %}".replace('0', row.id);
                    var deleteUrl = "{% url 'admin_department_delete' 0 %}".replace('0', row.id);
                    return `
                        <a title="EDIT" href="${editUrl}" class="btn btn-primary"><i class="bx bx-pencil"></i></a>
                        <button title="DELETE" class="btn btn-danger delete-link" data-id="${row.id}" value="${deleteUrl}"><i class="bx bx-trash"></i></button>
                    `;
                }
             }
        ],
        "processing": true,
        "serverSide": true,
        "responsive": true,
        "ordering": false,
        lengthMenu: [
          [10, 25, 50, 100],
          [10, 25, 50, 100]
        ],
        layout: {
          topStart: {
            buttons: [
                {
                  extend: 'csv',
                  text: 'Export'
                },
                'pageLength'
              ]
          }
        }
    });

    // Clear file input when modal is closed
    function clearFileInput() {
        $('#csvFile').val('');
        $('.file-name').text('No file chosen');
    }

    // Handle CSV form submission
    $('#csvUploadForm').on('submit', function(e) {
        e.preventDefault();
        var file = $('#csvFile')[0].files[0];
        if (file && file.size > 5 * 1024 * 1024) {
            alert("File size exceeds 5MB limit.");
            return;
        }

        var formData = new FormData(this);
        $.ajax({
            url: "{% url 'admin_department_csv_upload' %}", // Updated with proper URL
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                $('#csvUploadModal').modal('hide');
                clearFileInput();
                table.ajax.reload();

                if (response.status === 'success') {
                    $('<div class="alert alert-success alert-dismissible" role="alert">' + response.message + '<button type="button" class="btn-close" data-bs-dismiss="alert">&times;</button></div>').insertBefore('.content-header').delay(5000).fadeOut();

                    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);
                        $('<div class="alert alert-warning alert-dismissible" role="alert">Some rows failed to upload. Error report downloaded.<button type="button" class="btn-close" data-bs-dismiss="alert">&times;</button></div>').insertBefore('.content-header').delay(5000).fadeOut();
                    }
                } else {
                    $('<div class="alert alert-danger alert-dismissible" role="alert">' + response.message + '<button type="button" class="btn-close" data-bs-dismiss="alert">&times;</button></div>').insertBefore('.content-header').delay(5000).fadeOut();
                }
            },
            error: function(xhr) {
                var errorMessage = xhr.responseJSON?.message || 'An error occurred during file upload.';
                $('#csvUploadModal').modal('hide');
                clearFileInput();
                $('<div class="alert alert-danger alert-dismissible" role="alert">' + errorMessage + '<button type="button" class="btn-close" data-bs-dismiss="alert">&times;</button></div>').insertBefore('.content-header').delay(5000).fadeOut();
            }
        });
    });

    // Update file name display on file selection
    $('#csvFile').on('change', function() {
        var fileName = this.files.length > 0 ? this.files[0].name : 'No file chosen';
        $(this).closest('.custom-file-upload').find('.file-name').text(fileName);
    });

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

    // Clear file input when modal is hidden
    $('#csvUploadModal').on('hidden.bs.modal', clearFileInput);
});
</script>
{% endblock %}