{% extends 'base.html' %}
{% load static %}
{% load utils_filters %}

{% block title %}Documents - HAVEN GRAZURI ADVANCE{% endblock %}

{% block content %}
<div class="min-h-screen">
    <!-- Page header -->
    <div class="mb-8">
        <div class="sm:flex sm:items-center">
            <div class="sm:flex-auto">
                <h1 class="text-2xl font-semibold text-gray-900">Documents</h1>
                <p class="mt-2 text-sm text-gray-700">
                    Manage and organize all your business documents in one place.
                    <span class="font-medium">Total Documents: {{ total_documents }}</span>
                </p>
            </div>
            <div class="mt-4 sm:ml-16 sm:mt-0 sm:flex-none flex gap-2">
                <div class="relative">
                    <input type="text" id="searchInput" placeholder="Search documents..." value="{{ search_query }}" class="block w-64 rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                    <div class="absolute inset-y-0 right-0 flex items-center pr-3">
                        <span>🔍</span>
                    </div>
                </div>
                <select id="sortSelect" class="block rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                    {% for value, label in sort_options %}
                    <option value="{{ value }}" {% if value == current_sort %}selected{% endif %}>{{ label }}</option>
                    {% endfor %}
                </select>
                <a href="{% url 'utils:all_customer_documents' %}" class="block rounded-md bg-secondary px-3 py-2 text-center text-sm font-semibold text-white shadow-sm hover:bg-opacity-90">
                    <span>👥</span>Customer Documents
                </a>
                <button type="button" onclick="openUploadModal()" class="block rounded-md bg-primary px-3 py-2 text-center text-sm font-semibold text-white shadow-sm hover:bg-opacity-90">
                    <span>⬆️</span>Upload
                </button>
            </div>
        </div>
    </div>

    <!-- Document grid -->
    <div id="dropZone" class="border-2 border-dashed border-gray-300 rounded-lg p-8 mb-8 text-center hidden">
        <i class="fas fa-cloud-upload-alt text-4xl text-gray-400 mb-4"></i>
        <p class="text-gray-600">Drop files here to upload</p>
    </div>

    <!-- Document categories -->
    <div class="space-y-8">
        {% for doc_type, doc_name in document_types %}
        {% with docs=documents|get_item:doc_type %}
        {% if docs %}
        <div class="bg-white rounded-lg shadow overflow-hidden">
            <div class="p-6 border-b border-gray-200">
                <h3 class="text-lg font-semibold text-gray-900 flex items-center">
                    {% if doc_type == 'loan_agreement' %}
                        <i class="fas fa-file-invoice-dollar text-primary mr-2"></i>
                    {% elif doc_type == 'id_document' %}
                        <span>🪪</span>
                    {% elif doc_type == 'selfie' %}
                        <span>👤</span>
                    {% elif doc_type == 'utility_bill' %}
                        <span>🧾</span>
                    {% elif doc_type == 'bank_statement' %}
                        <i class="fas fa-university text-primary mr-2"></i>
                    {% elif doc_type == 'business_license' %}
                        <i class="fas fa-certificate text-primary mr-2"></i>
                    {% elif doc_type == 'tax_return' %}
                        <span>📄</span>
                    {% elif doc_type == 'payslip' %}
                        <span>💵</span>
                    {% elif doc_type == 'contract' %}
                        <i class="fas fa-gavel text-primary mr-2"></i>
                    {% elif doc_type == 'logbook' %}
                        <i class="fas fa-car text-primary mr-2"></i>
                    {% elif doc_type == 'title_deed' %}
                        <span>🏠</span>
                    {% elif doc_type == 'signature' %}
                        <i class="fas fa-signature text-primary mr-2"></i>
                    {% else %}
                        <span>📂</span>
                    {% endif %}
                    {{ doc_name }} Documents
                    <span class="ml-2 text-sm text-gray-500">({{ docs|length }})</span>
                </h3>
            </div>
            
            <div class="p-6">
                <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
                    {% for doc in docs %}
                    <div class="document-card group relative bg-white rounded-lg border border-gray-200 overflow-hidden hover:shadow-lg transition-shadow duration-200" data-id="{{ doc.id }}" data-category="{{ doc_type }}">
                        <!-- Document Preview -->
                        <div class="aspect-w-3 aspect-h-4 bg-gray-100 group-hover:opacity-75">
                            {% if doc.source == 'kyc' %}
                                <!-- KYC Document Preview -->
                                {% if doc.file.url|lower|slice:"-4:" in '.pdf,.doc,.docx' %}
                                    <div class="flex items-center justify-center h-full">
                                        <i class="fas {% if doc.file.url|lower|slice:"-4:" == '.pdf' %}fa-file-pdf{% else %}fa-file-word{% endif %} text-4xl text-gray-400"></i>
                                    </div>
                                {% else %}
                                    <img src="{{ doc.file.url }}" alt="{{ doc.name }}" class="w-full h-full object-cover">
                                {% endif %}
                            {% else %}
                                <!-- Regular Document Preview -->
                                {% if doc.file.url|lower|slice:"-4:" in '.pdf,.doc,.docx' %}
                                    <div class="flex items-center justify-center h-full">
                                        <i class="fas {% if doc.file.url|lower|slice:"-4:" == '.pdf' %}fa-file-pdf{% else %}fa-file-word{% endif %} text-4xl text-gray-400"></i>
                                    </div>
                                {% else %}
                                    <img src="{{ doc.file.url }}" alt="{{ doc.name }}" class="w-full h-full object-cover">
                                {% endif %}
                            {% endif %}
                        </div>
                        
                        <!-- Document Info -->
                        <div class="p-4">
                            <h4 class="text-sm font-medium text-gray-900 truncate">{{ doc.name }}</h4>
                            <p class="mt-1 text-xs text-gray-500">{{ doc.created_at|date:"M d, Y" }}</p>
                            
                            {% if doc.source == 'kyc' %}
                                <p class="mt-1 text-xs text-blue-600 font-medium">{{ doc.client_name }}</p>
                            {% endif %}
                            
                            <!-- Tags -->
                            <div class="mt-2 flex flex-wrap gap-1">
                                {% if doc.source == 'kyc' %}
                                    <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800">
                                        KYC Document
                                    </span>
                                {% endif %}
                                {% for tag in doc.tags.all %}
                                <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-gray-100 text-gray-800">
                                    {{ tag.name }}
                                </span>
                                {% endfor %}
                            </div>
                        </div>
                        
                        <!-- Actions -->
                        <div class="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity duration-200 flex gap-1">
                            <button onclick="previewDocument('{{ doc.file.url }}')" class="p-1 bg-white rounded-full shadow-sm hover:bg-gray-50">
                                <i class="fas fa-eye text-gray-600"></i>
                            </button>
                            <a href="{{ doc.file.url }}" download class="p-1 bg-white rounded-full shadow-sm hover:bg-gray-50">
                                <span>⬇️</span>
                            </a>
                            {% if doc.source != 'kyc' %}
                            <button onclick="shareDocument('{{ doc.id }}')" class="p-1 bg-white rounded-full shadow-sm hover:bg-gray-50">
                                <i class="fas fa-share-alt text-gray-600"></i>
                            </button>
                            {% if user.is_staff %}
                            <button onclick="deleteDocument('{{ doc.id }}')" class="p-1 bg-white rounded-full shadow-sm hover:bg-gray-50">
                                <span>🗑️</span>
                            </button>
                            {% endif %}
                            {% endif %}
                        </div>
                        
                        <!-- Selection Checkbox for Bulk Actions -->
                        <div class="absolute top-2 left-2">
                            <input type="checkbox" class="doc-select form-checkbox h-4 w-4 text-primary rounded border-gray-300">
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>
        {% endif %}
        {% endwith %}
        {% endfor %}
    </div>
