<!---
Files component: template for displaying files and folders in a folder

Variables:
    - current_folder: the current folder
    - folders: list of folders in the current folder
    - files: list of files in the current folder
    - content_type_id: the content type id of the object
    - object_id: the id of the object
-->
{% load static %}
{% load i18n %}
{% load crispy_forms_tags %}
{% load bloomerp %}

<!--breadcrumb-->
<div class="d-flex my-2">
    <nav>
        {% if current_folder %}
            <a 
                hx-get="{% url 'components_files' %}?{% if content_type_id %}content_type_id={{ content_type_id }}&{% endif %}{% if object_id %}object_id={{ object_id }}{% endif %}"
                hx-trigger="click"
                hx-target="#{{ target }}"
                class="card-title pointer"
                >
                Root
            </a>
            <span class="card-title"> > </span>
        {% else %}
            <a 
                class="card-title pointer active" 
                aria-current="page"
                data-bs-toggle="dropdown"
                aria-haspopup="true"
                aria-expanded="false"
                >Root
                
            </a>
            <span class="card-title"> > </span>

            <div
                class="dropdown-menu dropdown-menu-start"
                aria-labelledby="triggerId"
                >   
                    <a class="dropdown-item pointer" data-bs-toggle="modal" data-bs-target="#uploadFileModal">Upload file</a>
                    <a class="dropdown-item pointer" data-bs-toggle="modal" data-bs-target="#createFolderModal">Create new folder</a>
            </div>
        {% endif %}

        {% for parent in current_folder.parents %}
            <a  
                hx-get="{% url 'components_files' %}?folder_id={{ parent.id }}&{% if content_type_id %}content_type_id={{ content_type_id }}&{% endif %}{% if object_id %}object_id={{ object_id }}{% endif %}"
                hx-trigger="click"
                hx-target="#{{target}}"
                class="card-title pointer"
                dropable="true"
                id = "folder_link_{{ parent.pk }}"
                >{{ parent.name }}</a>
            <span class="card-title"> > </span>
        {% endfor %}

        <!-- Current folder -->
        {% if current_folder %}
            <a 
                class="card-title active pointer" 
                aria-current="page"
                data-bs-toggle="dropdown"
                aria-haspopup="true"
                aria-expanded="false"
                id="currentFolderBreadcrumb"
            >{{ current_folder.name }}
            </a>
            <div
                class="dropdown-menu dropdown-menu-start"
                aria-labelledby="triggerId"
                >   
                    <a class="dropdown-item pointer" href="#" data-bs-toggle="modal" data-bs-target="#uploadFileModal">Upload file</a>
                    <a class="dropdown-item pointer" href="#" data-bs-toggle="modal" data-bs-target="#createFolderModal">Create new folder</a>
                    <a class="dropdown-item pointer" href="#" data-bs-toggle="modal" data-bs-target="#renameFolderModal">Rename folder</a>
                    <a class="dropdown-item pointer" href="#">Download</a>
                    <a class="dropdown-item pointer" data-bs-toggle="modal" data-bs-target="#deleteFolderModal">Delete folder</a>
            </div>


        {% endif %}
        <!-- End current folder -->
    </nav>
</div>
<!--End breadcrumb-->

<!-- File results -->
<div
    class="table-responsive overflow-auto"
    id="{{ target }}"
