<?php
session_start();
include 'layouts/dbconn.php';

// Check if the user is not logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Get user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT username, user_role, full_name, email, role_id FROM users WHERE user_id = ?";
$stmt = $conn->prepare($sql_user_details);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result_user_details = $stmt->get_result();

if ($result_user_details && $row_user_details = $result_user_details->fetch_assoc()) {
    $username = $row_user_details['username'];
    $user_role = $row_user_details['user_role'];
    $full_name = $row_user_details['full_name'];
    $email = $row_user_details['email'];
    $role_id = $row_user_details['role_id'];
} else {
    // Handle the case if user details are not found
    $_SESSION['error_message'] = "User details not found";
    header('Location: index.php');
    exit();
}

// Function to check user permissions
function hasPermission($role_id, $permission) {
    // Define permissions for different roles
    $permissions = [
        '1' => ['view', 'upload', 'create_folder', 'delete', 'share'], // Admin has all permissions
        '2' => ['view', 'upload', 'create_folder', 'share'],           // General Manager
        '3' => ['view', 'upload', 'create_folder'],                     // Operations
        '4' => ['view', 'upload'],                                      // Finance
        '5' => ['view', 'upload'],                                      // Declaration Officer
        '6' => ['view'],                                                // Shipping Line Clerk
        '7' => ['view'],                                                // Transport Supervisor
    ];
    
    if (isset($permissions[$role_id]) && in_array($permission, $permissions[$role_id])) {
        return true;
    }
    
    return false;
}

// Check permissions
$can_upload = hasPermission($role_id, 'upload');
$can_create_folder = hasPermission($role_id, 'create_folder');
$can_delete = hasPermission($role_id, 'delete');
$can_share = hasPermission($role_id, 'share');

// Get the current folder ID from the query string (if any)
$current_folder_id = isset($_GET['folder_id']) ? intval($_GET['folder_id']) : 0;
$search_term = isset($_GET['search']) ? $_GET['search'] : '';
$file_number_filter = isset($_GET['file_number']) ? $_GET['file_number'] : '';

// Get breadcrumb navigation
$breadcrumbs = [];
$temp_folder_id = $current_folder_id;

if ($temp_folder_id > 0) {
    $breadcrumb_sql = "SELECT folder_id, folder_name, parent_folder_id FROM file_folders WHERE folder_id = ? AND is_deleted = 0";
    $breadcrumb_stmt = $conn->prepare($breadcrumb_sql);
    
    while ($temp_folder_id > 0) {
        $breadcrumb_stmt->bind_param("i", $temp_folder_id);
        $breadcrumb_stmt->execute();
        $breadcrumb_result = $breadcrumb_stmt->get_result();
        
        if ($breadcrumb_result && $folder = $breadcrumb_result->fetch_assoc()) {
            array_unshift($breadcrumbs, [
                'id' => $folder['folder_id'],
                'name' => $folder['folder_name']
            ]);
            $temp_folder_id = $folder['parent_folder_id'];
        } else {
            $temp_folder_id = 0;
        }
    }
    
    $breadcrumb_stmt->close();
}

// Add root breadcrumb
array_unshift($breadcrumbs, [
    'id' => 0,
    'name' => 'Root'
]);

// Get folders in the current directory
$folders_sql = "SELECT f.*, u.username AS creator_name 
                FROM file_folders f 
                JOIN users u ON f.created_by = u.user_id 
                WHERE f.parent_folder_id " . ($current_folder_id > 0 ? "= ?" : "IS NULL") . " 
                AND f.is_deleted = 0";

// Add search condition if search term exists
if (!empty($search_term)) {
    $folders_sql .= " AND f.folder_name LIKE ?";
}

// Add file number filter if provided
if (!empty($file_number_filter)) {
    $folders_sql .= " AND f.related_file_number = ?";
}

$folders_sql .= " ORDER BY f.folder_name ASC";

$folders_stmt = $conn->prepare($folders_sql);

// Bind parameters based on the conditions
if ($current_folder_id > 0) {
    if (!empty($search_term) && !empty($file_number_filter)) {
        $search_param = "%$search_term%";
        $folders_stmt->bind_param("iss", $current_folder_id, $search_param, $file_number_filter);
    } elseif (!empty($search_term)) {
        $search_param = "%$search_term%";
        $folders_stmt->bind_param("is", $current_folder_id, $search_param);
    } elseif (!empty($file_number_filter)) {
        $folders_stmt->bind_param("is", $current_folder_id, $file_number_filter);
    } else {
        $folders_stmt->bind_param("i", $current_folder_id);
    }
} else {
    if (!empty($search_term) && !empty($file_number_filter)) {
        $search_param = "%$search_term%";
        $folders_stmt->bind_param("ss", $search_param, $file_number_filter);
    } elseif (!empty($search_term)) {
        $search_param = "%$search_term%";
        $folders_stmt->bind_param("s", $search_param);
    } elseif (!empty($file_number_filter)) {
        $folders_stmt->bind_param("s", $file_number_filter);
    }
}