</div>

<!-- Upload Modal -->
<div id="uploadModal" class="fixed inset-0 z-50 hidden">
    <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"></div>
    <div class="fixed inset-0 z-10 overflow-y-auto">
        <div class="flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0">
            <div class="relative transform overflow-hidden rounded-lg bg-white px-4 pb-4 pt-5 text-left shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-lg sm:p-6">
                <div>
                    <div class="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-primary">
                        <span>⬆️</span>
                    </div>
                    <div class="mt-3 text-center sm:mt-5">
                        <h3 class="text-base font-semibold leading-6 text-gray-900">Upload Document</h3>
                        <form id="uploadForm" class="mt-6">
                            <div class="space-y-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700">Title</label>
                                    <input type="text" name="title" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700">Category</label>
                                    <select name="category" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                                        {% for value, label in document_types %}
                                        <option value="{{ value }}">{{ label }}</option>
                                        {% endfor %}
                                    </select>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700">Tags</label>
                                    <input type="text" name="tags" placeholder="Enter tags separated by commas" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700">Description</label>
                                    <textarea name="description" rows="3" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm"></textarea>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700">File</label>
                                    <input type="file" name="file" required multiple class="mt-1 block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-semibold file:bg-primary file:text-white hover:file:bg-opacity-90">
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <div class="mt-5 sm:mt-6 sm:grid sm:grid-flow-row-dense sm:grid-cols-2 sm:gap-3">
                    <button type="button" onclick="submitUpload()" class="inline-flex w-full justify-center rounded-md bg-primary px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-opacity-90 sm:col-start-2">Upload</button>
                    <button type="button" onclick="closeUploadModal()" class="mt-3 inline-flex w-full justify-center rounded-md bg-white px-3 py-2 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50 sm:col-start-1 sm:mt-0">Cancel</button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Preview Modal -->