>
    <table
        class="table table-hover"
    >
        <thead>
            <tr>
                <th style="width=50px">
                    <input 
                        type="checkbox" 
                        name="file" 
                        id="fileAll"
                        onclick="selectAll(this)"
                        >
                </th>
                <th scope="col">
                    Name
                    <a href="#" 
                        class="bi bi-chevron-down"
                        onclick="sortFiles('name')"
                    ></a>
                </th>
                <th scope="col">Created by
                    <a href="#" 
                        class="bi bi-chevron-down"
                        onclick="sortFiles('created_by')"
                    ></a>
                </th>
                <th scope="col">Last modified
                    <a href="#" 
                        class="bi bi-chevron-down"
                        onclick="sortFiles('datetime_updated')"
                    ></a>
                </th>
                <th scope="col">File size</th>
                <th scope="col">Object</th>
                <th scope="col">Actions</th>
            </tr>
        </thead>
        <tbody
            id="fileTableBody"
            ondrop="tableDropHandler(event)"
            ondragover="tableDragoverHandler(event)"
            ondragleave="tableDragleaveHandler(event)"
        >
            <!-- Folders -->
            {% for folder in folders %}
                <tr
                    class="folder-row"
                    onmouseover="this.querySelector('.d-flex').classList.remove('d-none')"
                    onmouseout="this.querySelector('.d-flex').classList.add('d-none')"
                    draggable="true"
                    ondragover="folderDragOverHandler(event)"
                    ondragleave="folderDragLeaveHandler(event)"
                    ondrop="folderDropHandler(event)"
                    ondragstart="folderDragStartHandler(event)"
                    id = "folder_{{ folder.pk }}_row"
                >
                    <td>
                        
                    </td>
                    <td>
                        <i class="bi bi-folder" style="font-size:20"></i>
                        <a
                            hx-get="{% url 'components_files' %}?folder_id={{ folder.id }}&{% if content_type_id %}content_type_id={{ content_type_id }}&{% endif %}{% if object_id %}object_id={{ object_id }}{% endif %}"
                            hx-trigger="click"
                            hx-target="#{{target}}"
                            hx-swap="innerHTML"
                            class="href"
                        >
                        <span>&nbsp;&nbsp;{{ folder.name }}</span>
                        </a>
                    </td>
                    <td>{{ folder.created_by }}</td>
                    <td>{{folder.datetime_updated}}</td>
                    <td></td>
                    <td width="120px">
                        <div class="d-flex d-none justify-content-between">
                            
                        </div>
                    </td>
                    <td></td>
                </tr>
            {% endfor %}
            <!-- End folders -->

            <!-- Files -->
            {% if files %}
                {% for file in files %}
                <tr 
                    class="file-row"
                    onmouseover="this.querySelector('.d-flex').classList.remove('d-none')"
                    onmouseout="this.querySelector('.d-flex').classList.add('d-none')"
                    draggable="true"
                    ondragstart="fileDragStartHandler(event)"
                    data-id="{{ file.pk }}"
                    >
                    <td scope="row">
                        <input 
                            type="checkbox" 
                            name="selected_files" 
                            value="{{ file.pk }}"
                        >
                    </td>
                    <td>
                        <i class="bi bi-filetype-{{ file.file_extension }}" style="font-size:20"></i>
                        <a href="{{ file.file.url }}">&nbsp;&nbsp;{{ file.name }}</a>
                    </td>
                    <td>{{ file.created_by }}</td>
                    <td>{{ file.datetime_updated | date:request.user.datetime_view_preference }}</td>
                    <td>{{ file.size_str }}</td>

                    {% if file.content_object %}
                    <td>
                        <a
                            hx-get="{{ file.content_object | detail_view_url }}"
                            hx-target="#main-content"
                            hx-swap="innerHTML"
                            hx-trigger="click"
                            hx-push-url="true"
                            href="#"
                            >
                        {{ file.content_object }}
                        </a>
                    </td>

                    {% else %}
                    <td></td>
                    {% endif %}


                    <td width="120px">
                        <div class="d-flex d-none justify-content-between">
                            {% if file.file_extension == 'pdf' %}
                            <a
                                data-bs-target="#signPdfModal"
                                data-bs-toggle="modal"
                                data-bs-fileId="{{ file.pk }}"
                                onclick="document.getElementById('signatureFileId').value = '{{ file.pk }}'"
                                class="pointer"
                                draggable="false"
                                >
                                <img src="{% static 'bloomerp/icons/pen.svg' %}" alt="View" width="20" height="20">
                            </a>
                            {% endif %}
                            <a href="{{ file.file.url }}" draggable="false">
                                <img src="{% static 'bloomerp/icons/download.svg' %}" alt="Download" width="20" height="20">
                            </a>
                            <a href="#" draggable="false">
                                <img src="{% static 'bloomerp/icons/edit.svg' %}" alt="Edit" width="20" height="20">
                            </a>
                            <a href="#" data-bs-toggle="modal" data-bs-target="#deleteFileModal" data-bs-fileId="{{ file.pk }}" draggable="false">
                                <img src="{% static 'bloomerp/icons/delete.svg' %}" alt="Delete" width="20" height="20">
                            </a>
                        </div>
                    </td>
                </tr>
                {% endfor %}
            {% else %}
                <tr>
                    <td colspan="6">No files found</td>
                </tr>
            {% endif %}
            <!-- End files -->
        </tbody>
    </table>

    <!--Bulk actions-->
    <div class="save-layout-div d-none" id="bulk-actions">
        <div class="dropup">
            <button
                class="btn btn-primary dropdown-toggle"
                type="button"
                id="bulkActionsButton"            
                data-bs-toggle="dropdown"
                aria-haspopup="true"
                aria-expanded="false"
            >
                Bulk actions on <span id="selectedObjectsCount"></span> objects
            </button>
            <div class="dropdown-menu" aria-labelledby="bulkActionsButton">
                <a class="dropdown-item pointer"
                    data-bs-toggle="modal"
                    data-bs-target="#bulkShareModal"
                >Share</a>
                <a class="dropdown-item pointer"
                    data-bs-toggle="modal"
                    data-bs-target="#bulkDeleteModal"
                >Delete</a>
                <a class="dropdown-item pointer"
                    data-bs-toggle="modal"
                    data-bs-target="#bulkDownloadModal"
                >Download</a>
                <a class="dropdown-item pointer">Bookmark</a>
            </div>
        </div>
    </div>
    <!--End Bulk actions-->