$folders_stmt->execute();
$folders_result = $folders_stmt->get_result();
$folders = [];

if ($folders_result->num_rows > 0) {
    while ($folder = $folders_result->fetch_assoc()) {
        $folders[] = $folder;
    }
}

$folders_stmt->close();

// Get files in the current directory
$files_sql = "SELECT f.*, u.username AS uploader_name 
              FROM file_manager f 
              JOIN users u ON f.uploaded_by = u.user_id 
              WHERE f.folder_id " . ($current_folder_id > 0 ? "= ?" : "IS NULL") . " 
              AND f.is_deleted = 0";

// Add search condition if search term exists
if (!empty($search_term)) {
    $files_sql .= " AND (f.file_name LIKE ? OR f.description LIKE ?)";
}

// Add file number filter if provided
if (!empty($file_number_filter)) {
    $files_sql .= " AND f.related_file_number = ?";
}

$files_sql .= " ORDER BY f.upload_date DESC";

$files_stmt = $conn->prepare($files_sql);

// Bind parameters based on the conditions
if ($current_folder_id > 0) {
    if (!empty($search_term) && !empty($file_number_filter)) {
        $search_param = "%$search_term%";
        $files_stmt->bind_param("isss", $current_folder_id, $search_param, $search_param, $file_number_filter);
    } elseif (!empty($search_term)) {
        $search_param = "%$search_term%";
        $files_stmt->bind_param("iss", $current_folder_id, $search_param, $search_param);
    } elseif (!empty($file_number_filter)) {
        $files_stmt->bind_param("is", $current_folder_id, $file_number_filter);
    } else {
        $files_stmt->bind_param("i", $current_folder_id);
    }
} else {
    if (!empty($search_term) && !empty($file_number_filter)) {
        $search_param = "%$search_term%";
        $files_stmt->bind_param("sss", $search_param, $search_param, $file_number_filter);
    } elseif (!empty($search_term)) {
        $search_param = "%$search_term%";
        $files_stmt->bind_param("ss", $search_param, $search_param);
    } elseif (!empty($file_number_filter)) {
        $files_stmt->bind_param("s", $file_number_filter);
    }
}

$files_stmt->execute();
$files_result = $files_stmt->get_result();
$files = [];

if ($files_result->num_rows > 0) {
    while ($file = $files_result->fetch_assoc()) {
        $files[] = $file;
    }
}

$files_stmt->close();

// Get all file numbers for filter dropdown
$file_numbers_sql = "SELECT DISTINCT file_number FROM files ORDER BY file_number ASC";
$file_numbers_result = $conn->query($file_numbers_sql);
$file_numbers = [];

if ($file_numbers_result->num_rows > 0) {
    while ($row = $file_numbers_result->fetch_assoc()) {
        $file_numbers[] = $row['file_number'];
    }
}

// Get system name from settings
$sql_settings = "SELECT setting_value FROM settings WHERE setting_key = 'system_name'";
$result_settings = $conn->query($sql_settings);
if ($result_settings && $result_settings->num_rows > 0) {
    $row_settings = $result_settings->fetch_assoc();
    $system_name = $row_settings['setting_value'];
} else {
    $system_name = "Royal Freight";
}

// Function to format file size
function formatFileSize($bytes) {
    if ($bytes >= 1073741824) {
        return number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        return number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        return number_format($bytes / 1024, 2) . ' KB';
    } else {
        return $bytes . ' bytes';
    }
}

// Function to get file icon based on extension
function getFileIcon($extension) {
    $extension = strtolower($extension);
    
    $icons = [
        'pdf' => 'ri-file-pdf-line text-danger',
        'doc' => 'ri-file-word-line text-primary',
        'docx' => 'ri-file-word-line text-primary',
        'xls' => 'ri-file-excel-line text-success',
        'xlsx' => 'ri-file-excel-line text-success',
        'csv' => 'ri-file-excel-line text-success',
        'ppt' => 'ri-file-ppt-line text-warning',
        'pptx' => 'ri-file-ppt-line text-warning',
        'jpg' => 'ri-image-line text-info',
        'jpeg' => 'ri-image-line text-info',
        'png' => 'ri-image-line text-info',
        'gif' => 'ri-image-line text-info',
        'txt' => 'ri-file-text-line text-secondary',
        'zip' => 'ri-file-zip-line text-dark',
        'rar' => 'ri-file-zip-line text-dark',
        'mp4' => 'ri-video-line text-danger',
        'mp3' => 'ri-music-line text-success',
    ];
    
    return isset($icons[$extension]) ? $icons[$extension] : 'ri-file-line text-secondary';
}

