<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;

use App\Models\Folder;
use App\Models\FileMetadata;
use App\Models\FolderDocument;
use App\Models\User;
use App\Models\Role;
use App\Notifications\FileSharedNotification;
use App\Helpers\AuditLogger;


class FileController extends Controller   
{

    /**
     * Serve PDF for AJAX preview (PDF.js) with inline headers, not download
     */
    public function ajaxPreviewPdf(Request $request)
    {
        $fileName = $request->query('file_name');
        $folderId = $request->query('folder_id');
        if (!$fileName || !$folderId) {
            abort(404, 'Missing file or folder info');
        }
        $folder = Folder::findOrFail($folderId);
        $filePath = 'uploads/' . $fileName;
        if (!Storage::disk('public')->exists($filePath)) {
            abort(404, 'File not found');
        }
        $mimeType = Storage::disk('public')->mimeType($filePath);
        if ($mimeType !== 'application/pdf') {
            abort(415, 'Not a PDF file');
        }
        $fileContent = Storage::disk('public')->get($filePath);
        return response($fileContent, 200, [
            'Content-Type' => 'application/pdf',
            'Content-Disposition' => 'inline; filename="' . basename($fileName) . '"',
            'Cache-Control' => 'no-cache, no-store, must-revalidate',
            'Pragma' => 'no-cache',
            'Expires' => '0',
        ]);
    }

    /**
     * Share a file with users or roles
     */
    public function share(Request $request)
    {
        $request->validate([
            'file_id' => 'required|integer|exists:file_metadata,id',
            'users' => 'nullable|array',
            'users.*' => 'integer|exists:users,id',
            'roles' => 'nullable|array',
            'roles.*' => 'integer|exists:roles,id',
        ]);

        $fileId = $request->input('file_id');
        $userIds = $request->input('users', []);
        $roleIds = $request->input('roles', []);

        // Remove duplicates
        $userIds = array_unique(array_filter($userIds));
        $roleIds = array_unique(array_filter($roleIds));


        // Get file and sharer
        $file = FileMetadata::findOrFail($fileId);
        $sharedBy = Auth::user()->name ?? (Auth::user()->first_name . ' ' . Auth::user()->last_name);

        // Save user shares and notify
        foreach ($userIds as $userId) {
            \App\Models\FileShare::firstOrCreate([
                'file_metadata_id' => $fileId,
                'user_id' => $userId,
                'role_id' => null,
            ]);
            $user = User::find($userId);
            if ($user) {
                $user->notify(new FileSharedNotification($file, $sharedBy));
            }
        }

        // Save role shares and notify all users in the role
        foreach ($roleIds as $roleId) {
            \App\Models\FileShare::firstOrCreate([
                'file_metadata_id' => $fileId,
                'user_id' => null,
                'role_id' => $roleId,
            ]);
            $role = Role::find($roleId);
            if ($role) {
                foreach ($role->users as $user) {
                    $user->notify(new FileSharedNotification($file, $sharedBy));
                }
            }
        }

        // Optionally: remove shares not in the new list (not implemented here)

        // Return response
        AuditLogger::log('file_share', $file->id, 'shared', null, [
            'file_id' => $file->id,
            'file_name' => $file->file_name,
            'folder_id' => $file->folder_id,
            'users' => array_values($userIds),
            'roles' => array_values($roleIds),
        ]);

        if ($request->expectsJson()) {
            return response()->json(['success' => true, 'message' => 'File shared successfully.']);
        }
        return back()->with('message', 'File shared successfully.');
    }

