{% extends "users/base.html" %}
{% block title %}List of Database{% endblock title %}
{% block content %}

<div id="responseContainer" style="position: relative; display: none;"> <!-- Container for the response -->
        <nav aria-label="breadcrumb">
                  <ol class="breadcrumb breadcrumb-inverse">
                   
           <li class="breadcrumb-item active" aria-current="page" style="margin-top:10px">Exporting, please wait.....</li> 
			<li> <div class="sk-wave">
            <div class="rect1"></div>
            <div class="rect2"></div>
            <div class="rect3"></div>
            <div class="rect4"></div>
            <div class="rect5"></div>
          
        </div>
</li> 
       </ol>
                </nav>
    </div>
<div id="alertContainer" class="alert alert-success alert-dismissible fade show" role="alert" style="display: none;">
    <div id="message"></div>
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                  <span aria-hidden="true">×</span>
                </button>
</div>	

 <div class="card card-default">
      <div class="card-header">
        <h2>List of Database</h2>
		
        

      </div>
    
   <div class="card-body">
   <div class="row">
   <div class="col-xl-6">
   <a class="mb-1 btn btn-pill btn-success" href="{% url 'db_make' %}" role="button" style="text-transform: none;">+ Add Database</a>
</div>
<div class="col-xl-6 d-flex justify-content-end">
    <form class="form-inline mb-3">
        <div class="form-group mr-2">
            <input type="text" id="search" name="search" class="form-control" placeholder="Search for record...">
        </div>
    </form>
	</div>
	</div>
	
<div class="table-responsive">
    <table class="table table-bordered">
        <thead class="thead-light">
             <tr>
                <th>Database</th>
				<th>Size</th>
				<th>Privileged Users</th>
				
                <th>Actions</th>
            </tr>
        </thead>
        <tbody id="domainTable">
            {% for database in databases %}
            <tr>
                <td>{{ database.db_name }}</td>
				<td>{{ database.size_display }}</td>
            <td>{{ database.privileged_users }}</td>
			{% if db %}
                <td>
				<a href="{% url 'db_import' database.db_name %}" class="btn btn-primary btn-sm" style="text-transform: none;">Import</a>
                  
                    
                </td>
				{% else %}
				<td>
				<a href="{% url 'db_edit' database.db_name %}" class="btn btn-primary btn-sm" style="text-transform: none;">Manage</a>
                   <form action="{% url 'db_edit' database.db_name %}" method="post" style="display:inline;">
                        {% csrf_token %}
						<input type="hidden" id="action" name="action" value="delete">
                        <button type="submit" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure you want to delete this Database?');" style="text-transform: none;">Delete</button>
                    </form>

                    
                        <button type="submit" class="btn btn-info btn-sm" onclick="exportdb('{{database.db_name}}')" style="text-transform: none;">Export</button>
                 <a href="{% url 'db_repair' database.db_name %}" class="btn btn-success btn-sm" style="text-transform: none;">Repair</a>
					
                </td>
				{% endif %}
            </tr>
            {% empty %}
            <tr>
                <td colspan="4" class="text-center">No domains found.</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</div>
    <!-- No Results Message -->
    <div id="noResults" class="text-center text-danger" style="display:none;">No results found.</div>

</div>
</div>

<script>
const download_url = "{% url 'download' %}"; // Base download URL

function exportdb(id) {
    if (id) {
        console.log('ID found:', id);
        const responseDisplay = document.getElementById('responseContainer');
        const alertContainer = document.getElementById('alertContainer');
        const messageDisplay = document.getElementById('message');

        setTimeout(function () {
            responseDisplay.style.display = 'inline-block';

            // Make the fetch call to trigger the export
            fetch('/file_manager/export_db/' + id, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                },
            })
                .then((response) => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok: ' + response.statusText);
                    }
                    return response.json(); // Parse JSON response
                })
                .then((data) => {
                    console.log('Response:', data);
                    responseDisplay.style.display = 'none';

                    if (data.status === 'success') {
                        // Set alert for success
                        alertContainer.className =
                            'alert alert-success alert-dismissible fade show';
                        messageDisplay.innerText = 'Database export successful!';

                        // Construct the download URL using the file_path from JSON
                        const filePath = data.file_path;
                        window.open(download_url + `?file=${encodeURIComponent(filePath)}`, '_blank');
                    } else {
                        // Set alert for error
                        alertContainer.className =
                            'alert alert-danger alert-dismissible fade show';
                        messageDisplay.innerText = data.message;
                    }

                    alertContainer.style.display = 'block';
                    
                })
                .catch((error) => {
                    console.error('Error:', error);
                });
        }, 0);
    } else {
        console.log('No ID parameter found.');
    }
}

  
    document.addEventListener("DOMContentLoaded", function() {
        const searchInput = document.getElementById('search');
        const tableRows = document.querySelectorAll('#domainTable tr');
        const noResults = document.getElementById('noResults');

        // Function to filter the table based on search query
        function filterTable() {
            const searchQuery = searchInput.value.trim().toLowerCase();
            let visibleRows = 0;

            tableRows.forEach(row => {
                const dbName = row.cells[0]?.textContent.toLowerCase() || '';
                const matchesSearch = dbName.includes(searchQuery);

                if (matchesSearch || searchQuery === '') {
                    row.style.display = '';  // Show the row
                    visibleRows++;
                } else {
                    row.style.display = 'none';  // Hide the row
                }
            });

            // Show or hide the "No results" message based on visible rows
            noResults.style.display = visibleRows === 0 ? 'block' : 'none';
        }

        // Filter table when the search input changes
        searchInput.addEventListener('input', filterTable);

        // Trigger the filter initially in case there's a pre-filled search
        filterTable();
    });
</script>



{% endblock content %}

{% include "users/footer.html" %}