<div id="previewModal" class="fixed inset-0 z-50 hidden">
    <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"></div>
    <div class="fixed inset-0 z-10 overflow-y-auto">
        <div class="flex min-h-full items-center justify-center p-4">
            <div class="relative transform overflow-hidden rounded-lg bg-white shadow-xl transition-all max-w-4xl w-full">
                <div class="absolute top-0 right-0 pt-4 pr-4">
                    <button type="button" onclick="closePreviewModal()" class="rounded-md bg-white text-gray-400 hover:text-gray-500">
                        <span>✕</span>
                    </button>
                </div>
                <div class="p-6">
                    <div id="previewContent" class="min-h-[400px] flex items-center justify-center">
                        <!-- Preview content will be inserted here -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Share Modal -->
<div id="shareModal" class="fixed inset-0 z-50 hidden">
    <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"></div>
    <div class="fixed inset-0 z-10 overflow-y-auto">
        <div class="flex min-h-full items-center justify-center p-4">
            <div class="relative transform overflow-hidden rounded-lg bg-white shadow-xl transition-all sm:max-w-lg w-full">
                <div class="p-6">
                    <h3 class="text-lg font-semibold mb-4">Share Document</h3>
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Share with</label>
                            <select id="shareUsers" multiple class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                                <!-- Users will be populated by JavaScript -->
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Message</label>
                            <textarea id="shareMessage" rows="3" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm"></textarea>
                        </div>
                        <div class="flex justify-end gap-2">
                            <button onclick="closeShareModal()" class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50">Cancel</button>
                            <button onclick="submitShare()" class="px-4 py-2 text-sm font-medium text-white bg-primary rounded-md hover:bg-opacity-90">Share</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Bulk Actions Bar -->
