<?php
session_start();
require_once 'config/config.php';
require_once 'auth/check_auth.php';

// Check if user is logged in and has appropriate permissions
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit();
}

$pageTitle = 'Document Management';
$currentPage = 'documents';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?php echo $pageTitle; ?> | KSO Chandigarh</title>
    
    <!-- AdminLTE CSS -->
    <link rel="stylesheet" href="dist/css/adminlte.min.css">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <!-- DataTables -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap4.min.css">
    <!-- SweetAlert2 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    
    <style>
        .document-card {
            transition: all 0.3s ease;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .document-card:hover {
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            transform: translateY(-2px);
        }
        .file-icon {
            font-size: 2.5rem;
            margin-bottom: 10px;
        }
        .file-icon.pdf { color: #dc3545; }
        .file-icon.doc { color: #2196F3; }
        .file-icon.xlsx { color: #4CAF50; }
        .file-icon.ppt { color: #FF9800; }
        .file-icon.image { color: #9C27B0; }
        .file-icon.default { color: #6c757d; }
        
        .upload-zone {
            border: 2px dashed #007bff;
            border-radius: 12px;
            padding: 50px;
            text-align: center;
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            transition: all 0.3s ease;
            cursor: pointer;
        }
        .upload-zone:hover {
            background: linear-gradient(135deg, #e9ecef 0%, #dee2e6 100%);
            border-color: #0056b3;
        }
        .upload-zone.dragover {
            background: linear-gradient(135deg, #cce7ff 0%, #b3d7ff 100%);
            border-color: #0056b3;
        }
        
        .document-stats {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .document-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }
        
        .document-actions {
            position: absolute;
            top: 15px;
            right: 15px;
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        
        .document-card:hover .document-actions {
            opacity: 1;
        }
        
        .access-level {
            position: absolute;
            top: 15px;
            left: 15px;
            padding: 6px 12px;
            border-radius: 15px;
            font-size: 0.75rem;
            font-weight: bold;
            z-index: 10;
        }
        
        .access-public {
            background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%);
            color: #155724;
        }
        
        .access-private {
            background: linear-gradient(135deg, #f8d7da 0%, #f5c2c7 100%);
            color: #721c24;
        }
        
        .filter-section {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .stat-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .stat-icon {
            font-size: 2rem;
            margin-bottom: 10px;
        }
        
        .loading-spinner {
            display: none;
            text-align: center;
            padding: 20px;
        }
        
        .empty-state {
            text-align: center;
            padding: 50px;
            color: #6c757d;
        }
        
        .empty-state i {
            font-size: 4rem;
            margin-bottom: 20px;
        }
    </style>
</head>

<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">
    <!-- Include header -->
    <?php include 'templates/header.php'; ?>
    
    <!-- Include sidebar -->
    <?php include 'templates/sidebar.php'; ?>
    
    <!-- Content Wrapper -->
    <div class="content-wrapper">
        <!-- Content Header -->
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0">
                            <i class="fas fa-folder-open text-primary"></i> Document Management
                        </h1>
                    </div>
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                            <li class="breadcrumb-item active">Documents</li>
                        </ol>
                    </div>
                </div>
            </div>
        </div>

        <!-- Main content -->
        <section class="content">
            <div class="container-fluid">
                
                <!-- Document Statistics -->
                <div class="document-stats">
                    <div class="row">
                        <div class="col-md-3">
                            <div class="stat-card">
                                <div class="stat-icon text-primary">
                                    <i class="fas fa-file-alt"></i>
                                </div>
                                <h3 class="mb-1" id="totalDocuments">0</h3>
                                <p class="mb-0">Total Documents</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stat-card">
                                <div class="stat-icon text-success">
                                    <i class="fas fa-eye"></i>
                                </div>
                                <h3 class="mb-1" id="publicDocuments">0</h3>
                                <p class="mb-0">Public Documents</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stat-card">
                                <div class="stat-icon text-info">
                                    <i class="fas fa-download"></i>
                                </div>
                                <h3 class="mb-1" id="totalDownloads">0</h3>
                                <p class="mb-0">Total Downloads</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stat-card">
                                <div class="stat-icon text-warning">
                                    <i class="fas fa-hdd"></i>
                                </div>
                                <h3 class="mb-1" id="storageUsed">0 MB</h3>
                                <p class="mb-0">Storage Used</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Document Upload Section -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-upload"></i> Upload Documents
                        </h3>
                        <div class="card-tools">
                            <button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#uploadModal">
                                <i class="fas fa-plus"></i> Upload Document
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="upload-zone" id="uploadZone">
                            <i class="fas fa-cloud-upload-alt fa-4x text-primary mb-3"></i>
                            <h4>Drag & Drop Files Here</h4>
                            <p class="text-muted">or click to browse files</p>
                            <button class="btn btn-outline-primary btn-lg" onclick="$('#fileInput').click()">
                                <i class="fas fa-folder-open"></i> Browse Files
                            </button>
                            <input type="file" id="fileInput" multiple style="display: none;" accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.jpg,.png,.gif">
                        </div>
                    </div>
                </div>

                <!-- Document Filters -->
                <div class="filter-section">
                    <h5 class="mb-3"><i class="fas fa-filter"></i> Filter Documents</h5>
                    <div class="row">
                        <div class="col-md-3">
                            <select class="form-control" id="categoryFilter">
                                <option value="">All Categories</option>
                                <option value="general">General</option>
                                <option value="financial">Financial</option>
                                <option value="membership">Membership</option>
                                <option value="events">Events</option>
                                <option value="policies">Policies</option>
                                <option value="other">Other</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <select class="form-control" id="accessFilter">
                                <option value="">All Access Levels</option>
                                <option value="1">Public</option>
                                <option value="0">Private</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <div class="input-group">
                                <input type="text" class="form-control" id="searchFilter" placeholder="Search documents...">
                                <div class="input-group-append">
                                    <button class="btn btn-primary" type="button" onclick="filterDocuments()">
                                        <i class="fas fa-search"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <button class="btn btn-secondary btn-block" onclick="clearFilters()">
                                <i class="fas fa-times"></i> Clear
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Loading Spinner -->
                <div class="loading-spinner" id="loadingSpinner">
                    <i class="fas fa-spinner fa-spin fa-2x"></i>
                    <p>Loading documents...</p>
                </div>

                <!-- Documents Grid -->
                <div class="document-grid" id="documentsGrid">
                    <!-- Documents will be loaded here via JavaScript -->
                </div>

                <!-- Empty State -->
                <div class="empty-state" id="emptyState" style="display: none;">
                    <i class="fas fa-folder-open"></i>
                    <h4>No documents found</h4>
                    <p>Upload your first document to get started.</p>
                    <button class="btn btn-primary" data-toggle="modal" data-target="#uploadModal">
                        <i class="fas fa-upload"></i> Upload Document
                    </button>
                </div>

                <!-- Load More Button -->
                <div class="text-center mt-4">
                    <button class="btn btn-outline-primary btn-lg" id="loadMoreBtn" onclick="loadMoreDocuments()" style="display: none;">
                        <i class="fas fa-plus"></i> Load More Documents
                    </button>
                </div>

            </div>
        </section>
    </div>
</div>

<!-- Upload Modal -->
<div class="modal fade" id="uploadModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-upload"></i> Upload Document
                </h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <form id="uploadForm" enctype="multipart/form-data">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="documentTitle">Document Title *</label>
                                <input type="text" class="form-control" id="documentTitle" name="title" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="documentCategory">Category *</label>
                                <select class="form-control" id="documentCategory" name="category" required>
                                    <option value="">Select Category</option>
                                    <option value="general">General</option>
                                    <option value="financial">Financial</option>
                                    <option value="membership">Membership</option>
                                    <option value="events">Events</option>
                                    <option value="policies">Policies</option>
                                    <option value="other">Other</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="documentDescription">Description</label>
                        <textarea class="form-control" id="documentDescription" name="description" rows="3" placeholder="Enter document description..."></textarea>
                    </div>
                    <div class="form-group">
                        <label for="documentFile">Select File *</label>
                        <div class="custom-file">
                            <input type="file" class="custom-file-input" id="documentFile" name="file" required>
                            <label class="custom-file-label" for="documentFile">Choose file</label>
                        </div>
                        <small class="form-text text-muted">
                            Supported formats: PDF, DOC, DOCX, XLS, XLSX, PPT, PPTX, TXT, JPG, PNG, GIF (Max: 10MB)
                        </small>
                    </div>
                    <div class="form-group">
                        <div class="custom-control custom-switch">
                            <input type="checkbox" class="custom-control-input" id="isPublic" name="is_public" value="1">
                            <label class="custom-control-label" for="isPublic">Make this document public</label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-upload"></i> Upload Document
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Document Details Modal -->
<div class="modal fade" id="documentModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="documentModalTitle">Document Details</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body" id="documentModalBody">
                <!-- Document details will be loaded here -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="downloadBtn">
                    <i class="fas fa-download"></i> Download
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Include footer -->
<?php include 'templates/footer.php'; ?>

<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="dist/js/adminlte.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<!-- Custom JavaScript -->
<script src="dist/js/preloader.js"></script>
<script src="dist/js/theme-manager.js"></script>
<script src="dist/js/toast.js"></script>
<script src="dist/js/breadcrumbs.js"></script>

<script>
// Industrial-Level Document Management System
$(document).ready(function() {
    // Initialize the page
    loadDocuments();
    loadStatistics();
    setupDragDrop();
    setupUploadForm();
    setupFilters();
    
    // Custom file input
    $('.custom-file-input').on('change', function() {
        let fileName = $(this).val().split('\\').pop();
        $(this).siblings('.custom-file-label').addClass('selected').html(fileName);
    });
});

let currentPage = 1;
let isLoading = false;
let hasMoreDocuments = true;

function loadDocuments(page = 1, reset = false) {
    if (isLoading) return;
    
    isLoading = true;
    $('#loadingSpinner').show();
    
    const filters = {
        category: $('#categoryFilter').val(),
        access: $('#accessFilter').val(),
        search: $('#searchFilter').val(),
        page: page
    };
    
    $.ajax({
        url: 'api/documents/fetch.php',
        method: 'GET',
        data: filters,
        success: function(response) {
            if (response.success) {
                if (reset) {
                    $('#documentsGrid').html('');
                }
                
                if (response.documents && response.documents.length > 0) {
                    response.documents.forEach(function(doc) {
                        $('#documentsGrid').append(createDocumentCard(doc));
                    });
                    
                    hasMoreDocuments = response.hasMore;
                    $('#loadMoreBtn').toggle(hasMoreDocuments);
                    $('#emptyState').hide();
                } else if (page === 1) {
                    $('#documentsGrid').html('');
                    $('#emptyState').show();
                    $('#loadMoreBtn').hide();
                }
            } else {
                if (window.ksoToast) {
                    window.ksoToast.error('Error loading documents: ' + response.message);
                } else {
                    console.error('Error loading documents:', response.message);
                }
            }
        },
        error: function() {
            if (window.ksoToast) {
                window.ksoToast.error('Error loading documents');
            } else {
                console.error('Error loading documents');
            }
        },
        complete: function() {
            isLoading = false;
            $('#loadingSpinner').hide();
        }
    });
}

function createDocumentCard(doc) {
    const fileIcon = getFileIcon(doc.file_type);
    const accessLevel = doc.is_public == 1 ? 'Public' : 'Private';
    const accessClass = doc.is_public == 1 ? 'access-public' : 'access-private';
    
    return `
        <div class="card document-card" data-doc-id="${doc.id}">
            <div class="card-body position-relative">
                <div class="access-level ${accessClass}">${accessLevel}</div>
                <div class="document-actions">
                    <div class="btn-group">
                        <button class="btn btn-sm btn-primary" onclick="viewDocument(${doc.id})" title="View Details">
                            <i class="fas fa-eye"></i>
                        </button>
                        <button class="btn btn-sm btn-success" onclick="downloadDocument(${doc.id})" title="Download">
                            <i class="fas fa-download"></i>
                        </button>
                        <button class="btn btn-sm btn-danger" onclick="deleteDocument(${doc.id})" title="Delete">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
                
                <div class="text-center">
                    <div class="file-icon ${fileIcon.class}">
                        <i class="${fileIcon.icon}"></i>
                    </div>
                    <h5 class="card-title">${doc.title}</h5>
                    <p class="card-text text-muted">${doc.description || 'No description'}</p>
                    
                    <div class="mt-3">
                        <span class="badge badge-secondary">${doc.category}</span>
                        <span class="badge badge-info">${formatFileSize(doc.file_size)}</span>
                    </div>
                    
                    <div class="mt-2">
                        <small class="text-muted">
                            <i class="fas fa-calendar"></i> ${formatDate(doc.created_at)}
                        </small>
                        <br>
                        <small class="text-muted">
                            <i class="fas fa-download"></i> ${doc.download_count} downloads
                        </small>
                    </div>
                </div>
            </div>
        </div>
    `;
}

function getFileIcon(fileType) {
    const type = fileType.toLowerCase();
    
    if (type.includes('pdf')) {
        return { icon: 'fas fa-file-pdf', class: 'pdf' };
    } else if (type.includes('doc') || type.includes('word')) {
        return { icon: 'fas fa-file-word', class: 'doc' };
    } else if (type.includes('excel') || type.includes('sheet')) {
        return { icon: 'fas fa-file-excel', class: 'xlsx' };
    } else if (type.includes('powerpoint') || type.includes('presentation')) {
        return { icon: 'fas fa-file-powerpoint', class: 'ppt' };
    } else if (type.includes('image') || type.includes('jpg') || type.includes('png') || type.includes('gif')) {
        return { icon: 'fas fa-file-image', class: 'image' };
    } else {
        return { icon: 'fas fa-file', class: 'default' };
    }
}

function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('en-US', {
        year: 'numeric',
        month: 'short',
        day: 'numeric'
    });
}

function loadStatistics() {
    $.ajax({
        url: 'api/documents/stats.php',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                $('#totalDocuments').text(response.stats.total);
                $('#publicDocuments').text(response.stats.public);
                $('#totalDownloads').text(response.stats.downloads);
                $('#storageUsed').text(formatFileSize(response.stats.storage));
            }
        },
        error: function() {
            // Set default values on error
            $('#totalDocuments').text('0');
            $('#publicDocuments').text('0');
            $('#totalDownloads').text('0');
            $('#storageUsed').text('0 MB');
        }
    });
}

function setupDragDrop() {
    const uploadZone = document.getElementById('uploadZone');
    
    uploadZone.addEventListener('dragover', function(e) {
        e.preventDefault();
        uploadZone.classList.add('dragover');
    });
    
    uploadZone.addEventListener('dragleave', function(e) {
        e.preventDefault();
        uploadZone.classList.remove('dragover');
    });
    
    uploadZone.addEventListener('drop', function(e) {
        e.preventDefault();
        uploadZone.classList.remove('dragover');
        
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            handleFileUpload(files[0]);
        }
    });
    
    uploadZone.addEventListener('click', function() {
        $('#fileInput').click();
    });
    
    $('#fileInput').on('change', function() {
        if (this.files.length > 0) {
            handleFileUpload(this.files[0]);
        }
    });
}

function handleFileUpload(file) {
    // Open upload modal with file pre-selected
    $('#uploadModal').modal('show');
    
    // Create FileList and assign to input
    const dt = new DataTransfer();
    dt.items.add(file);
    $('#documentFile')[0].files = dt.files;
    
    // Update file label
    $('.custom-file-label').addClass('selected').html(file.name);
    
    // Auto-fill title
    $('#documentTitle').val(file.name.replace(/\.[^/.]+$/, ""));
}

function setupUploadForm() {
    $('#uploadForm').on('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        const submitBtn = $(this).find('button[type="submit"]');
        
        submitBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Uploading...');
        
        $.ajax({
            url: 'api/documents/upload.php',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    if (window.ksoToast) {
                        window.ksoToast.success('Document uploaded successfully!');
                    } else {
                        alert('Document uploaded successfully!');
                    }
                    $('#uploadModal').modal('hide');
                    $('#uploadForm')[0].reset();
                    $('.custom-file-label').removeClass('selected').html('Choose file');
                    loadDocuments(1, true);
                    loadStatistics();
                } else {
                    if (window.ksoToast) {
                        window.ksoToast.error('Upload failed: ' + response.message);
                    } else {
                        alert('Upload failed: ' + response.message);
                    }
                }
            },
            error: function() {
                if (window.ksoToast) {
                    window.ksoToast.error('Upload failed');
                } else {
                    alert('Upload failed');
                }
            },
            complete: function() {
                submitBtn.prop('disabled', false).html('<i class="fas fa-upload"></i> Upload Document');
            }
        });
    });
}

function setupFilters() {
    $('#categoryFilter, #accessFilter').on('change', function() {
        currentPage = 1;
        loadDocuments(1, true);
    });
    
    $('#searchFilter').on('keyup', function() {
        clearTimeout(this.searchTimeout);
        this.searchTimeout = setTimeout(function() {
            currentPage = 1;
            loadDocuments(1, true);
        }, 500);
    });
}

function filterDocuments() {
    currentPage = 1;
    loadDocuments(1, true);
}

function clearFilters() {
    $('#categoryFilter, #accessFilter, #searchFilter').val('');
    currentPage = 1;
    loadDocuments(1, true);
}

function loadMoreDocuments() {
    if (hasMoreDocuments && !isLoading) {
        currentPage++;
        loadDocuments(currentPage, false);
    }
}

function viewDocument(id) {
    $.ajax({
        url: 'api/documents/details.php',
        method: 'GET',
        data: { id: id },
        success: function(response) {
            if (response.success) {
                const doc = response.document;
                $('#documentModalTitle').text(doc.title);
                $('#documentModalBody').html(`
                    <div class="row">
                        <div class="col-md-4">
                            <div class="text-center">
                                <div class="file-icon ${getFileIcon(doc.file_type).class}" style="font-size: 4rem;">
                                    <i class="${getFileIcon(doc.file_type).icon}"></i>
                                </div>
                                <h5>${doc.title}</h5>
                                <p class="text-muted">${formatFileSize(doc.file_size)}</p>
                            </div>
                        </div>
                        <div class="col-md-8">
                            <h6>Description</h6>
                            <p>${doc.description || 'No description available'}</p>
                            
                            <h6>Details</h6>
                            <table class="table table-sm">
                                <tr>
                                    <td><strong>Category:</strong></td>
                                    <td><span class="badge badge-secondary">${doc.category}</span></td>
                                </tr>
                                <tr>
                                    <td><strong>Access Level:</strong></td>
                                    <td><span class="badge badge-${doc.is_public == 1 ? 'success' : 'warning'}">${doc.is_public == 1 ? 'Public' : 'Private'}</span></td>
                                </tr>
                                <tr>
                                    <td><strong>Uploaded By:</strong></td>
                                    <td>${doc.uploaded_by_name || 'Unknown'}</td>
                                </tr>
                                <tr>
                                    <td><strong>Upload Date:</strong></td>
                                    <td>${formatDate(doc.created_at)}</td>
                                </tr>
                                <tr>
                                    <td><strong>Downloads:</strong></td>
                                    <td>${doc.download_count}</td>
                                </tr>
                            </table>
                        </div>
                    </div>
                `);
                
                $('#downloadBtn').off('click').on('click', function() {
                    downloadDocument(doc.id);
                });
                
                $('#documentModal').modal('show');
            } else {
                if (window.ksoToast) {
                    window.ksoToast.error('Error loading document details');
                } else {
                    alert('Error loading document details');
                }
            }
        },
        error: function() {
            if (window.ksoToast) {
                window.ksoToast.error('Error loading document details');
            } else {
                alert('Error loading document details');
            }
        }
    });
}

function downloadDocument(id) {
    window.open('api/documents/download.php?id=' + id, '_blank');
}

function deleteDocument(id) {
    if (typeof Swal !== 'undefined') {
        Swal.fire({
            title: 'Are you sure?',
            text: "You won't be able to revert this!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, delete it!'
        }).then((result) => {
            if (result.isConfirmed) {
                performDelete(id);
            }
        });
    } else {
        if (confirm('Are you sure you want to delete this document?')) {
            performDelete(id);
        }
    }
}

function performDelete(id) {
    $.ajax({
        url: 'api/documents/delete.php',
        method: 'POST',
        data: { id: id },
        success: function(response) {
            if (response.success) {
                if (window.ksoToast) {
                    window.ksoToast.success('Document deleted successfully!');
                } else {
                    alert('Document deleted successfully!');
                }
                loadDocuments(1, true);
                loadStatistics();
            } else {
                if (window.ksoToast) {
                    window.ksoToast.error('Delete failed: ' + response.message);
                } else {
                    alert('Delete failed: ' + response.message);
                }
            }
        },
        error: function() {
            if (window.ksoToast) {
                window.ksoToast.error('Delete failed');
            } else {
                alert('Delete failed');
            }
        }
    });
}
</script>

</body>
</html>