</div>
<!-- End file results -->

<!--Hidden inputs for JS-->
<input type="hidden" id="file_table_content_type_id" value="{{ content_type_id }}">
<input type="hidden" id="file_table_object_id" value="{{ object_id }}">
<input type="hidden" id="file_table_current_folder_id" value="{{ current_folder.pk }}">
<input type="hidden" id="file_table_url" value="{{ url}}">
<input type="hidden" id="file_table_user_id" value="{{ request.user.pk }}">
<input type="hidden" id="file_table_folder_api_url" value="{% url 'file_folders-list' %}">
<input type="hidden" id="file_table_file_api_url" value="{% url 'files-list' %}">
<input type="hidden" id="csrf_token" value="{{ csrf_token }}">
<input type="hidden" id="file_table_sort" value="{{sort}}">
<input type="hidden" id="file_table_target" value="#{{ target }}">
<!--End hidden inputs for JS-->


{% if current_folder %}
<!--Rename folder modal-->
<div
    class="modal fade"
    id="renameFolderModal"
    tabindex="-1"
    role="dialog"
    aria-labelledby="modalTitleId"
    aria-hidden="true"
>
    <div
        class="modal-dialog modal-dialog-scrollable modal-dialog-centered modal-sm"
        role="document"
    >
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitleId">
                    Rename folder
                </h5>
                <button
                    type="button"
                    class="btn-close"
                    data-bs-dismiss="modal"
                    aria-label="Close"
                ></button>
            </div>
            <form 
                hx-patch="{% url 'file_folders-detail' current_folder.pk %}"
                hx-trigger="submit"
                hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'
                hx-swap="none"
                hx-target="this"
                autocomplete="off"
            >
                <div class="modal-body">
                    <input
                        type="text"
                        class="form-control"
                        placeholder="Folder name"
                        value="{{ current_folder.name }}"
                        name="name"
                        id="renameFolderInput"
                    >
                    <input type="hidden" name="updated_by" value="{{ request.user.pk }}">
                </div>
                <div class="modal-footer">
                    <button
                        type="button"
                        class="btn btn-secondary"
                        data-bs-dismiss="modal"
                    >
                        Close
                    </button>
                    <button type="submit" class="btn btn-primary" id="renameFolderButton" data-bs-dismiss="modal">Save</button>
                </div>
            </form>
        </div>
    </div>
</div>
<!--End Rename folder modal-->

<!--Delete folder modal-->
<div
    class="modal fade"
    id="deleteFolderModal"
    tabindex="-1"
    role="dialog"
    aria-labelledby="modalTitleId"
    aria-hidden="true"
>
    <div
        class="modal-dialog modal-dialog-scrollable modal-dialog-centered modal-sm"
        role="document"
    >
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitleId">
                    Delete folder
                </h5>
                <button
                    type="button"
                    class="btn-close"
                    data-bs-dismiss="modal"
                    aria-label="Close"
                ></button>
            </div>
            <form 
                hx-delete="{% url 'file_folders-detail' current_folder.pk %}"
                hx-trigger="submit"
                hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'
                hx-swap="none"
                hx-target="this"
                autocomplete="off"
            >
                <div class="modal-body">
                    <p>Are you sure you want to delete this folder?</p>
                </div>
                <div class="modal-footer">
                    <button
                        type="button"
                        class="btn btn-secondary"
                        data-bs-dismiss="modal"
                    >
                        Close
                    </button>
                    <button type="submit" class="btn btn-danger" id="deleteFolderButton" data-bs-dismiss="modal">Delete</button>
                </div>
            </form>
        </div>
    </div>
</div>
<!--End Delete folder modal-->

<form id="currentFolderForm">
    <input type="hidden" name="folder_id" value="{{ current_folder.pk }}">
</form>

{% endif %}