<div id="bulkActionsBar" class="fixed bottom-0 inset-x-0 pb-2 sm:pb-5 hidden">
    <div class="mx-auto max-w-7xl px-2 sm:px-6 lg:px-8">
        <div class="rounded-lg bg-primary p-2 shadow-lg sm:p-3">
            <div class="flex flex-wrap items-center justify-between">
                <div class="flex w-0 flex-1 items-center">
                    <span class="flex rounded-lg bg-primary-dark p-2">
                        <i class="fas fa-check-square text-white"></i>
                    </span>
                    <p class="ml-3 font-medium text-white truncate">
                        <span class="hidden md:inline"><span id="selectedCount">0</span> documents selected</span>
                    </p>
                </div>
                <div class="flex-shrink-0 w-full sm:w-auto">
                    <div class="flex space-x-2">
                        <button onclick="bulkDownload()" class="flex items-center justify-center rounded-md bg-white px-3 py-2 text-sm font-semibold text-primary shadow-sm hover:bg-primary-light">
                            <span>⬇️</span>Download
                        </button>
                        <button onclick="bulkShare()" class="flex items-center justify-center rounded-md bg-white px-3 py-2 text-sm font-semibold text-primary shadow-sm hover:bg-primary-light">
                            <i class="fas fa-share-alt mr-2"></i>Share
                        </button>
                        {% if user.is_staff %}
                        <button onclick="bulkDelete()" class="flex items-center justify-center rounded-md bg-red-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-red-500">
                            <span>🗑️</span>Delete
                        </button>
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
// Drag and drop functionality
const dropZone = document.getElementById('dropZone');
const body = document.body;

['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
    body.addEventListener(eventName, preventDefaults, false);
    dropZone.addEventListener(eventName, preventDefaults, false);
});

function preventDefaults(e) {
    e.preventDefault();
    e.stopPropagation();
}

['dragenter', 'dragover'].forEach(eventName => {
    body.addEventListener(eventName, highlight, false);
});

['dragleave', 'drop'].forEach(eventName => {
    body.addEventListener(eventName, unhighlight, false);
});

function highlight(e) {
    dropZone.classList.remove('hidden');
}

function unhighlight(e) {
    dropZone.classList.add('hidden');
}

dropZone.addEventListener('drop', handleDrop, false);

function handleDrop(e) {
    const dt = e.dataTransfer;
    const files = dt.files;
    handleFiles(files);
}

function handleFiles(files) {
    const formData = new FormData();
    [...files].forEach(file => {
        formData.append('files[]', file);
    });
    // Add default category
    formData.append('category', 'other');
    
    uploadFiles(formData);
}

// Search and sort functionality
const searchInput = document.getElementById('searchInput');
const sortSelect = document.getElementById('sortSelect');

searchInput.addEventListener('input', function() {
    const searchTerm = searchInput.value;
    const currentSort = sortSelect.value;
    updateURL(searchTerm, currentSort);
});

sortSelect.addEventListener('change', function() {
    const searchTerm = searchInput.value;
    const currentSort = sortSelect.value;
    updateURL(searchTerm, currentSort);
});

function updateURL(search, sort) {
    const url = new URL(window.location);
    if (search) {
        url.searchParams.set('search', search);
    } else {
        url.searchParams.delete('search');
    }
    if (sort) {
        url.searchParams.set('sort', sort);
    } else {
        url.searchParams.delete('sort');
    }
    window.location.href = url.toString();
}

// Document preview
function previewDocument(url) {
    const previewModal = document.getElementById('previewModal');
    const previewContent = document.getElementById('previewContent');
    const fileExtension = url.split('.').pop().toLowerCase();
    
    previewContent.innerHTML = '';
    
    if (['jpg', 'jpeg', 'png', 'gif'].includes(fileExtension)) {
        const img = document.createElement('img');
        img.src = url;
        img.className = 'max-w-full max-h-[70vh] object-contain';
        previewContent.appendChild(img);
    } else if (fileExtension === 'pdf') {
        const iframe = document.createElement('iframe');
        iframe.src = url;
        iframe.className = 'w-full h-[70vh]';
        previewContent.appendChild(iframe);
    } else {
        previewContent.innerHTML = `
            <div class="text-center">
                <span>📄</span>
                <p class="text-gray-600">Preview not available for this file type</p>
                <a href="${url}" download class="mt-4 inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-primary hover:bg-opacity-90">
                    <span>⬇️</span>Download File
                </a>
            </div>
        `;
    }
    
    previewModal.classList.remove('hidden');
}

function closePreviewModal() {
    document.getElementById('previewModal').classList.add('hidden');
}

