<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;

class FileManagerController extends Controller
{
    /**
     * Mostra la gestione file dell'amministratore
     */
    public function index()
    {
        $user = Auth::user();
        
        // Verifica che l'utente sia un amministratore  
        if (!$user->hasRole('amministratore') || !$user->amministratore) {
            abort(403, 'Accesso non autorizzato');
        }

        $amministratore = $user->amministratore;
        $basePath = $amministratore->getFolderPath();
        
        // Ottieni struttura cartelle
        $folders = $this->getFolderStructure($basePath);
        
        // Statistiche utilizzo spazio
        $stats = $this->calculateStorageStats($basePath);

        return view('admin.file-manager.index', compact('amministratore', 'folders', 'stats'));
    }

    /**
     * Mostra contenuto di una cartella specifica
     */
    public function folder(Request $request, $folder = '')
    {
        $user = Auth::user();
        $amministratore = $user->amministratore;
        $basePath = $amministratore->getFolderPath();
        
        // Sanitizza il path per sicurezza
        $safePath = $this->sanitizePath($folder);
        $fullPath = $basePath . '/' . $safePath;
        
        // Verifica che la cartella esista
        if (!Storage::disk('local')->exists($fullPath)) {
            abort(404, 'Cartella non trovata');
        }

        // Ottieni contenuto cartella
        $files = Storage::disk('local')->files($fullPath);
        $directories = Storage::disk('local')->directories($fullPath);
        
        // Formatta per la vista
        $formattedFiles = collect($files)->map(function ($file) {
            return [
                'name' => basename($file),
                'path' => $file,
                'size' => Storage::disk('local')->size($file),
                'modified' => Storage::disk('local')->lastModified($file),
                'type' => $this->getFileType($file),
            ];
        });

        $formattedDirs = collect($directories)->map(function ($dir) {
            return [
                'name' => basename($dir),
                'path' => $dir,
                'type' => 'folder',
            ];
        });

        return view('admin.file-manager.folder', compact(
            'amministratore', 
            'formattedFiles', 
            'formattedDirs', 
            'safePath',
            'fullPath'
        ));
    }

    /**
     * Upload file nella cartella dell'amministratore
     */
    public function upload(Request $request)
    {
        $request->validate([
            'file' => 'required|file|max:10240', // Max 10MB
            'folder' => 'nullable|string',
        ]);

        $user = Auth::user();
        $amministratore = $user->amministratore;
        $basePath = $amministratore->getFolderPath();
        
        $folder = $this->sanitizePath($request->folder ?? 'documenti/allegati');
        $uploadPath = $basePath . '/' . $folder;

        // Upload file
        $file = $request->file('file');
        $filename = time() . '_' . $file->getClientOriginalName();
        
        $file->storeAs($uploadPath, $filename, 'local');

        return redirect()->back()->with('success', "File {$filename} caricato con successo");
    }

    /**
     * Download file dall'archivio amministratore
     */
    public function download($filePath)
    {
        $user = Auth::user();
        $amministratore = $user->amministratore;
        $basePath = $amministratore->getFolderPath();
        
        $safePath = $this->sanitizePath($filePath);
        $fullPath = $basePath . '/' . $safePath;
        
        // Verifica che il file esista e appartenga all'amministratore
        if (!Storage::disk('local')->exists($fullPath)) {
            abort(404, 'File non trovato');
        }

        return response()->download(storage_path("app/{$fullPath}"));
    }

    /**
     * Ottieni struttura cartelle
     */
    private function getFolderStructure($basePath): array
    {
        $structure = [
            'documenti' => [
                'allegati' => [],
                'contratti' => [],
                'assemblee' => [],
                'preventivi' => [],
            ],
            'backup' => [
                'database' => [],
                'files' => [],
            ],
            'exports' => [],
            'logs' => [],
        ];

        foreach ($structure as $folder => $subfolders) {
            if (is_array($subfolders)) {
                foreach ($subfolders as $subfolder => $content) {
                    $path = "{$basePath}/{$folder}/{$subfolder}";
                    $structure[$folder][$subfolder] = $this->getFolderInfo($path);
                }
            } else {
                $path = "{$basePath}/{$folder}";
                $structure[$folder] = $this->getFolderInfo($path);
            }
        }

        return $structure;
    }

    /**
     * Ottieni info cartella
     */
    private function getFolderInfo($path): array
    {
        if (!Storage::disk('local')->exists($path)) {
            return ['files' => 0, 'size' => 0];
        }

        $files = Storage::disk('local')->allFiles($path);
        $totalSize = 0;

        foreach ($files as $file) {
            $totalSize += Storage::disk('local')->size($file);
        }

        return [
            'files' => count($files),
            'size' => $totalSize,
        ];
    }

    /**
     * Calcola statistiche storage
     */
    private function calculateStorageStats($basePath): array
    {
        $allFiles = Storage::disk('local')->allFiles($basePath);
        $totalSize = 0;
        $fileTypes = [];

        foreach ($allFiles as $file) {
            $size = Storage::disk('local')->size($file);
            $totalSize += $size;
            
            $ext = pathinfo($file, PATHINFO_EXTENSION);
            $fileTypes[$ext] = ($fileTypes[$ext] ?? 0) + 1;
        }

        return [
            'total_files' => count($allFiles),
            'total_size' => $totalSize,
            'file_types' => $fileTypes,
        ];
    }

    /**
     * Sanitizza path per sicurezza
     */
    private function sanitizePath($path): string
    {
        // Rimuovi caratteri pericolosi
        $path = str_replace(['../', '../', '..\\'], '', $path);
        $path = trim($path, '/\\');
        
        return $path;
    }

    /**
     * Ottieni tipo file
     */
    private function getFileType($file): string
    {
        $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        
        $types = [
            'pdf' => 'document',
            'doc' => 'document', 'docx' => 'document',
            'xls' => 'spreadsheet', 'xlsx' => 'spreadsheet',
            'jpg' => 'image', 'jpeg' => 'image', 'png' => 'image', 'gif' => 'image',
            'zip' => 'archive', 'rar' => 'archive', '7z' => 'archive',
        ];

        return $types[$ext] ?? 'file';
    }
}
