Path : /home/vishqocm/pcib.in/student/
File Upload :
Current File : /home/vishqocm/pcib.in/student/documents.php

<?php
$pageTitle = "My Documents";
include_once('includes/header.php');

// Check if student is logged in
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'student') {
    header("Location: ../login.php");
    exit();
}

$userId = $_SESSION['user_id'];
$success_message = '';
$error_message = '';
$need_refresh = false; // Initialize the refresh flag

// Handle flash messages
if (isset($_SESSION['success_message'])) {
    $success_message = $_SESSION['success_message'];
    unset($_SESSION['success_message']);
}

if (isset($_SESSION['error_message'])) {
    $error_message = $_SESSION['error_message'];
    unset($_SESSION['error_message']);
}

// Handle direct document deletion via GET
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
    $document_id = intval($_GET['id']);
    
    if ($document_id > 0) {
        // First get the document to check if it belongs to the current student
        $check_query = "SELECT * FROM student_documents WHERE id = ? AND user_id = ?";
        $check_stmt = $conn->prepare($check_query);
        $check_stmt->bind_param("ii", $document_id, $userId);
        $check_stmt->execute();
        $result = $check_stmt->get_result();
        
        if ($result->num_rows === 1) {
            $document = $result->fetch_assoc();
            
            // Delete the file from the server
            $document_path = $document['document_path'];
            $full_path = realpath('../' . $document_path);
            if (file_exists($full_path)) {
                unlink($full_path);
            }
            
            // Delete the record from the database
            $delete_query = "DELETE FROM student_documents WHERE id = ?";
            $delete_stmt = $conn->prepare($delete_query);
            $delete_stmt->bind_param("i", $document_id);
            
            if ($delete_stmt->execute()) {
                $success_message = "Document deleted successfully.";
            } else {
                $error_message = "Error deleting document: " . $delete_stmt->error;
            }
            $delete_stmt->close();
        } else {
            $error_message = "Document not found or you don't have permission to delete it.";
        }
        $check_stmt->close();
        
        // Set a flag to refresh the page via JavaScript instead of using header()
        $need_refresh = true;
    }
}

// Handle document upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload_document'])) {
    $document_type = $_POST['document_type'] ?? '';
    $document_title = $_POST['document_title'] ?? '';
    $custom_type = $_POST['custom_type'] ?? '';
    
    // Use custom type if selected
    if ($document_type === 'other' && !empty($custom_type)) {
        $document_type = $custom_type;
    }
    
    // Validate document type and title
    if (empty($document_type) || empty($document_title)) {
        $error_message = "Document type and title are required.";
    } else {
        // Handle file upload
        if (isset($_FILES['document_file']) && $_FILES['document_file']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = '../uploads/student_documents/';
            
            // Create directory if it doesn't exist
            if (!file_exists($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }
            
            // Get the file extension
            $file_extension = strtolower(pathinfo($_FILES['document_file']['name'], PATHINFO_EXTENSION));
            
            // Allowed file types
            $allowed_extensions = ['pdf', 'jpg', 'jpeg', 'png', 'doc', 'docx'];
            
            if (!in_array($file_extension, $allowed_extensions)) {
                $error_message = "Invalid file type. Allowed types: PDF, JPG, JPEG, PNG, DOC, DOCX.";
            } else {
                // Generate unique filename
                $file_name = 'doc_' . $userId . '_' . time() . '.' . $file_extension;
                $document_path = $upload_dir . $file_name;
                
                // Move uploaded file
                if (move_uploaded_file($_FILES['document_file']['tmp_name'], $document_path)) {
                    // Insert document record into database
                    $insert_query = "
                        INSERT INTO student_documents (
                            user_id, document_type, document_path, 
                            document_name, document_size, upload_date, status
                        ) VALUES (?, ?, ?, ?, ?, NOW(), 'pending')
                    ";
                    
                    $file_size = $_FILES['document_file']['size'];
                    $file_type = $_FILES['document_file']['type'];
                    $db_document_path = '../uploads/student_documents/' . $file_name;
                    
                    $stmt = $conn->prepare($insert_query);
                    $stmt->bind_param("isssi", $userId, $document_type, 
                                      $db_document_path, $file_name, $file_size);
                    
                    if ($stmt->execute()) {
                        $success_message = "Document uploaded successfully and is pending verification.";
                        
                        // Clear form data after successful upload
                        $_POST = [];
                    } else {
                        $error_message = "Error uploading document: " . $stmt->error;
                    }
                    $stmt->close();
                } else {
                    $error_message = "Failed to move uploaded file.";
                }
            }
        } else {
            $error_message = "Please select a file to upload.";
        }
    }
}