// Function to check if file is viewable in browser
function isViewable($extension) {
    $viewable_extensions = ['pdf', 'jpg', 'jpeg', 'png', 'gif', 'txt'];
    return in_array(strtolower($extension), $viewable_extensions);
}

// Get all users for sharing
$users_sql = "SELECT user_id, username, full_name FROM users WHERE user_id != ? ORDER BY username ASC";
$users_stmt = $conn->prepare($users_sql);
$users_stmt->bind_param("i", $user_id);
$users_stmt->execute();
$users_result = $users_stmt->get_result();
$users = [];

if ($users_result->num_rows > 0) {
    while ($user = $users_result->fetch_assoc()) {
        $users[] = $user;
    }
}

$users_stmt->close();

// Close database connection
$conn->close();

// Common page title
$page_title = "File Manager";
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => $page_title)); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/dropzone@5.9.3/dist/min/dropzone.min.css" rel="stylesheet">
    
    <style>
        .folder-card, .file-card {
            transition: all 0.3s ease;
            cursor: pointer;
        }
        
        .folder-card:hover, .file-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15) !important;
        }
        
        .folder-icon {
            font-size: 2.5rem;
            color: #ffc107;
        }
        
        .file-icon {
            font-size: 2.5rem;
        }
        
        .breadcrumb-item a {
            text-decoration: none;
        }
        
        .dropzone {
            border: 2px dashed #0087F7;
            border-radius: 5px;
            background: white;
        }
        
        .file-actions {
            position: absolute;
            top: 10px;
            right: 10px;
            display: none;
        }
        
        .file-card:hover .file-actions,
        .folder-card:hover .file-actions {
            display: block;
        }
        
        .file-preview-modal .modal-dialog {
            max-width: 80%;
        }
        
        .file-preview-content {
            max-height: 80vh;
            overflow: auto;
        }
        
        .shared-badge {
            position: absolute;
            top: 10px;
            left: 10px;
        }
    </style>
</head>

