{% extends "base.html" %}

{% block title %}Browse Ghosts{% endblock title %}


{% block js %}
{% include "datatables.html" %}
{% endblock js %}

{% block content %}
<div class="columns">
    <div class="column col-12">
        <h1>Browse Ghosts</h1>
    </div>
</div>
<div class="columns">
    <div class="column col-12">
        <table id="ghosts-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>First</th>
                    <th>Middle</th>
                    <th>Last</th>
                    <th>Birthdate</th>
                    <th>Owner</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>
</div>
{% endblock content %}

{% block bottomjs %}
<script>
    $(document).ready(function () {
        $('#ghosts-table').DataTable({
            "processing": true,
            "serverSide": true,
            "ajax": {
                "url": "/ghosts",
                "type": "POST",
                "dataType": "json"
            },
            "columns": [
                {
                    "data": "Ghost.id",
                    "render": function (data, type, row, meta) {
                        return '<a href="/ghosts/' + data + '">' + data + '</a>';
                    }
                },
                { "data": "Ghost.first_name" },
                { "data": "Ghost.middle_name" },
                { "data": "Ghost.last_name" },
                {
                    "data": "Ghost.birthdate",
                    "render": function (data, type, row, meta) {
                        var date = new Date(data);
                        var day = date.getDate().toString().padStart(2, '0');
                        var month = (date.getMonth() + 1).toString().padStart(2, '0');
                        var year = date.getFullYear().toString();
                        return month + '/' + day + '/' + year;
                    }
                },
                {
                    "data": "owner_username",
                    "render": function (data, type, row, meta) {
                        return '<a href="/manage/' + row.owner_guid + '">' + data + '</a>';
                    }
                }
            ]
        });
    });
    $(document).ready(function () {
        var urlParams = new URLSearchParams(window.location.search);
        var searchTerm = urlParams.get('initial');
        if (searchTerm) {
            $('#ghosts-table').DataTable().search(searchTerm).draw();
        }
    });

</script>
{% endblock bottomjs %}