// Handle document deletion
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_document'])) {
    $document_id = isset($_POST['document_id']) ? intval($_POST['document_id']) : 0;
    
    if ($document_id > 0) {
        // First get the document to check if it belongs to the current student
        $check_query = "SELECT * FROM student_documents WHERE id = ? AND user_id = ?";
        $check_stmt = $conn->prepare($check_query);
        $check_stmt->bind_param("ii", $document_id, $userId);
        $check_stmt->execute();
        $result = $check_stmt->get_result();
        
        if ($result->num_rows === 1) {
            $document = $result->fetch_assoc();
            
            // Delete the file from the server
            $document_path = '../' . $document['document_path'];
            if (file_exists($document_path)) {
                unlink($document_path);
            }
            
            // Delete the record from the database
            $delete_query = "DELETE FROM student_documents WHERE id = ?";
            $delete_stmt = $conn->prepare($delete_query);
            $delete_stmt->bind_param("i", $document_id);
            
            if ($delete_stmt->execute()) {
                $success_message = "Document deleted successfully.";
            } else {
                $error_message = "Error deleting document: " . $delete_stmt->error;
            }
            $delete_stmt->close();
        } else {
            $error_message = "Document not found or you don't have permission to delete it.";
        }
        $check_stmt->close();
    } else {
        $error_message = "Invalid document ID.";
    }
}

// Get student documents
$documents_query = "
    SELECT * FROM student_documents
    WHERE user_id = ?
    ORDER BY upload_date DESC
";
$stmt = $conn->prepare($documents_query);
$stmt->bind_param("i", $userId);
$stmt->execute();
$documents_result = $stmt->get_result();
$documents = [];

while ($row = $documents_result->fetch_assoc()) {
    $documents[] = $row;
}
$stmt->close();

// Get document types
$document_types = [
    'identity' => 'Identity Proof (Aadhaar/PAN/Voter ID)',
    'academic' => 'Academic Certificates',
    'address' => 'Address Proof',
    'photo' => 'Passport Size Photo',
    'signature' => 'Signature',
    'income' => 'Income Certificate',
    'medical' => 'Medical Certificate',
    'recommendation' => 'Recommendation Letter',
    'other' => 'Other'
];

// Get required documents from settings
$required_docs = [
    'identity' => 'Identity Proof (Aadhaar/PAN/Voter ID)',
    'academic' => 'Academic Certificates',
    'address' => 'Address Proof',
    'photo' => 'Passport Size Photo'
];

// Count documents by status
$verified_count = 0;
$pending_count = 0;
$rejected_count = 0;

foreach ($documents as $doc) {
    if ($doc['status'] === 'verified') {
        $verified_count++;
    } elseif ($doc['status'] === 'pending') {
        $pending_count++;
    } elseif ($doc['status'] === 'rejected') {
        $rejected_count++;
    }
}

// Check for missing required documents
$uploaded_doc_types = [];
foreach ($documents as $doc) {
    $uploaded_doc_types[$doc['document_type']] = true;
}

$missing_docs = [];
foreach ($required_docs as $key => $name) {
    if (!isset($uploaded_doc_types[$key])) {
        $missing_docs[$key] = $name;
    }
}
?>

<!-- Modern UI CSS -->
<link rel="stylesheet" href="css/modern-ui.css">

<style>
    body {
        font-family: 'Poppins', sans-serif;
        background-color: #f8f9fa;
        min-height: 100vh;
        overflow-x: hidden;
    }
    
    .card-footer .btn-outline-danger {
        transition: all 0.3s ease;
    }
    
    .card-footer .btn-outline-danger:hover {
        background-color: #e74a3b;
        color: white;
    }
    
    .document-icon {
        padding: 30px 0;
    }
    
    .delete-document {
        transition: all 0.3s ease;
    }
    
    .delete-document:hover {
        transform: scale(1.05);
    }
</style>

