<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>Eversync</title>
    {% load static %}
    <link rel="icon" href="{% static 'favicon.ico' %}">
    <link rel="stylesheet" href="{% static 'index-style.css' %}" ">
    <link rel="stylesheet" href="{% static 'register-style.css' %}" ">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
</head>
<body>   
    <div class="header">
        <div class="header-content">
            <a href="/"><img src="{% static 'eversync2.png' %}" alt="Eversync Logo" style="height: 80px; margin-right: 10px; display: flex; align-items: center; gap: 5px;"></a>
            <a href="/" class="logo" >eversync</a>
            <div class="nav-links" style="position: relative;">
                <div class="dropdown">
                    <button class="dropdown-toggle" style="background: none; border: none; color: white; font-size: 16px; cursor: pointer;">
                        Welcome, {{ user.username }} <i class="fas fa-caret-down"></i>
                    </button>
                    <div class="dropdown-menu" style="display: none; position: absolute; right: 0; background-color: #333; border: 1px solid #444; border-radius: 4px; padding: 10px; width: 184px;">
                        
                        <form action="{% url 'manage' %}" method="post" style="margin: 0;">
                            {% csrf_token %}
                            <button type="submit" class="logout-button" style="background-color: transparent; color: white; border: none; cursor: pointer;">Manage Account</button>
                        </form>
                        
                        <form action="{% url 'logoutz' %}" method="post" style="margin: 0;">
                            {% csrf_token %}
                            <button type="submit" class="logout-button" style="background-color: transparent; color: white; border: none; cursor: pointer;">Log Out</button>
                        </form>
                        
                    </div>
                </div>
            </div>
        </div>
    </div>
    

    <div class="container">


        <div class="register-box">
            {% if form.errors %}
                <div class="error-message">
                    <ul>
                        {% for field in form %}
                            {% for error in field.errors %}
                                <li>{{ error }}</li>
                            {% endfor %}
                        {% endfor %}
                        {% for error in form.non_field_errors %}
                            <li>{{ error }}</li>
                        {% endfor %}
                        </ul>
                </div>
            {% endif %}

            <h1>Your Uploaded Files</h1>
            <div style="display: inline-block;">
            <ul>
                {% for document in documents %}
                <li style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                    {% with document.file.url|lower as file_url %}
                        {% with file_url|slice:"-4:" as slice4 %}
                            {% with file_url|slice:"-5:" as slice5 %}
                                {% if slice4 == ".png" or slice4 == ".jpg" or slice4 == ".gif" or slice5 == ".jpeg" or slice5 == ".webp" %}
                                    <img src="{{ document.file.url }}" class="file-thumbnail" style="max-height: 30%; max-width: 30%;"></img>
                                {% else %}
                                    <img src="{% static 'newnew.png' %}" class="file-thumbnail"></img>
                                {% endif %}
                            {% endwith %}
                        {% endwith %}
                    {% endwith %}
                    <a href="{{ document.file.url }}">{{ document.title }}</a>
                    <button onclick="deleteFile('{{ document.id }}')" style="margin-left: 10px;">Delete</button>
                </li>
            {% endfor %}
            </ul>
            </div>
            <div class="divider"></div>

            <div style="display: flex; justify-content: center;">
                <a href="{% url 'upload_file' %}" class="register-button" style="width: 100%; text-align: center; text-decoration: none;">Upload</a>
            </div>      
        </div>
     </div>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const toggle = document.querySelector('.dropdown-toggle');
            const menu = document.querySelector('.dropdown-menu');
            toggle.addEventListener('click', function () {
                menu.style.display = menu.style.display === 'block' ? 'none' : 'block';
            });
        });
    </script>

    <script>
        const csrfToken = '{{ csrf_token }}'

        function deleteFile(fileId) {
        if (confirm("Are you sure you want to delete this file?")) {
            fetch(`/delete_file/${fileId}`, {
                method: 'DELETE',
                headers: {
                    'X-CSRFToken': csrfToken,
                    'file_id': '{{ file.id }}'
                },
            })
        
        .then(response => {
            if (response.ok) {
                location.reload();
            } else {
                alert("Error deleting files");
                location.reload();
            }
        })
        }
        }
    </script>



<script>
    if ('serviceWorker' in navigator) {
        navigator.serviceWorker.register('/webpush/service-worker.js').then(function(reg) {
            console.log('Service Worker Registered!', reg);
            subscribeForPush();
        }).catch(function(err) {
            console.error('Service Worker registration failed:', err);
        });
    }
</script>

<script>
async function subscribeForPush() {
console.log("Requesting notification permission...");
const permission = await Notification.requestPermission();
console.log("Notification permission status:", permission);
if (permission !== "granted") {
    console.warn("User denied notification permission");
    return;
}

const registration = await navigator.serviceWorker.ready;
console.log("Service Worker ready:", registration);

// Replace with your public VAPID key:
const vapidPublicKey = "BArtoQuGwO4z_wyCZJ6cZpkCJVuEHt-YeiHtocH6cTmPNUHL8657te2gXhEiXjjfNMy0igo1PxrSGFokdOokzfA";


function urlBase64ToUint8Array(base64String) {
  const padding = '='.repeat((4 - base64String.length % 4) % 4);
  const base64 = (base64String + padding)
    .replace(/-/g, '+')
    .replace(/_/g, '/');

  const rawData = window.atob(base64);
  const outputArray = new Uint8Array(rawData.length);

  for (let i = 0; i < rawData.length; ++i) {
    outputArray[i] = rawData.charCodeAt(i);
  }
  return outputArray;
}

const convertedKey = urlBase64ToUint8Array(vapidPublicKey);

try {
    const subscription = await registration.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: convertedKey
    });
    console.log("Push subscription object:", subscription);

    const response = await fetch('/webpush/save_information', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': '{{ csrf_token }}',
        },
        body: JSON.stringify(subscription)
    });

    if (!response.ok) {
        console.error("Failed to save subscription:", response.statusText);
    } else {
        console.log("Subscription saved successfully");
    }
} catch (error) {
    console.error("Push subscription failed:", error);
}
}
</script>



</body>
</html>