<!--Create folder modal-->
<div
    class="modal fade"
    id="createFolderModal"
    tabindex="-1"
    role="dialog"
    aria-labelledby="modalTitleId"
    aria-hidden="true"
>
    <div
        class="modal-dialog modal-dialog-scrollable modal-dialog-centered"
        role="document"
    >
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitleId">
                    Create new folder
                </h5>
                <button
                    type="button"
                    class="btn-close"
                    data-bs-dismiss="modal"
                    aria-label="Close"
                ></button>
            </div>
            <form 
                hx-post="{% url 'file_folders-list' %}"
                hx-trigger="submit"
                hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'
                hx-swap="none"
                hx-target="this"
                autocomplete="off"
            >
                <div class="modal-body">
                    {{ create_folder_form | crispy}}
                    <input 
                        type="hidden" 
                        name="parent" 
                        {% if current_folder %} value="{{ current_folder.pk }}" {% endif %}
                    >
                    <input type="hidden" name="created_by" value="{{ request.user.pk }}">
                    <input type="hidden" name="updated_by" value="{{ request.user.pk }}">
                </div>
                <div class="modal-footer">
                    <button
                        type="button"
                        class="btn btn-secondary"
                        data-bs-dismiss="modal"
                    >
                        Close
                    </button>
                    <button type="submit" class="btn btn-primary" id="createFolderButton" data-bs-dismiss="modal">Create</button>
                </div>
            </form>
        </div>
    </div>
</div>
<!--End Create folder modal-->


<!--Delete file modal-->
<div
    class="modal fade"
    id="deleteFileModal"
    tabindex="-1"
    role="dialog"
    aria-labelledby="modalTitleId"
    aria-hidden="true"
>
    <div
        class="modal-dialog modal-dialog-scrollable modal-dialog-centered modal-sm"
        role="document"
    >
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitleId">
                    Delete file
                </h5>
                <button
                    type="button"
                    class="btn-close"
                    data-bs-dismiss="modal"
                    aria-label="Close"
                ></button>
            </div>
            <form 
                id="deleteFileForm"
            >
                <div class="modal-body">
                    <p>Are you sure you want to delete this file?
                    </p>
                </div>
                <div class="modal-footer">
                    <button
                        type="button"
                        class="btn btn-secondary"
                        data-bs-dismiss="modal"
                    >
                        Close
                    </button>
                    <button type="submit" class="btn btn-danger" id="deleteFileButton" data-bs-dismiss="modal">Delete</button>
                </div>
            </form>
        </div>
    </div>
</div>
<script>
    var deleteFileModal = document.getElementById('deleteFileModal');

    deleteFileModal.addEventListener('show.bs.modal', async function (event) {
        // Button that triggered the modal
        let button = event.relatedTarget;
        // Extract info from data-bs-* attributes
        let fileId = button.getAttribute('data-bs-fileId');
        
        // Get the form and init everything for HTMX as it will otherwise not work
        var deleteFileForm = document.getElementById('deleteFileForm');

        deleteFileForm.addEventListener('submit', async function(event) {
            event.preventDefault();
            await deleteFile(fileId);

            // Refresh the files
            refreshFiles('#{{ target }}');

            // Show a message
            showMessage('File deleted successfully', 'success');
        });
    });

    

</script>

<!--Upload file modal-->
<div
    class="modal fade"
    id="uploadFileModal"
    tabindex="-1"
    role="dialog"
    aria-labelledby="modalTitleId"
    aria-hidden="true"
>
    <div
        class="modal-dialog modal-dialog-scrollable modal-dialog-centered modal-sm"
        role="document"
    >
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitleId">
                    Upload file
                </h5>
                <button
                    type="button"
                    class="btn-close"
                    data-bs-dismiss="modal"
                    aria-label="Close"
                ></button>
            </div>
            <form 
                hx-post="{% url 'files-list' %}"
                hx-trigger="submit"
                hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'
                hx-swap="none"
                hx-target="this"
                enctype="multipart/form-data"
                id="uploadFileForm"
            >
                <div class="modal-body">
                    <input
                        type="file"
                        class="form-control"
                        name="file"
                        id="uploadFileInput"
                    >
                    <input 
                        type="hidden" 
                        name="created_by" 
                        value="{{ request.user.pk }}">
                    <input type="hidden" name="updated_by" value="{{ request.user.pk }}">
                    <input 
                        type="hidden" 
                        name="content_type"
                        {% if content_type_id %}value="{{ content_type_id }}"{% endif %}
                    >
                    <input 
                        type="hidden" 
                        name="object_id"
                        {% if object_id %}value="{{ object_id }}"{% endif %}
                        >
                </div>
                <div class="modal-footer">
                    <button
                        type="button"
                        class="btn btn-secondary"
                        data-bs-dismiss="modal"
                    >
                        Close
                    </button>
                    <button type="submit" class="btn btn-primary" id="uploadFileButton" data-bs-dismiss="modal">Upload</button>
                </div>
            </form>
        </div>
    </div>