<div class="container-fluid">
    <!-- Page Heading -->
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800">Document Management</h1>
    </div>
    
    <?php if ($success_message): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fas fa-check-circle mr-2"></i> <?php echo $success_message; ?>
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
    <?php endif; ?>
    
    <?php if ($error_message): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fas fa-exclamation-circle mr-2"></i> <?php echo $error_message; ?>
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
    <?php endif; ?>
    
    <!-- Document Status Cards -->
    <div class="row">
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-primary shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                Total Documents</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo count($documents); ?></div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-file-alt fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-success shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                Verified</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $verified_count; ?></div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-check-circle fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-warning shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                                Pending</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $pending_count; ?></div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-clock fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-danger shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-danger text-uppercase mb-1">
                                Rejected</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $rejected_count; ?></div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-times-circle fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Required Documents Alert -->
    <?php if (!empty($missing_docs)): ?>
    <div class="alert alert-warning mb-4">
        <h5 class="alert-heading"><i class="fas fa-exclamation-triangle mr-2"></i> Required Documents</h5>
        <p>Please upload the following required documents to complete your profile:</p>
        <ul class="mb-0">
            <?php foreach ($missing_docs as $key => $name): ?>
            <li><strong><?php echo $name; ?></strong></li>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php endif; ?>
    
    <div class="row">
        <!-- Document Upload Form -->
        <div class="col-lg-4 mb-4">
            <div class="card shadow">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">Upload New Document</h6>
                </div>
                <div class="card-body">
                    <form method="POST" enctype="multipart/form-data">
                        <div class="form-group">
                            <label for="document_type">Document Type <span class="text-danger">*</span></label>
                            <select class="form-control" id="document_type" name="document_type" required>
                                <option value="">Select Document Type</option>
                                <?php foreach ($document_types as $key => $name): ?>
                                    <?php $is_required = array_key_exists($key, $required_docs); ?>
                                    <?php $is_missing = array_key_exists($key, $missing_docs); ?>
                                    <option value="<?php echo $key; ?>" <?php echo isset($_POST['document_type']) && $_POST['document_type'] === $key ? 'selected' : ''; ?>>
                                        <?php echo $name; ?>
                                        <?php if ($is_required): ?><span class="text-danger"> (Required)</span><?php endif; ?>
                                        <?php if ($is_missing): ?><span class="text-danger"> (Missing)</span><?php endif; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="form-group" id="custom_type_group" style="display: none;">
                            <label for="custom_type">Specify Document Type <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="custom_type" name="custom_type" value="<?php echo isset($_POST['custom_type']) ? htmlspecialchars($_POST['custom_type']) : ''; ?>">
                        </div>
                        
                        <div class="form-group">
                            <label for="document_title">Document Title <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="document_title" name="document_title" value="<?php echo isset($_POST['document_title']) ? htmlspecialchars($_POST['document_title']) : ''; ?>" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="document_file">Document File <span class="text-danger">*</span></label>
                            <input type="file" class="form-control" id="document_file" name="document_file" required>
                            <small class="form-text text-muted">Allowed file types: PDF, JPG, JPEG, PNG, DOC, DOCX. Max size: 5MB</small>
                        </div>
                        
                        <button type="submit" name="upload_document" class="btn btn-primary">
                            <i class="fas fa-upload mr-2"></i> Upload Document
                        </button>
                    </form>
                </div>
            </div>
        </div>
        
        <!-- Document List -->
        <div class="col-lg-8 mb-4">
            <div class="card shadow">
                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                    <h6 class="m-0 font-weight-bold text-primary">My Documents</h6>
                    <div>
                        <button class="btn btn-sm btn-light shadow-sm" id="viewToggleBtn" data-view="grid">
                            <i class="fas fa-list"></i> List View
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <?php if (empty($documents)): ?>
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle mr-2"></i> You haven't uploaded any documents yet.
                    </div>
                    <?php else: ?>
                    <!-- Grid View (Default) -->
                    <div class="row" id="documentsGrid">
                        <?php foreach ($documents as $document): ?>
                        <div class="col-md-6 mb-3">
                            <div class="card h-100 shadow-sm" data-document-id="<?php echo $document['id']; ?>">
                                <div class="card-header bg-light d-flex justify-content-between align-items-center">
                                    <span class="badge badge-<?php 
                                        echo $document['status'] === 'verified' ? 'success' : 
                                            ($document['status'] === 'pending' ? 'warning' : 'danger'); 
                                    ?>">
                                        <?php echo ucfirst($document['status']); ?>
                                    </span>
                                    <div class="dropdown no-arrow">
                                        <a class="dropdown-toggle" href="#" role="button" id="documentOptions<?php echo $document['id']; ?>" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                            <i class="fas fa-ellipsis-v fa-sm fa-fw text-gray-400"></i>
                                        </a>
                                        <div class="dropdown-menu dropdown-menu-right shadow animated--fade-in" aria-labelledby="documentOptions<?php echo $document['id']; ?>">
                                            <a class="dropdown-item" href="../<?php echo $document['document_path']; ?>" target="_blank">
                                                <i class="fas fa-eye mr-2"></i> View
                                            </a>
                                            <a class="dropdown-item" href="../<?php echo $document['document_path']; ?>" download>
                                                <i class="fas fa-download mr-2"></i> Download
                                            </a>
                                            <?php if ($document['status'] !== 'verified'): ?>
                                            <div class="dropdown-divider"></div>
                                            <a class="dropdown-item text-danger delete-document" href="javascript:void(0);" data-document-id="<?php echo $document['id']; ?>" data-document-title="<?php echo htmlspecialchars($document['document_title']); ?>">
                                                <i class="fas fa-trash-alt mr-2"></i> Delete
                                            </a>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="document-preview mb-3 text-center">
                                        <?php
                                        $file_extension = strtolower(pathinfo($document['document_path'], PATHINFO_EXTENSION));
                                        if (in_array($file_extension, ['jpg', 'jpeg', 'png'])) {
                                        ?>
                                            <img src="../<?php echo $document['document_path']; ?>" class="img-fluid document-thumbnail" alt="<?php echo htmlspecialchars($document['document_title']); ?>" style="max-height: 150px; max-width: 100%;">
                                        <?php } else { ?>
                                            <div class="document-icon">
                                                <i class="fas <?php 
                                                    echo $file_extension === 'pdf' ? 'fa-file-pdf' : 
                                                        (in_array($file_extension, ['doc', 'docx']) ? 'fa-file-word' : 'fa-file-alt'); 
                                                ?> fa-5x text-<?php 
                                                    echo $file_extension === 'pdf' ? 'danger' : 
                                                        (in_array($file_extension, ['doc', 'docx']) ? 'primary' : 'secondary'); 
                                                ?>"></i>
                                            </div>
                                        <?php } ?>
                                    </div>
                                    <h5 class="card-title"><?php echo htmlspecialchars($document['document_title']); ?></h5>
                                    <p class="card-text text-muted mb-2">
                                        <i class="fas fa-tag mr-1"></i> <?php echo ucfirst(str_replace('_', ' ', $document['document_type'])); ?>
                                    </p>
                                    <p class="card-text text-muted">
                                        <i class="fas fa-calendar-alt mr-1"></i> <?php echo date('M d, Y', strtotime($document['upload_date'])); ?>
                                    </p>
                                </div>
                                <div class="card-footer bg-light">
                                    <a href="../<?php echo $document['document_path']; ?>" target="_blank" class="btn btn-sm btn-outline-primary mr-2">
                                        <i class="fas fa-eye mr-1"></i> View
                                    </a>
                                    <a href="../<?php echo $document['document_path']; ?>" download class="btn btn-sm btn-outline-success">
                                        <i class="fas fa-download mr-1"></i> Download
                                    </a>
                                    <?php if ($document['status'] !== 'verified'): ?>
                                    <a href="documents.php?action=delete&id=<?php echo $document['id']; ?>" 
                                       class="btn btn-sm btn-outline-danger mt-2 w-100"
                                       onclick="return confirm('Are you sure you want to delete this document: <?php echo htmlspecialchars($document['document_title']); ?>?');">
                                        <i class="fas fa-trash-alt mr-1"></i> Delete
                                    </a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    
                    <!-- List View (Hidden by default) -->
                    <div class="table-responsive" id="documentsList" style="display: none;">
                        <table class="table table-bordered" width="100%" cellspacing="0">
                            <thead>
                                <tr>
                                    <th>Title</th>
                                    <th>Type</th>
                                    <th>Status</th>
                                    <th>Uploaded On</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($documents as $document): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($document['document_title']); ?></td>
                                    <td><?php echo ucfirst(str_replace('_', ' ', $document['document_type'])); ?></td>
                                    <td>
                                        <span class="badge badge-<?php 
                                            echo $document['status'] === 'verified' ? 'success' : 
                                                ($document['status'] === 'pending' ? 'warning' : 'danger'); 
                                        ?>">
                                            <?php echo ucfirst($document['status']); ?>
                                        </span>
                                    </td>
                                    <td><?php echo date('M d, Y', strtotime($document['upload_date'])); ?></td>
                                    <td>
                                        <a href="../<?php echo $document['document_path']; ?>" target="_blank" class="btn btn-sm btn-outline-primary mr-1">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        <a href="../<?php echo $document['document_path']; ?>" download class="btn btn-sm btn-outline-success mr-1">
                                            <i class="fas fa-download"></i>
                                        </a>
                                        <?php if ($document['status'] !== 'verified'): ?>
                                        <a href="documents.php?action=delete&id=<?php echo $document['id']; ?>" 
                                           class="btn btn-sm btn-outline-danger"
                                           onclick="return confirm('Are you sure you want to delete this document: <?php echo htmlspecialchars($document['document_title']); ?>?');">
                                            <i class="fas fa-trash-alt"></i>
                                        </a>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Delete Document Modal -->