    /**
     * Get users and roles with whom the file is shared
     */
    public function getSharedAccess($fileId)
    {
        // Get users with whom the file is shared
        $userShares = \App\Models\FileShare::where('file_metadata_id', $fileId)
            ->whereNotNull('user_id')
            ->with('user')
            ->get();

        $users = $userShares->map(function ($share) {
            if ($share->user) {
                return [
                    'id' => $share->user->id,
                    'first_name' => $share->user->first_name ?? '',
                    'last_name' => $share->user->last_name ?? '',
                    'email' => $share->user->email ?? '',
                ];
            }
            return null;
        })->filter()->values();

        // Get roles with whom the file is shared
        $roleShares = \App\Models\FileShare::where('file_metadata_id', $fileId)
            ->whereNotNull('role_id')
            ->with('role')
            ->get();

        $roles = $roleShares->map(function ($share) {
            if ($share->role) {
                return [
                    'id' => $share->role->id,
                    'name' => $share->role->name ?? '',
                ];
            }
            return null;
        })->filter()->values();

        return response()->json([
            'users' => $users,
            'roles' => $roles
        ]);
    }
    /**
     * Upload files to a folder with metadata
     */
    public function upload(Request $request)
        // Debug: print all request fields
    {
  
        try {
            // Convert 'on' to boolean for view_only
            $input = $request->all();

            $input['view_only'] = $request->has('view_only') && ($request->input('view_only') === 'on' || $request->input('view_only') === 1 || $request->input('view_only') === true);
            $request->replace($input);

            $request->validate([
                'files.*' => 'required|file|max:10240', // 10MB max per file
                'folder_id' => 'required|exists:folders,id',
                'meta_tags.*' => 'nullable|string|max:255',
                'meta_values.*' => 'nullable|string|max:1000',
                'overwrite' => 'nullable|boolean',
                'view_only' => 'nullable|boolean',
                'comment' => 'nullable|string|max:2000',
            ]);

            $folderId = $request->input('folder_id');
            $folder = Folder::findOrFail($folderId);
            $files = $request->file('files');
            $overwrite = $request->boolean('overwrite');
            $viewOnly = $request->boolean('view_only');

            // Get metadata arrays
            $metaTags = $request->input('meta_tags', []);
            $metaValues = $request->input('meta_values', []);

            // Clean up metadata arrays - remove empty entries
            $metadata = [];
            for ($i = 0; $i < count($metaTags); $i++) {
                if (!empty($metaTags[$i])) {
                    $metadata[] = [
                        'tag' => trim($metaTags[$i]),
                        'value' => isset($metaValues[$i]) ? trim($metaValues[$i]) : null
                    ];
                }
            }

            $uploadedFiles = [];
            $uploadedCount = 0;

            // Fix: define $comment from request
            $comment = $request->input('comment');

            foreach ($files as $file) {
                $originalName = $file->getClientOriginalName();
                $generatedName = $request->input('custom_generated_file_name');
                $extension = $file->getClientOriginalExtension();
                if (!empty($generatedName)) {
                    // Only add extension if not already present
                    $fileName = (str_ends_with(strtolower($generatedName), '.' . strtolower($extension)))
                        ? $generatedName
                        : $generatedName . '.' . $extension;
                } else {
                    $fileName = $originalName;
                }
                $filePath = 'uploads/' . $fileName;

                // Check for duplicate file name in the same folder
                if (Storage::disk('public')->exists($filePath) && !$overwrite) {
                    return back()->withErrors(['files' => 'A file named "' . $fileName . '" already exists in this folder. Please rename your file or enable overwrite.'])->withInput();
                }

                try {
                    // Store file to the public disk under the "uploads" folder
                    // (storage/app/public/uploads), using the generated file name.
                    $stored = Storage::disk('public')->putFileAs(
                        'uploads',
                        $file,
                        $fileName
                    );

                    if ($stored) {
                        $uploadedFiles[] = [
                            'original_name' => $originalName,
                            'stored_name' => $fileName,
                            'path' => $filePath
                        ];

                        // Save metadata for this file
                        $fileMeta = null;
                        if (count($metadata) > 0) {
                            foreach ($metadata as $meta) {
                                $fileMeta = FileMetadata::create([
                                    'file_path' => $filePath,
                                    'file_name' => $fileName,
                                    'folder_id' => $folderId,
                                    'meta_tag' => $meta['tag'],
                                    'meta_value' => $meta['value'],
                                    'uploaded_by' => Auth::id(),
                                    'comment' => $comment,
                                ]);
                            }
                        } else {
                            // Create a basic record even if no metadata is provided
                            $fileMeta = FileMetadata::create([
                                'file_path' => $filePath,
                                'file_name' => $fileName,
                                'folder_id' => $folderId,
                                'meta_tag' => null,
                                'meta_value' => null,
                                'uploaded_by' => Auth::id(),
                                'comment' => $comment,
                            ]);
                        }

                        // Also save comment to Document if exists for this file_path
                        $document = \App\Models\Document::where('file_path', $filePath)->first();
                        if ($document && $comment) {
                            $document->comments = $comment;
                            $document->save();
                        }

                        // Save view_only flag in file_shares for uploader
                        if ($fileMeta) {
                            \App\Models\FileShare::create([
                                'file_metadata_id' => $fileMeta->id,
                                'user_id' => Auth::id(),
                                'role_id' => null,
                                'view_only' => $viewOnly,
                            ]);

                            AuditLogger::log('file', $fileMeta->id, 'created', null, [
                                'file_id' => $fileMeta->id,
                                'file_name' => $fileName,
                                'file_path' => $filePath,
                                'folder_id' => $folderId,
                                'uploaded_by' => Auth::id(),
                                'view_only' => $viewOnly,
                            ]);
                        }

                   

                        $uploadedCount++;
                    }
                } catch (\Exception $e) {
                    \Log::error('Failed to upload file ' . $originalName . ': ' . $e->getMessage());
                    continue;
                }
            }

            if ($request->expectsJson()) {
                return response()->json([
                    'success' => true,
                    'message' => $uploadedCount . ' file(s) uploaded successfully!',
                    'uploaded_count' => $uploadedCount,
                    'uploaded_files' => $uploadedFiles,
                    'metadata_count' => count($metadata)
                ]);
            }

            return redirect()->back()->with('success', $uploadedCount . ' file(s) uploaded successfully!');

        } catch (\Illuminate\Validation\ValidationException $e) {
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed: ' . implode(', ', $e->validator->errors()->all())
                ], 422);
            }
            return back()->withErrors($e->validator)->withInput();

        } catch (\Exception $e) {
            \Log::error('Error uploading files1: ' . $e->getMessage());

            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Error uploading files2: ' . $e->getMessage()
                ], 500);
            }

            return back()->with('error', 'Error uploading files3: ' . $e->getMessage());
        }
    }

    /**
     * View file in browser (inline display)
     */
    public function view(Request $request)
    {
        try {
            $request->validate([
                'file_name' => 'required|string',
                'folder_id' => 'required|exists:folders,id',
            ]);

            $fileName = $request->input('file_name');
            $folderId = $request->input('folder_id');
            
            // Get the folder to construct the file path
            $folder = Folder::findOrFail($folderId);
            $filePath = 'uploads/' . $fileName;
            
            // Check if file exists in storage
            if (!Storage::disk('public')->exists($filePath)) {
                return response()->json([
                    'success' => false,
                    'message' => 'File not found.'
                ], 404);
            }
            
            // Get file extension to determine how to display
            $extension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
            
            // For images, serve directly with simple headers
            if (in_array($extension, ['jpg', 'jpeg', 'png', 'gif', 'svg'])) {
                $fileContents = Storage::disk('public')->get($filePath);
                $mimeType = Storage::disk('public')->mimeType($filePath);
                
                return response($fileContents, 200, [
                    'Content-Type' => $mimeType,
                    'Content-Disposition' => 'inline; filename="' . $fileName . '"',
                    'Cache-Control' => 'public, max-age=3600',
                ]);
            }
            
            // For text-based files, create a simple viewer
            if (in_array($extension, ['txt', 'html', 'htm', 'css', 'js', 'json', 'xml', 'log', 'md', 'csv'])) {
                return $this->createSimpleTextViewer($fileName, $folderId, $filePath, $extension);
            }
            
            // For PDFs, serve directly with PDF headers
            if ($extension === 'pdf') {
                $fileContents = Storage::disk('public')->get($filePath);
                
                return response($fileContents, 200, [
                    'Content-Type' => 'application/pdf',
                    'Content-Disposition' => 'inline; filename="' . $fileName . '"',
                    'Cache-Control' => 'public, max-age=3600',
                ]);
            }
            
            // For Office files (Word, Excel), serve with correct headers for iframe/Office viewer
            if (in_array($extension, ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'])) {
                $fileContents = Storage::disk('public')->get($filePath);
                $mimeType = Storage::disk('public')->mimeType($filePath);
                // Use Office MIME types for best compatibility
                $officeMimeTypes = [
                    'doc' => 'application/msword',
                    'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                    'xls' => 'application/vnd.ms-excel',
                    'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                    'ppt' => 'application/vnd.ms-powerpoint',
                    'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
                ];
                $mimeType = $officeMimeTypes[$extension] ?? $mimeType;
                return response($fileContents, 200, [
                    'Content-Type' => $mimeType,
                    'Content-Disposition' => 'inline; filename="' . $fileName . '"',
                    'Cache-Control' => 'no-cache, no-store, must-revalidate',
                    'Pragma' => 'no-cache',
                    'Expires' => '0',
                ]);
            }

            // For other files, serve directly with basic headers
            $fileContents = Storage::disk('public')->get($filePath);
            $mimeType = Storage::disk('public')->mimeType($filePath);
            return response($fileContents, 200, [
                'Content-Type' => $mimeType,
                'Content-Disposition' => 'inline; filename="' . $fileName . '"',
                'Cache-Control' => 'no-cache, no-store, must-revalidate',
                'Pragma' => 'no-cache',
                'Expires' => '0',
            ]);
            
        } catch (\Exception $e) {
            \Log::error('Error viewing file: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Error viewing file: ' . $e->getMessage()
            ], 500);
        }
    }
    
    /**
     * Create a simple text viewer for text-based files
     */
    private function createSimpleTextViewer($fileName, $folderId, $filePath, $extension)
    {
        // Get file contents
        $fileContents = Storage::disk('public')->get($filePath);
        $fileSize = Storage::disk('public')->size($filePath);
        
        $displayName = htmlspecialchars($fileName, ENT_QUOTES, 'UTF-8');
        $formattedSize = $this->formatFileSize($fileSize);
        
        // Escape content for safe display
        $textContent = htmlspecialchars($fileContents, ENT_QUOTES, 'UTF-8');
        
        // Create simple HTML viewer
        $html = "<!DOCTYPE html>
<html lang='en'>
<head>
    <meta charset='UTF-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <title>Viewing: {$displayName}</title>
    <style>
        body { 
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; 
            margin: 0; 
            padding: 20px; 
            background: #f5f5f5;
            line-height: 1.6;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        .header { 
            background: #007bff; 
            color: white;
            padding: 20px; 
        }
        .header h1 { 
            margin: 0 0 5px 0; 
            font-size: 20px;
            font-weight: 600;
        }
        .header .info { 
            opacity: 0.9;
            font-size: 14px; 
        }
        .content { 
            padding: 0;
        }
        .file-content {
            padding: 30px;
            max-height: 80vh;
            overflow: auto;
            white-space: pre-wrap;
            font-family: 'Courier New', monospace;
            font-size: 14px;
            line-height: 1.4;
            background: #f8f9fa;
            border-top: 1px solid #dee2e6;
        }
    </style>
</head>
<body>
    <div class='container'>
        <div class='header'>
            <h1>📄 {$displayName}</h1>
            <div class='info'>Size: {$formattedSize} | Type: " . strtoupper($extension) . " | View Mode</div>
        </div>
        
        <div class='content'>
            <div class='file-content'>{$textContent}</div>
        </div>
    </div>
</body>
</html>";
        
        return response($html, 200, [
            'Content-Type' => 'text/html; charset=utf-8',
            'Cache-Control' => 'no-cache, no-store, must-revalidate',
            'Pragma' => 'no-cache',
            'Expires' => '0',
        ]);
    }
    
    /**
     * Create a secure viewer page for sensitive files
     */
    private function createSecureViewer($fileName, $folderId, $filePath, $extension)
    {
        // Get file contents
        $fileContents = Storage::disk('public')->get($filePath);
        $fileSize = Storage::disk('public')->size($filePath);
        
        // Create a secure viewer HTML page
        $viewerHtml = $this->generateSecureViewerHtml($fileName, $fileContents, $extension, $fileSize);
        
        return response($viewerHtml, 200, [
            'Content-Type' => 'text/html; charset=utf-8',
            'Cache-Control' => 'no-cache, no-store, must-revalidate',
            'Pragma' => 'no-cache',
            'Expires' => '0',
            'X-Content-Type-Options' => 'nosniff',
            'Referrer-Policy' => 'no-referrer',
            'Content-Security-Policy' => "default-src 'self' 'unsafe-inline' 'unsafe-eval' data:; img-src 'self' data: blob:; object-src 'self' data:; frame-src 'self' data:; script-src 'self' 'unsafe-inline' 'unsafe-eval';",
        ]);
    }
    
    /**
     * Generate secure viewer HTML
     */
    private function generateSecureViewerHtml($fileName, $fileContents, $extension, $fileSize)
    {
        $displayName = htmlspecialchars($fileName, ENT_QUOTES, 'UTF-8');
        $formattedSize = $this->formatFileSize($fileSize);
        
        $content = '';
        $debugInfo = "Extension: {$extension}, File size: {$fileSize} bytes";
        
        switch ($extension) {
            case 'pdf':
                // For PDFs, create a simple embed without data URI to avoid CSP issues
                $content = "<div style='text-align: center; padding: 20px;'>
                    <div style='background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 5px; padding: 30px;'>
                        <div style='font-size: 48px; margin-bottom: 20px;'>📄</div>
                        <h3 style='color: #495057; margin-bottom: 15px;'>PDF Document</h3>
                        <p style='color: #6c757d; margin-bottom: 20px;'>Size: {$formattedSize}</p>
                        <div style='background: #e9ecef; padding: 15px; border-radius: 4px; margin: 20px 0;'>
                            <p style='margin: 0; color: #495057; font-size: 14px;'>
                                <strong>Note:</strong> PDF viewing in browser is temporarily disabled for security reasons.<br>
                                Please use the download option to view this file.
                            </p>
                        </div>
                    </div>
                </div>";
                $debugInfo .= " | PDF info displayed (direct viewing disabled)";
                break;
                
            case 'jpg':
            case 'jpeg':
            case 'png':
            case 'gif':
                $fileData = base64_encode($fileContents);
                $mimeType = 'image/' . ($extension === 'jpg' ? 'jpeg' : $extension);
                $content = "<div style='text-align: center;'><img src='data:{$mimeType};base64,{$fileData}' alt='{$displayName}' style='max-width: 100%; height: auto; box-shadow: 0 2px 8px rgba(0,0,0,0.1);'></div>";
                $debugInfo .= " | Image embedded as base64";
                break;
                
            case 'svg':
                $fileData = base64_encode($fileContents);
                $content = "<div style='text-align: center;'><img src='data:image/svg+xml;base64,{$fileData}' alt='{$displayName}' style='max-width: 100%; height: auto; box-shadow: 0 2px 8px rgba(0,0,0,0.1);'></div>";
                $debugInfo .= " | SVG embedded as base64";
                break;
                
            case 'txt':
            case 'log':
            case 'md':
                $textContent = htmlspecialchars($fileContents, ENT_QUOTES, 'UTF-8');
                $content = "<div style='background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 5px; padding: 20px;'>
                    <h4 style='margin-top: 0; color: #495057;'>Text Content</h4>
                    <pre style='white-space: pre-wrap; font-family: \"Courier New\", monospace; margin: 0; max-height: 500px; overflow-y: auto; font-size: 14px; line-height: 1.4; background: white; padding: 15px; border-radius: 3px;'>{$textContent}</pre>
                </div>";
                $debugInfo .= " | Text content length: " . strlen($textContent) . " chars";
                break;
                
            case 'html':
            case 'htm':
                // For HTML files, display as escaped text to prevent execution
                $htmlContent = htmlspecialchars($fileContents, ENT_QUOTES, 'UTF-8');
                $content = "<div style='background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 5px; padding: 20px;'>
                    <h4 style='margin-top: 0; color: #dc3545;'>HTML Source Code (Read-Only)</h4>
                    <pre style='white-space: pre-wrap; font-family: \"Courier New\", monospace; margin: 0; max-height: 500px; overflow-y: auto; font-size: 14px; line-height: 1.4; background: white; padding: 15px; border-radius: 3px;'>{$htmlContent}</pre>
                </div>";
                $debugInfo .= " | HTML content length: " . strlen($htmlContent) . " chars";
                break;
                
            case 'css':
                $cssContent = htmlspecialchars($fileContents, ENT_QUOTES, 'UTF-8');
                $content = "<div style='background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 5px; padding: 20px;'>
                    <h4 style='margin-top: 0; color: #6f42c1;'>CSS Stylesheet</h4>
                    <pre style='white-space: pre-wrap; font-family: \"Courier New\", monospace; margin: 0; max-height: 500px; overflow-y: auto; font-size: 14px; line-height: 1.4; background: white; padding: 15px; border-radius: 3px;'>{$cssContent}</pre>
                </div>";
                $debugInfo .= " | CSS content length: " . strlen($cssContent) . " chars";
                break;
                
            case 'js':
                $jsContent = htmlspecialchars($fileContents, ENT_QUOTES, 'UTF-8');
                $content = "<div style='background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 5px; padding: 20px;'>
                    <h4 style='margin-top: 0; color: #f39c12;'>JavaScript Code</h4>
                    <pre style='white-space: pre-wrap; font-family: \"Courier New\", monospace; margin: 0; max-height: 500px; overflow-y: auto; font-size: 14px; line-height: 1.4; background: white; padding: 15px; border-radius: 3px;'>{$jsContent}</pre>
                </div>";
                $debugInfo .= " | JavaScript content length: " . strlen($jsContent) . " chars";
                break;
                
            case 'json':
                $jsonContent = htmlspecialchars($fileContents, ENT_QUOTES, 'UTF-8');
                // Try to pretty-print JSON
                $jsonData = json_decode($fileContents, true);
                if ($jsonData !== null) {
                    $jsonContent = htmlspecialchars(json_encode($jsonData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8');
                }
                $content = "<div style='background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 5px; padding: 20px;'>
                    <h4 style='margin-top: 0; color: #28a745;'>JSON Data</h4>
                    <pre style='white-space: pre-wrap; font-family: \"Courier New\", monospace; margin: 0; max-height: 500px; overflow-y: auto; font-size: 14px; line-height: 1.4; background: white; padding: 15px; border-radius: 3px;'>{$jsonContent}</pre>
                </div>";
                $debugInfo .= " | JSON content length: " . strlen($jsonContent) . " chars";
                break;
                
            case 'xml':
                $xmlContent = htmlspecialchars($fileContents, ENT_QUOTES, 'UTF-8');
                $content = "<div style='background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 5px; padding: 20px;'>
                    <h4 style='margin-top: 0; color: #17a2b8;'>XML Document</h4>
                    <pre style='white-space: pre-wrap; font-family: \"Courier New\", monospace; margin: 0; max-height: 500px; overflow-y: auto; font-size: 14px; line-height: 1.4; background: white; padding: 15px; border-radius: 3px;'>{$xmlContent}</pre>
                </div>";
                $debugInfo .= " | XML content length: " . strlen($xmlContent) . " chars";
                break;
                
            case 'csv':
                $csvContent = htmlspecialchars($fileContents, ENT_QUOTES, 'UTF-8');
                $lines = explode("\n", $csvContent);
                $tableHtml = "<table style='width: 100%; border-collapse: collapse; font-size: 14px;'>";
                $isFirstRow = true;
                foreach (array_slice($lines, 0, 100) as $line) { // Limit to first 100 rows
                    if (trim($line) === '') continue;
                    $cells = str_getcsv($line);
                    $tableHtml .= $isFirstRow ? "<thead><tr>" : "<tr>";
                    foreach ($cells as $cell) {
                        $cellContent = htmlspecialchars(trim($cell), ENT_QUOTES, 'UTF-8');
                        $tableHtml .= $isFirstRow ? 
                            "<th style='border: 1px solid #dee2e6; padding: 8px; background: #f8f9fa; font-weight: bold;'>{$cellContent}</th>" :
                            "<td style='border: 1px solid #dee2e6; padding: 8px;'>{$cellContent}</td>";
                    }
                    $tableHtml .= $isFirstRow ? "</tr></thead><tbody>" : "</tr>";
                    $isFirstRow = false;
                }
                $tableHtml .= "</tbody></table>";
                
                $content = "<div style='background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 5px; padding: 20px;'>
                    <h4 style='margin-top: 0; color: #20c997;'>CSV Data (First 100 rows)</h4>
                    <div style='overflow-x: auto; max-height: 500px; overflow-y: auto; background: white; padding: 15px; border-radius: 3px;'>{$tableHtml}</div>
                </div>";
                $debugInfo .= " | CSV rows: " . count($lines);
                break;
                
            default:
                // For unsupported file types, show file info and download option
                $content = "<div style='text-align: center; padding: 40px; background: #f8f9fa; border: 2px dashed #dee2e6; border-radius: 5px;'>
                    <div style='font-size: 48px; margin-bottom: 20px;'>📄</div>
                    <h3 style='color: #6c757d; margin-bottom: 10px;'>File Preview Not Available</h3>
                    <p style='color: #6c757d; margin-bottom: 20px;'>This file type ({$extension}) cannot be previewed in the browser.</p>
                    <p style='color: #6c757d; font-size: 14px;'>File Size: {$formattedSize}</p>
                </div>";
                $debugInfo .= " | Unsupported file type";
                break;
        }
        
        return "<!DOCTYPE html>
<html lang='en'>
<head>
    <meta charset='UTF-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <title>Viewing: {$displayName}</title>
    <style>
        body { 
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; 
            margin: 0; 
            padding: 20px; 
            background: #f5f5f5;
            line-height: 1.6;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        .header { 
            background: #fff; 
            padding: 20px; 
            border-radius: 8px; 
            margin-bottom: 20px; 
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            border-left: 4px solid #007bff;
        }
        .header h1 { 
            margin: 0 0 10px 0; 
            color: #333; 
            font-size: 20px;
            font-weight: 600;
        }
        .header .info { 
            color: #666; 
            font-size: 14px; 
            background: #f8f9fa;
            padding: 8px 12px;
            border-radius: 4px;
            display: inline-block;
        }
        .content { 
            background: #fff; 
            padding: 30px; 
            border-radius: 8px; 
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            min-height: 400px;
        }
        .warning {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            color: #856404;
            padding: 15px;
            border-radius: 6px;
            margin-bottom: 20px;
            font-size: 14px;
        }
        .debug {
            background: #e7f3ff;
            border: 1px solid #b3d9ff;
            color: #0066cc;
            padding: 10px;
            border-radius: 4px;
            font-size: 12px;
            font-family: monospace;
            margin-bottom: 15px;
        }
    </style>
</head>
<body>
    <div class='container'>
        <div class='header'>
            <h1>📁 File Viewer - {$displayName}</h1>
            <div class='info'>Size: {$formattedSize} | Type: " . strtoupper($extension) . " | View Only Mode</div>
        </div>
        
        <div class='warning'>
            ⚠️ <strong>View Only Mode:</strong> This file is displayed for viewing purposes only. Download functionality is restricted.
        </div>
        
        <div class='debug'>
            🔧 Debug Info: {$debugInfo}
        </div>
        
        <div class='content'>
            {$content}
        </div>
    </div>
    
    <script>
        console.log('File viewer loaded successfully');
        console.log('File extension: {$extension}');
        console.log('File size: {$fileSize} bytes');
        
        // Basic protection while keeping content accessible
        document.addEventListener('contextmenu', function(e) {
            e.preventDefault();
            return false;
        });
        
        // Disable some keyboard shortcuts
        document.addEventListener('keydown', function(e) {
            if (e.ctrlKey && (e.key === 's' || e.key === 'p')) {
                e.preventDefault();
                return false;
            }
        });
    </script>
</body>
</html>";
    }
    
    /**
     * Format file size in human readable format
     */
    private 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';
        }
    }

    /**
     * Get file metadata
     */
    public function getMetadata(Request $request)
    {
        try {
            $request->validate([
                'file_name' => 'required|string',
                'folder_id' => 'nullable|integer'
            ]);
            
            $fileName = $request->input('file_name');
            $folderId = $request->input('folder_id');
            
            // Build file path
            if ($folderId) {
                $folder = Folder::findOrFail($folderId);
                $filePath = 'uploads/' . $fileName;
            } else {
                $filePath = $fileName;
            }
            
            $metadata = FileMetadata::getFileMetadata($filePath);
            
            return response()->json([
                'success' => true,
                'metadata' => $metadata,
                'file_path' => $filePath
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error retrieving metadata: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Download a file from the network storage
     */
    public function download(Request $request)
    {
        try {
            $request->validate([
                'file_name' => 'required|string',
                'folder_id' => 'required|exists:folders,id'
            ]);

            $fileName = $request->input('file_name');
            $folderId = $request->input('folder_id');
            $userId = Auth::id();

            // Get folder information
            $folder = Folder::findOrFail($folderId);
            $filePath = 'uploads/' . $fileName;

            // Check if file exists on network drive
            if (!Storage::disk('public')->exists($filePath)) {
                return response()->json([
                    'success' => false,
                    'message' => 'File not found on the network drive.'
                ], 404);
            }

            // Find file metadata
            $fileMeta = \App\Models\FileMetadata::where('file_path', $filePath)->first();
            if ($fileMeta) {
                // Check if this file is view-only for this user
                $fileShare = \App\Models\FileShare::where('file_metadata_id', $fileMeta->id)
                    ->where(function($q) use ($userId) {
                        $q->where('user_id', $userId)->orWhereNull('user_id');
                    })
                    ->orderByDesc('view_only')
                    ->first();
                if ($fileShare && $fileShare->view_only) {
                    return response()->json([
                        'success' => false,
                        'message' => 'Download is not allowed. This file is view-only.'
                    ], 403);
                }
            }

            // Get file content
            $fileContent = Storage::disk('public')->get($filePath);
            $mimeType = Storage::disk('public')->mimeType($filePath);
            $fileSize = Storage::disk('public')->size($filePath);

            // Sanitize filename for download
            $downloadName = basename($fileName);

            // Return file download response
            return response($fileContent)
                ->header('Content-Type', $mimeType ?: 'application/octet-stream')
                ->header('Content-Disposition', 'attachment; filename="' . $downloadName . '"')
                ->header('Content-Length', $fileSize)
                ->header('Cache-Control', 'no-cache, no-store, must-revalidate')
                ->header('Pragma', 'no-cache')
                ->header('Expires', '0');

        } catch (\Illuminate\Validation\ValidationException $e) {
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed: ' . implode(', ', $e->validator->errors()->all())
                ], 422);
            }
            return back()->withErrors($e->validator)->withInput();

        } catch (\Exception $e) {
            \Log::error('Error downloading file: ' . $e->getMessage());

            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Error downloading file: ' . $e->getMessage()
                ], 500);
            }

            return back()->with('error', 'Error downloading file: ' . $e->getMessage());
        }
    }

    /**
     * Search files by metadata
     */
    public function searchByMetadata(Request $request)
    {
        try {
            $request->validate([
                'tag' => 'required|string',
                'value' => 'required|string'
            ]);

            $files = FileMetadata::getFilesByMetadata(
                $request->input('tag'),
                $request->input('value')
            );

            return response()->json([
                'success' => true,
                'files' => $files
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error searching files: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Delete a file (only by creator)
     */
    public function delete(Request $request)
    {
        try {
            $request->validate([
                'file_name' => 'required|string',
                'folder_id' => 'required|exists:folders,id',
            ]);

            $fileName = $request->input('file_name');
            $folderId = $request->input('folder_id');
            
            // Get the folder to construct the file path
            $folder = Folder::findOrFail($folderId);
            $filePath = 'uploads/' . $fileName;
            
            // Check if file exists in storage
            if (!Storage::disk('public')->exists($filePath)) {
                return response()->json([
                    'success' => false,
                    'message' => 'File not found.'
                ], 404);
            }
            
            // Check if file exists in metadata (to verify creator)
            $fileMetadata = FileMetadata::where('file_path', $filePath)->first();
            
            if (!$fileMetadata) {
                return response()->json([
                    'success' => false,
                    'message' => 'File metadata not found. Unable to verify ownership.'
                ], 404);
            }
            
            // Check if current user is the creator of the file
            if ($fileMetadata->uploaded_by !== Auth::id()) {
                return response()->json([
                    'success' => false,
                    'message' => 'You can only delete files that you uploaded.'
                ], 403);
            }
            
            // Delete file from storage
            Storage::disk('public')->delete($filePath);

            $before = [
                'file_id' => $fileMetadata->id,
                'file_name' => $fileName,
                'file_path' => $filePath,
                'folder_id' => $folderId,
                'uploaded_by' => $fileMetadata->uploaded_by,
            ];
            
            // Delete file metadata from database
            FileMetadata::where('file_path', $filePath)->delete();

            AuditLogger::log('file', $fileMetadata->id, 'deleted', $before, null);
            
            return response()->json([
                'success' => true,
                'message' => 'File deleted successfully.'
            ]);
            
        } catch (\Exception $e) {
            \Log::error('Error deleting file: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Error deleting file: ' . $e->getMessage()
            ], 500);
        }
    }

        /**
     * Return only the file content for AJAX view-only modal preview.
     */
    public function ajaxViewContent(Request $request)
    {
        $request->validate([
            'file_name' => 'required|string',
            'folder_id' => 'required|exists:folders,id',
        ]);

        $fileName = $request->input('file_name');
        $folderId = $request->input('folder_id');
        $folder = \App\Models\Folder::findOrFail($folderId);
        $filePath = 'uploads/' . $fileName;

        if (!\Storage::disk('public')->exists($filePath)) {
            return response()->json([
                'success' => false,
                'message' => 'File not found.'
            ], 404);
        }

        $extension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
        if (in_array($extension, ['txt', 'html', 'htm', 'css', 'js', 'json', 'xml', 'log', 'md', 'csv'])) {
            $fileContents = \Storage::disk('public')->get($filePath);
            return response()->json([
                'success' => true,
                'content' => $fileContents,
                'file_name' => $fileName
            ]);
        } elseif ($extension === 'pdf') {
            // Generate a temporary URL for PDF.js (no download headers)
            $url = route('files.ajax-preview-pdf', ['folder_id' => $folderId, 'file_name' => $fileName, 't' => time()]);
            return response()->json([
                'success' => true,
                'url' => $url,
                'file_name' => $fileName
            ]);
        } else {
            return response()->json([
                'success' => false,
                'message' => 'Preview not supported for this file type.'
            ], 415);
        }
    }

    public function viewFileReadOnly($fileId)
    {
        $file = \App\Models\FileMetadata::findOrFail($fileId);
        $folder = $file->folder;
        $filePath = 'uploads/' . $file->name;
        if (!\Storage::disk('public')->exists($filePath)) {
            abort(404, 'File not found.');
        }
        $extension = strtolower(pathinfo($file->name, PATHINFO_EXTENSION));
        $content = '';
        if (in_array($extension, ['txt', 'html', 'htm', 'css', 'js', 'json', 'xml', 'log', 'md', 'csv'])) {
            $content = \Storage::disk('public')->get($filePath);
        } else {
            $content = 'Preview not supported for this file type.';
        }
        return view('files.readonly', [
            'file' => $file,
            'content' => $content,
        ]);
    }

     /**
     * Update file comment
     */
    public function updateComment(Request $request)
    {
        $request->validate([
            'file_id' => 'required|integer|exists:file_metadata,id',
            'comment' => 'nullable|string|max:2000',
        ]);
        $file = FileMetadata::findOrFail($request->input('file_id'));
        $before = [
            'file_id' => $file->id,
            'file_name' => $file->file_name,
            'comment' => $file->comment,
        ];
        $file->comment = $request->input('comment');
        $file->save();

        AuditLogger::log('file', $file->id, 'updated', $before, [
            'file_id' => $file->id,
            'file_name' => $file->file_name,
            'comment' => $file->comment,
        ]);

        return redirect()->back()->with('message', 'Comment updated successfully.');
    }

}