</div>
<script>
    document.getElementById('uploadFileForm').addEventListener('htmx:afterRequest', function(evt) {
        // Get the id of the file
        var resp = evt.detail.xhr.response
        
        var file_id = JSON.parse(resp).id;
        
        var current_folder = null;

        // If there is a current folder, add the file to the current folder
        {% if current_folder %}
            // Get all of the files in the current folder
            fetch('{% url 'file_folders-detail' current_folder.pk %}')
                .then(response => response.json())
                .then(data => {
                    current_folder = data;

                    // Add the file to the current folder
                    current_folder.files.push(file_id);

                    // Update the current folder
                    fetch('{% url 'file_folders-detail' current_folder.pk %}', {
                        method: 'PATCH',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRFToken': '{{ csrf_token }}'
                        },
                        body: JSON.stringify(current_folder)
                    });

                    // Wait for the folder to be updated
                    setTimeout(() => {
                        refreshFiles('#{{ target }}');
                        showMessage('File uploaded successfully', 'success');
                    }, 1000);
                    return;

                });
        {% else %}
            refreshFiles();
        {% endif %}


    });
</script>
<!--End Upload file modal-->

<!--Bulk delete modal-->
<div
    class="modal fade"
    id="bulkDeleteModal"
    tabindex="-1"
    role="dialog"
    aria-labelledby="modalTitleId"
    aria-hidden="true"
>
    <div
        class="modal-dialog modal-dialog-scrollable modal-dialog-centered modal-sm"
        role="document"
    >
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitleId">
                    Delete files
                </h5>
                <button
                    type="button"
                    class="btn-close"
                    data-bs-dismiss="modal"
                    aria-label="Close"
                ></button>
            </div>
            <form 
                id="bulkDeleteForm"
                hx-post="{% url 'components_bulk_update_objects' %}?content_type_id={{ file_content_type_id }}&form_prefix=bulk_delete"
                hx-trigger="submit"
                hx-target="this"
                hx-swap="none"
                >
                {% csrf_token %}
                <div class="modal-body">
                    <p>Are you sure you want to delete the selected files?</p>
                    
                    <!--Object Ids-->
                    <div id="bulkDeleteIds" class="d-none"></div>
                    <!--End Object Ids-->

                    <input type="hidden" name="delete_objects" value="true">

                </div>
                <div class="modal-footer">
                    <button
                        type="button"
                        class="btn btn-secondary"
                        data-bs-dismiss="modal"
                    >
                        Close
                    </button>
                    <button type="submit" class="btn btn-danger" id="bulkDeleteButton" data-bs-dismiss="modal">Delete</button>
                </div>
            </form>
        </div>
    </div>
</div>
<!--End Bulk delete modal-->

<!--Sign pdf modal-->
<div
    class="modal fade"
    id="signPdfModal"
    tabindex="-1"
    data-bs-backdrop="static"
    data-bs-keyboard="false"
    role="dialog"
    aria-labelledby="signPdfModalTitle"
    aria-hidden="true"
>
    <div
        class="modal-dialog   modal-lg"
        role="document"
    >
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="signPdfModalTitle">
                    Sign PDF
                </h5>
                <button
                    type="button"
                    class="btn-close"
                    data-bs-dismiss="modal"
                    aria-label="Close"
                ></button>
            </div>
            <div class="modal-body">
                <form method="POST" action="{% url "components_sign_file" %}">
                    {% csrf_token %}

                    <input type="hidden" name="file_id" id="signatureFileId" value="">
                    
                    {% include "snippets/signature_snippet.html" with signature_field_name="signature" %}

                    <div class="d-flex justify-content-center">
                        <button type="submit" class="btn btn-primary">Sign</button>
                    </div>

                </form>
            </div>
            <div class="modal-footer">
                <button
                    type="button"
                    class="btn btn-secondary"
                    data-bs-dismiss="modal"
                >
                    Close
                </button>
            </div>
        </div>
    </div>
</div>
<!--End Sign pdf modal-->




<!--END MODALS -->
<script src="{% static 'bloomerp/js/files.js' %}"></script>