<div class="modal fade" id="deleteDocumentModal" tabindex="-1" aria-labelledby="deleteDocumentModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteDocumentModalLabel">Delete Document</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete the document: <strong id="deleteDocumentTitle"></strong>?</p>
                <p class="text-danger">This action cannot be undone.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <form method="POST" id="deleteDocumentForm">
                    <input type="hidden" name="document_id" id="deleteDocumentId">
                    <input type="hidden" name="delete_document" value="1">
                    <button type="submit" class="btn btn-danger">Delete</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Add this JavaScript code to handle page refresh after deletion -->
<?php if ($need_refresh): ?>
<script>
// Clean the URL by removing the action and id parameters
window.history.replaceState({}, document.title, 'documents.php');
// Show a temporary success message
document.addEventListener('DOMContentLoaded', function() {
    // The success message is already displayed via PHP
});
</script>
<?php endif; ?>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Show/hide custom document type field
    const documentTypeSelect = document.getElementById('document_type');
    const customTypeGroup = document.getElementById('custom_type_group');
    
    if (documentTypeSelect && customTypeGroup) {
        documentTypeSelect.addEventListener('change', function() {
            if (this.value === 'other') {
                customTypeGroup.style.display = 'block';
            } else {
                customTypeGroup.style.display = 'none';
            }
        });
        
        // Trigger the change event on page load
        if (documentTypeSelect.value === 'other') {
            customTypeGroup.style.display = 'block';
        }
    }
    
    // Toggle between grid and list view
    const viewToggleBtn = document.getElementById('viewToggleBtn');
    const documentsGrid = document.getElementById('documentsGrid');
    const documentsList = document.getElementById('documentsList');
    
    if (viewToggleBtn && documentsGrid && documentsList) {
        viewToggleBtn.addEventListener('click', function() {
            const currentView = this.getAttribute('data-view');
            
            if (currentView === 'grid') {
                // Switch to list view
                documentsGrid.style.display = 'none';
                documentsList.style.display = 'block';
                this.innerHTML = '<i class="fas fa-th"></i> Grid View';
                this.setAttribute('data-view', 'list');
            } else {
                // Switch to grid view
                documentsGrid.style.display = 'flex';
                documentsList.style.display = 'none';
                this.innerHTML = '<i class="fas fa-list"></i> List View';
                this.setAttribute('data-view', 'grid');
            }
        });
    }
    
    // Initialize delete document functionality
    initializeDeleteDocuments();
    
    // Handle view toggle to reinitialize delete document functionality
    if (viewToggleBtn) {
        viewToggleBtn.addEventListener('click', function() {
            // Reinitialize delete handlers after view toggle
            initializeDeleteDocuments();
        });
    }
    
    // Function to initialize delete document handlers
    function initializeDeleteDocuments() {
        // Get all delete buttons
        const deleteButtons = document.querySelectorAll('.delete-document');
        const deleteDocumentTitle = document.getElementById('deleteDocumentTitle');
        const deleteDocumentId = document.getElementById('deleteDocumentId');
        const deleteDocumentForm = document.getElementById('deleteDocumentForm');
        
        deleteButtons.forEach(button => {
            // Remove any existing event listeners to prevent duplicates
            button.removeEventListener('click', handleDeleteClick);
            
            // Add new event listener
            button.addEventListener('click', handleDeleteClick);
        });
        
        // Delete button click handler
        function handleDeleteClick(event) {
            const documentId = this.getAttribute('data-document-id');
            const documentTitle = this.getAttribute('data-document-title');
            
            console.log('Delete clicked for document ID:', documentId, 'Title:', documentTitle);
            
            // Set values in the modal
            deleteDocumentTitle.textContent = documentTitle;
            deleteDocumentId.value = documentId;
            
            // Show the delete confirmation modal
            $('#deleteDocumentModal').modal('show');
        }
        
        // Handle document form submission with animation
        if (deleteDocumentForm) {
            // Remove existing listeners to prevent duplicates
            deleteDocumentForm.removeEventListener('submit', handleFormSubmit);
            
            // Add form submit handler
            deleteDocumentForm.addEventListener('submit', handleFormSubmit);
            
            function handleFormSubmit(e) {
                e.preventDefault();
                
                const documentId = deleteDocumentId.value;
                console.log('Form submitted for document ID:', documentId);
                
                // Hide the modal
                $('#deleteDocumentModal').modal('hide');
                
                // Submit the form immediately to avoid any issues
                this.submit();
            }
        }
    }
});
</script>

<?php include_once('includes/footer.php'); ?>