// Document sharing
function shareDocument(docId) {
    const shareModal = document.getElementById('shareModal');
    // Store the document ID for use when submitting
    shareModal.dataset.docId = docId;
    // Fetch users and populate select
    fetchUsers().then(users => {
        const select = document.getElementById('shareUsers');
        select.innerHTML = users.map(user => 
            `<option value="${user.id}">${user.name}</option>`
        ).join('');
    });
    shareModal.classList.remove('hidden');
}

function closeShareModal() {
    document.getElementById('shareModal').classList.add('hidden');
}

function submitShare() {
    const shareModal = document.getElementById('shareModal');
    const docId = shareModal.dataset.docId;
    const users = Array.from(document.getElementById('shareUsers').selectedOptions).map(opt => opt.value);
    const message = document.getElementById('shareMessage').value;
    
    fetch('/utils/documents/share/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCsrfToken()
        },
        body: JSON.stringify({
            document_id: docId,
            users: users,
            message: message
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            closeShareModal();
            alert('Document shared successfully');
        } else {
            alert('Error sharing document: ' + data.error);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Error sharing document');
    });
}

// Bulk actions
const checkboxes = document.querySelectorAll('.doc-select');
const bulkActionsBar = document.getElementById('bulkActionsBar');
const selectedCount = document.getElementById('selectedCount');

checkboxes.forEach(checkbox => {
    checkbox.addEventListener('change', updateBulkActions);
});

function updateBulkActions() {
    const selected = document.querySelectorAll('.doc-select:checked');
    selectedCount.textContent = selected.length;
    bulkActionsBar.classList.toggle('hidden', selected.length === 0);
}

function bulkDownload() {
    const selected = getSelectedDocuments();
    selected.forEach(doc => {
        const link = document.createElement('a');
        link.href = doc.querySelector('a[download]').href;
        link.download = '';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    });
}

function bulkShare() {
    const selected = getSelectedDocuments();
    const docIds = Array.from(selected).map(doc => doc.dataset.id);
    shareDocument(docIds.join(','));
}

function bulkDelete() {
    if (!confirm('Are you sure you want to delete the selected documents?')) return;
    
    const selected = getSelectedDocuments();
    const docIds = Array.from(selected).map(doc => doc.dataset.id);
    
    Promise.all(docIds.map(id => deleteDocument(id)))
        .then(() => {
            selected.forEach(doc => doc.remove());
            updateBulkActions();
        });
}

function getSelectedDocuments() {
    return document.querySelectorAll('.doc-select:checked').forEach(cb => cb.closest('.document-card'));
}

// Existing functions
function openUploadModal() {
    document.getElementById('uploadModal').classList.remove('hidden');
}

function closeUploadModal() {
    document.getElementById('uploadModal').classList.add('hidden');
    document.getElementById('uploadForm').reset();
}

function submitUpload() {
    const form = document.getElementById('uploadForm');
    const formData = new FormData(form);
    
    fetch('/utils/documents/upload/', {
        method: 'POST',
        body: formData,
        headers: {
            'X-CSRFToken': getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            window.location.reload();
        } else {
            alert('Error uploading document: ' + data.error);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Error uploading document. Please try again.');
    });
}

function deleteDocument(id) {
    return fetch(`/utils/documents/delete/${id}/`, {
        method: 'POST',
        headers: {
            'X-CSRFToken': getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            const card = document.querySelector(`.document-card[data-id="${id}"]`);
            if (card) card.remove();
        } else {
            throw new Error(data.error);
        }
    });
}

async function fetchUsers() {
    const response = await fetch('/utils/users/list/');
    const data = await response.json();
    return data.users;
}

function getCsrfToken() {
    const name = 'csrftoken';
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

// Close modals with Escape key
document.addEventListener('keydown', function(event) {
    if (event.key === 'Escape') {
        closeUploadModal();
        closePreviewModal();
        closeShareModal();
    }
});

// Close modals when clicking outside
document.addEventListener('click', function(event) {
    const modals = [
        document.getElementById('uploadModal'),
        document.getElementById('previewModal'),
        document.getElementById('shareModal')
    ];
    
    modals.forEach(modal => {
        if (event.target === modal) {
            modal.classList.add('hidden');
        }
    });
});
</script>
{% endblock %} 