<body>
    <!-- Begin page -->
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <!-- ============================================================== -->
        <!-- Start right Content here -->
        <!-- ============================================================== -->
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Document Management', 'title' => $page_title)); ?>
                    
                    <!-- Alert messages -->
                    <?php if (isset($_SESSION['success_message'])): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['success_message']; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                        <?php unset($_SESSION['success_message']); ?>
                    <?php endif; ?>
                    
                    <?php if (isset($_SESSION['error_message'])): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['error_message']; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                        <?php unset($_SESSION['error_message']); ?>
                    <?php endif; ?>
                    
                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header d-flex align-items-center">
                                    <h5 class="card-title mb-0 flex-grow-1">Files and Folders</h5>
                                    <div class="flex-shrink-0">
                                        <?php if ($can_upload): ?>
                                            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#uploadModal">
                                                <i class="ri-upload-2-line align-bottom me-1"></i> Upload Files
                                            </button>
                                        <?php endif; ?>
                                        
                                        <?php if ($can_create_folder): ?>
                                            <button type="button" class="btn btn-info ms-2" data-bs-toggle="modal" data-bs-target="#createFolderModal">
                                                <i class="ri-folder-add-line align-bottom me-1"></i> New Folder
                                            </button>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <!-- Search and Filter -->
                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <form action="file_manager.php" method="GET" class="d-flex gap-2">
                                                <?php if ($current_folder_id > 0): ?>
                                                    <input type="hidden" name="folder_id" value="<?php echo $current_folder_id; ?>">
                                                <?php endif; ?>
                                                <input type="text" class="form-control" name="search" placeholder="Search files or folders" value="<?php echo htmlspecialchars($search_term); ?>">
                                                <button type="submit" class="btn btn-primary">
                                                    <i class="ri-search-line"></i>
                                                </button>
                                            </form>
                                        </div>
                                        <div class="col-md-6">
                                            <form action="file_manager.php" method="GET" class="d-flex gap-2">
                                                <?php if ($current_folder_id > 0): ?>
                                                    <input type="hidden" name="folder_id" value="<?php echo $current_folder_id; ?>">
                                                <?php endif; ?>
                                                <?php if (!empty($search_term)): ?>
                                                    <input type="hidden" name="search" value="<?php echo htmlspecialchars($search_term); ?>">
                                                <?php endif; ?>
                                                <select name="file_number" class="form-select">
                                                    <option value="">All File Numbers</option>
                                                    <?php foreach ($file_numbers as $file_number): ?>
                                                        <option value="<?php echo htmlspecialchars($file_number); ?>" <?php echo ($file_number_filter == $file_number) ? 'selected' : ''; ?>>
                                                            <?php echo htmlspecialchars($file_number); ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                                <button type="submit" class="btn btn-secondary">
                                                    <i class="ri-filter-line"></i> Filter
                                                </button>
                                                <?php if (!empty($search_term) || !empty($file_number_filter)): ?>
                                                    <a href="file_manager.php<?php echo ($current_folder_id > 0) ? '?folder_id='.$current_folder_id : ''; ?>" class="btn btn-light">
                                                        <i class="ri-refresh-line"></i> Clear
                                                    </a>
                                                <?php endif; ?>
                                            </form>
                                        </div>
                                    </div>
                                    
                                    <!-- Breadcrumb Navigation -->
                                    <nav aria-label="breadcrumb" class="mb-3">
                                        <ol class="breadcrumb mb-0">
                                            <?php foreach ($breadcrumbs as $index => $breadcrumb): ?>
                                                <?php $is_last = ($index === count($breadcrumbs) - 1); ?>
                                                <li class="breadcrumb-item <?php echo $is_last ? 'active' : ''; ?>">
                                                    <?php if (!$is_last): ?>
                                                        <a href="file_manager.php<?php echo $breadcrumb['id'] > 0 ? '?folder_id='.$breadcrumb['id'] : ''; ?>">
                                                            <?php echo htmlspecialchars($breadcrumb['name']); ?>
                                                        </a>
                                                    <?php else: ?>
                                                        <?php echo htmlspecialchars($breadcrumb['name']); ?>
                                                    <?php endif; ?>
                                                </li>
                                            <?php endforeach; ?>
                                        </ol>
                                    </nav>
                                    
                                    <!-- Folders and Files -->
                                    <div class="row">
                                        <!-- Parent Folder Link (if in subfolder) -->
                                        <?php if ($current_folder_id > 0): ?>
                                            <div class="col-md-3 col-sm-6 mb-4">
                                                <a href="file_manager.php?folder_id=<?php echo $breadcrumbs[count($breadcrumbs) - 2]['id']; ?>" class="text-decoration-none">
                                                    <div class="card folder-card">
                                                        <div class="card-body text-center">
                                                            <i class="ri-arrow-left-line folder-icon"></i>
                                                            <h5 class="mt-2 mb-0">Go Back</h5>
                                                            <p class="text-muted small mb-0">Parent Directory</p>
                                                        </div>
                                                    </div>
                                                </a>
                                            </div>
                                        <?php endif; ?>
                                        
                                        <!-- Folders -->
                                        <?php if (empty($folders) && empty($files)): ?>
                                            <div class="col-12">
                                                <div class="text-center py-5">
                                                    <div class="avatar-md mx-auto mb-4">
                                                        <div class="avatar-title bg-light text-primary rounded-circle">
                                                            <i class="ri-folder-5-line fs-40"></i>
                                                        </div>
                                                    </div>
                                                    <h5>No files or folders found</h5>
                                                    <p class="text-muted">
                                                        <?php if (!empty($search_term) || !empty($file_number_filter)): ?>
                                                            Try adjusting your search or filter
                                                        <?php else: ?>
                                                            This folder is empty. Upload files or create folders to get started.
                                                        <?php endif; ?>
                                                    </p>
                                                </div>
                                            </div>
                                        <?php else: ?>
                                            <!-- Folders -->
                                            <?php foreach ($folders as $folder): ?>
                                                <div class="col-md-3 col-sm-6 mb-4">
                                                    <div class="card folder-card position-relative">
                                                        <!-- Actions -->
                                                        <div class="file-actions dropdown">
                                                            <button class="btn btn-sm btn-ghost-secondary" data-bs-toggle="dropdown" aria-expanded="false">
                                                                <i class="ri-more-2-fill"></i>
                                                            </button>
                                                            <ul class="dropdown-menu">
                                                                <li>
                                                                    <a class="dropdown-item" href="file_manager.php?folder_id=<?php echo $folder['folder_id']; ?>">
                                                                        <i class="ri-folder-open-line me-2"></i> Open
                                                                    </a>
                                                                </li>
                                                                <?php if ($can_share): ?>
                                                                <li>
                                                                    <a class="dropdown-item share-folder-btn" href="javascript:void(0);" data-folder-id="<?php echo $folder['folder_id']; ?>" data-folder-name="<?php echo htmlspecialchars($folder['folder_name']); ?>">
                                                                        <i class="ri-share-line me-2"></i> Share
                                                                    </a>
                                                                </li>
                                                                <?php endif; ?>
                                                                <?php if ($can_delete && $folder['created_by'] == $user_id): ?>
                                                                <li>
                                                                    <a class="dropdown-item text-danger delete-folder-btn" href="javascript:void(0);" data-folder-id="<?php echo $folder['folder_id']; ?>" data-folder-name="<?php echo htmlspecialchars($folder['folder_name']); ?>">
                                                                        <i class="ri-delete-bin-line me-2"></i> Delete
                                                                    </a>
                                                                </li>
                                                                <?php endif; ?>
                                                            </ul>
                                                        </div>
                                                        <a href="file_manager.php?folder_id=<?php echo $folder['folder_id']; ?>" class="text-decoration-none">
                                                            <div class="card-body text-center">
                                                                <i class="ri-folder-5-line folder-icon"></i>
                                                                <h5 class="mt-2 mb-0"><?php echo htmlspecialchars($folder['folder_name']); ?></h5>
                                                                <p class="text-muted small mb-0">
                                                                    Created: <?php echo date('M d, Y', strtotime($folder['created_date'])); ?>
                                                                </p>
                                                                <?php if (!empty($folder['related_file_number'])): ?>
                                                                <span class="badge bg-info mt-2"><?php echo htmlspecialchars($folder['related_file_number']); ?></span>
                                                                <?php endif; ?>
                                                            </div>
                                                        </a>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                            
                                            <!-- Files -->
                                            <?php foreach ($files as $file): ?>
                                                <div class="col-md-3 col-sm-6 mb-4">
                                                    <div class="card file-card position-relative">
                                                        <!-- Shared badge -->
                                                        <?php 
                                                        // In a real implementation, you would check if this file is shared
                                                        $is_shared = false; // Placeholder, replace with actual check
                                                        if ($is_shared): 
                                                        ?>
                                                        <div class="shared-badge">
                                                            <span class="badge rounded-pill bg-success">
                                                                <i class="ri-share-line"></i>
                                                            </span>
                                                        </div>
                                                        <?php endif; ?>
                                                        
                                                        <!-- Actions -->
                                                        <div class="file-actions dropdown">
                                                            <button class="btn btn-sm btn-ghost-secondary" data-bs-toggle="dropdown" aria-expanded="false">
                                                                <i class="ri-more-2-fill"></i>
                                                            </button>
                                                            <ul class="dropdown-menu">
                                                                <?php if (isViewable($file['file_extension'])): ?>
                                                                <li>
                                                                    <a class="dropdown-item preview-file-btn" href="javascript:void(0);" data-file-id="<?php echo $file['file_id']; ?>" data-file-path="<?php echo $file['file_path']; ?>" data-file-name="<?php echo htmlspecialchars($file['file_name']); ?>" data-file-type="<?php echo $file['file_type']; ?>" data-file-extension="<?php echo $file['file_extension']; ?>">
                                                                        <i class="ri-eye-line me-2"></i> Preview
                                                                    </a>
                                                                </li>
                                                                <?php endif; ?>
                                                                <li>
                                                                    <a class="dropdown-item" href="file_download.php?file_id=<?php echo $file['file_id']; ?>">
                                                                        <i class="ri-download-line me-2"></i> Download
                                                                    </a>
                                                                </li>
                                                                <?php if ($can_share): ?>
                                                                <li>
                                                                    <a class="dropdown-item share-file-btn" href="javascript:void(0);" data-file-id="<?php echo $file['file_id']; ?>" data-file-name="<?php echo htmlspecialchars($file['file_name']); ?>">
                                                                        <i class="ri-share-line me-2"></i> Share
                                                                    </a>
                                                                </li>
                                                                <?php endif; ?>
                                                                <?php if ($can_delete && $file['uploaded_by'] == $user_id): ?>
                                                                <li>
                                                                    <a class="dropdown-item text-danger delete-file-btn" href="javascript:void(0);" data-file-id="<?php echo $file['file_id']; ?>" data-file-name="<?php echo htmlspecialchars($file['file_name']); ?>">
                                                                        <i class="ri-delete-bin-line me-2"></i> Delete
                                                                    </a>
                                                                </li>
                                                                <?php endif; ?>
                                                            </ul>
                                                        </div>
                                                        
                                                        <div class="card-body text-center" <?php if (isViewable($file['file_extension'])): ?>style="cursor: pointer;" onclick="previewFile(<?php echo $file['file_id']; ?>, '<?php echo $file['file_path']; ?>', '<?php echo htmlspecialchars(addslashes($file['file_name'])); ?>', '<?php echo $file['file_type']; ?>', '<?php echo $file['file_extension']; ?>')"<?php endif; ?>>
                                                            <i class="<?php echo getFileIcon($file['file_extension']); ?> file-icon"></i>
                                                            <h5 class="mt-2 mb-0" title="<?php echo htmlspecialchars($file['file_name']); ?>">
                                                                <?php 
                                                                $display_name = strlen($file['file_name']) > 15 
                                                                    ? substr($file['file_name'], 0, 15) . '...' 
                                                                    : $file['file_name'];
                                                                echo htmlspecialchars($display_name); 
                                                                ?>
                                                            </h5>
                                                            <p class="text-muted small mb-0">
                                                                <?php echo formatFileSize($file['file_size']); ?> • <?php echo strtoupper($file['file_extension']); ?>
                                                            </p>
                                                            <p class="text-muted small mb-0">
                                                                Uploaded: <?php echo date('M d, Y', strtotime($file['upload_date'])); ?>
                                                            </p>
                                                            <?php if (!empty($file['related_file_number'])): ?>
                                                            <span class="badge bg-info mt-2"><?php echo htmlspecialchars($file['related_file_number']); ?></span>
                                                            <?php endif; ?>
                                                        </div>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- container-fluid -->
            </div>
            <!-- End Page-content -->

            <?php include 'layouts/footer.php'; ?>
        </div>
        <!-- end main content-->
    </div>
    <!-- END layout-wrapper -->

    <!-- MODALS -->
    
    <!-- Upload Files Modal -->
    <div class="modal fade" id="uploadModal" tabindex="-1" aria-labelledby="uploadModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="uploadModalLabel">Upload Files</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form action="file_upload.php" method="post" class="dropzone" id="fileUploadDropzone">
                        <input type="hidden" name="folder_id" value="<?php echo $current_folder_id; ?>">
                        <div class="dz-message needsclick">
                            <div class="mb-3">
                                <i class="display-4 text-muted ri-upload-cloud-2-line"></i>
                            </div>
                            <h4>Drop files here or click to upload.</h4>
                        </div>
                    </form>
                    
                    <div class="mt-4">
                        <div class="mb-3">
                            <label for="fileDescription" class="form-label">Description (optional)</label>
                            <textarea class="form-control" id="fileDescription" rows="2" placeholder="Enter a description for uploaded files"></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label for="fileRelatedFileNumber" class="form-label">Related File Number (optional)</label>
                            <select class="form-select" id="fileRelatedFileNumber">
                                <option value="">None</option>
                                <?php foreach ($file_numbers as $file_number): ?>
                                    <option value="<?php echo htmlspecialchars($file_number); ?>">
                                        <?php echo htmlspecialchars($file_number); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" id="uploadBtn">Upload</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Create Folder Modal -->
    <div class="modal fade" id="createFolderModal" tabindex="-1" aria-labelledby="createFolderModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="createFolderModalLabel">Create New Folder</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form action="create_folder.php" method="post">
                    <div class="modal-body">
                        <input type="hidden" name="parent_folder_id" value="<?php echo $current_folder_id; ?>">
                        
                        <div class="mb-3">
                            <label for="folderName" class="form-label">Folder Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="folderName" name="folder_name" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="folderRelatedFileNumber" class="form-label">Related File Number (optional)</label>
                            <select class="form-select" id="folderRelatedFileNumber" name="related_file_number">
                                <option value="">None</option>
                                <?php foreach ($file_numbers as $file_number): ?>
                                    <option value="<?php echo htmlspecialchars($file_number); ?>">
                                        <?php echo htmlspecialchars($file_number); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Create Folder</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- File Preview Modal -->
    <div class="modal fade file-preview-modal" id="filePreviewModal" tabindex="-1" aria-labelledby="filePreviewModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="filePreviewModalLabel">File Preview</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="file-preview-content" id="filePreviewContent">
                        <!-- Preview content will be loaded here -->
                    </div>
                </div>
                <div class="modal-footer">
                    <a href="#" class="btn btn-primary" id="previewDownloadBtn">
                        <i class="ri-download-line me-1"></i> Download
                    </a>
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Share File Modal -->
    <div class="modal fade" id="shareFileModal" tabindex="-1" aria-labelledby="shareFileModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="shareFileModalLabel">Share File</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form action="share_file.php" method="post">
                    <div class="modal-body">
                        <input type="hidden" name="file_id" id="shareFileId">
                        <input type="hidden" name="folder_id" id="shareFolderId">
                        <input type="hidden" name="share_type" id="shareType">
                        
                        <div class="mb-3">
                            <label for="shareItemName" class="form-label">Sharing:</label>
                            <input type="text" class="form-control" id="shareItemName" readonly>
                        </div>
                        
                        <div class="mb-3">
                            <label for="shareWithUser" class="form-label">Share with User <span class="text-danger">*</span></label>
                            <select class="form-select" id="shareWithUser" name="shared_with" required>
                                <option value="">Select User</option>
                                <?php foreach ($users as $user): ?>
                                    <option value="<?php echo $user['user_id']; ?>">
                                        <?php echo htmlspecialchars($user['full_name'] . ' (' . $user['username'] . ')'); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label for="permissionLevel" class="form-label">Permission Level</label>
                            <select class="form-select" id="permissionLevel" name="permission_level">
                                <option value="read">Read Only</option>
                                <option value="edit">Edit</option>
                                <option value="delete">Full Control</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label for="expireDate" class="form-label">Expiry Date (optional)</label>
                            <input type="date" class="form-control" id="expireDate" name="expire_date">
                            <small class="text-muted">Leave blank for no expiration</small>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Share</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- Delete Confirmation Modal -->
    <div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-labelledby="deleteConfirmModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteConfirmModalLabel">Confirm Delete</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p id="deleteConfirmText">Are you sure you want to delete this item?</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                    <form action="delete_item.php" method="post" id="deleteItemForm">
                        <input type="hidden" name="item_id" id="deleteItemId">
                        <input type="hidden" name="item_type" id="deleteItemType">
                        <input type="hidden" name="return_folder" value="<?php echo $current_folder_id; ?>">
                        <button type="submit" class="btn btn-danger">Delete</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>

    <script src="https://cdn.jsdelivr.net/npm/dropzone@5.9.3/dist/min/dropzone.min.js"></script>

    <script>
        Dropzone.autoDiscover = false;
        
        document.addEventListener("DOMContentLoaded", function() {
            // Initialize Dropzone
           // Initialize Dropzone with better error handling
var myDropzone = new Dropzone("#fileUploadDropzone", {
    url: "file_upload.php",
    paramName: "file",
    maxFilesize: 20, // MB
    addRemoveLinks: true,
    autoProcessQueue: false,
    uploadMultiple: true,
    parallelUploads: 5,
    maxFiles: 10,
    init: function() {
        var dz = this;
        
        // Log any errors for debugging
        this.on("error", function(file, errorMessage, xhr) {
            console.error("Dropzone error:", errorMessage);
            if (xhr) {
                console.error("Server response:", xhr.responseText);
            }
            
            // Add error message to the file
            if (typeof errorMessage === "string") {
                alert("Upload error: " + errorMessage);
            } else if (typeof errorMessage === "object") {
                alert("Upload error: " + JSON.stringify(errorMessage));
            }
        });
        
        // Set up the button to process the queue
        document.getElementById("uploadBtn").addEventListener("click", function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            console.log("Upload button clicked");
            console.log("Files in queue:", dz.getQueuedFiles().length);
            
            if (dz.getQueuedFiles().length === 0) {
                alert("Please add files to upload.");
                return;
            }
            
            // Add extra parameters
            dz.options.params = {
                folder_id: <?php echo $current_folder_id; ?>,
                description: document.getElementById("fileDescription").value,
                related_file_number: document.getElementById("fileRelatedFileNumber").value
            };
            
            console.log("Processing queue with params:", dz.options.params);
            dz.processQueue();
        });
        
        this.on("sending", function(file, xhr, formData) {
            console.log("Sending file:", file.name);
            // Show loading indicator or disable button
            document.getElementById("uploadBtn").disabled = true;
        });
        
        this.on("success", function(file, response) {
            console.log("File uploaded successfully:", file.name);
            console.log("Server response:", response);
        });
        
        this.on("successmultiple", function(files, response) {
            console.log("All files uploaded successfully");
            console.log("Server response:", response);
            
            // Handle success
            var modal = bootstrap.Modal.getInstance(document.getElementById('uploadModal'));
            modal.hide();
            
            // Refresh the page after a delay
            setTimeout(function() {
                window.location.reload();
            }, 1000);
        });
        
        this.on("errormultiple", function(files, errorMessage, xhr) {
            console.error("Error uploading files:", errorMessage);
            if (xhr) {
                console.error("Server response:", xhr.responseText);
            }
            
            alert("Error uploading files: " + (xhr ? xhr.responseText : errorMessage));
            document.getElementById("uploadBtn").disabled = false;
        });
    }
});
            
            // File preview function
            window.previewFile = function(fileId, filePath, fileName, fileType, fileExtension) {
                var previewContent = document.getElementById('filePreviewContent');
                var previewModal = new bootstrap.Modal(document.getElementById('filePreviewModal'));
                var previewTitle = document.getElementById('filePreviewModalLabel');
                var downloadBtn = document.getElementById('previewDownloadBtn');
                
                // Set modal title and download link
                previewTitle.textContent = fileName;
                downloadBtn.href = 'file_download.php?file_id=' + fileId;
                
                // Clear previous content
                previewContent.innerHTML = '';
                
                // Show loading spinner
                previewContent.innerHTML = '<div class="text-center py-5"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div><p class="mt-2">Loading preview...</p></div>';
                
                // Show the modal
                previewModal.show();
                
                // Based on file type, show appropriate preview
                fileExtension = fileExtension.toLowerCase();
                
                if (fileExtension === 'pdf') {
                    previewContent.innerHTML = '<iframe src="file_view.php?file_id=' + fileId + '" style="width:100%; height:70vh;" frameborder="0"></iframe>';
                } else if (['jpg', 'jpeg', 'png', 'gif'].includes(fileExtension)) {
                    previewContent.innerHTML = '<div class="text-center"><img src="file_view.php?file_id=' + fileId + '" class="img-fluid" alt="' + fileName + '"></div>';
                } else if (fileExtension === 'txt') {
                    // Fetch text content
                    fetch('file_view.php?file_id=' + fileId)
                        .then(response => response.text())
                        .then(text => {
                            previewContent.innerHTML = '<pre style="white-space: pre-wrap; word-break: break-word;">' + text + '</pre>';
                        })
                        .catch(error => {
                            previewContent.innerHTML = '<div class="alert alert-danger">Error loading file: ' + error.message + '</div>';
                        });
                } else {
                    // Unsupported file type
                    previewContent.innerHTML = '<div class="alert alert-info">Preview not available for this file type. Please download the file to view its contents.</div>';
                }
            };
            
            // Preview file button click event
            document.querySelectorAll('.preview-file-btn').forEach(function(btn) {
                btn.addEventListener('click', function() {
                    var fileId = this.getAttribute('data-file-id');
                    var filePath = this.getAttribute('data-file-path');
                    var fileName = this.getAttribute('data-file-name');
                    var fileType = this.getAttribute('data-file-type');
                    var fileExtension = this.getAttribute('data-file-extension');
                    
                    previewFile(fileId, filePath, fileName, fileType, fileExtension);
                });
            });
            
            // Share file button click event
            document.querySelectorAll('.share-file-btn').forEach(function(btn) {
                btn.addEventListener('click', function() {
                    var fileId = this.getAttribute('data-file-id');
                    var fileName = this.getAttribute('data-file-name');
                    
                    document.getElementById('shareFileId').value = fileId;
                    document.getElementById('shareFolderId').value = '';
                    document.getElementById('shareType').value = 'file';
                    document.getElementById('shareItemName').value = fileName;
                    
                    var shareModal = new bootstrap.Modal(document.getElementById('shareFileModal'));
                    shareModal.show();
                });
            });
            
            // Share folder button click event
            document.querySelectorAll('.share-folder-btn').forEach(function(btn) {
                btn.addEventListener('click', function() {
                    var folderId = this.getAttribute('data-folder-id');
                    var folderName = this.getAttribute('data-folder-name');
                    
                    document.getElementById('shareFileId').value = '';
                    document.getElementById('shareFolderId').value = folderId;
                    document.getElementById('shareType').value = 'folder';
                    document.getElementById('shareItemName').value = folderName;
                    
                    var shareModal = new bootstrap.Modal(document.getElementById('shareFileModal'));
                    shareModal.show();
                });
            });
            
            // Delete file button click event
            document.querySelectorAll('.delete-file-btn').forEach(function(btn) {
                btn.addEventListener('click', function() {
                    var fileId = this.getAttribute('data-file-id');
                    var fileName = this.getAttribute('data-file-name');
                    
                    document.getElementById('deleteItemId').value = fileId;
                    document.getElementById('deleteItemType').value = 'file';
                    document.getElementById('deleteConfirmText').textContent = 'Are you sure you want to delete the file "' + fileName + '"? This action cannot be undone.';
                    
                    var deleteModal = new bootstrap.Modal(document.getElementById('deleteConfirmModal'));
                    deleteModal.show();
                });
            });
            
            // Delete folder button click event
            document.querySelectorAll('.delete-folder-btn').forEach(function(btn) {
                btn.addEventListener('click', function() {
                    var folderId = this.getAttribute('data-folder-id');
                    var folderName = this.getAttribute('data-folder-name');
                    
                    document.getElementById('deleteItemId').value = folderId;
                    document.getElementById('deleteItemType').value = 'folder';
                    document.getElementById('deleteConfirmText').textContent = 'Are you sure you want to delete the folder "' + folderName + '" and all its contents? This action cannot be undone.';
                    
                    var deleteModal = new bootstrap.Modal(document.getElementById('deleteConfirmModal'));
                    deleteModal.show();
                });
            });
        });
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>