<?php

namespace App\Http\Controllers\Agency;

use App\Http\Controllers\Controller;
use App\Models\Disk\DiskFolder;
use App\Models\Disk\DiskItem;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Intervention\Image\Facades\Image;

class DiskController extends Controller
{
    use AuthorizesRequests;

    /**
     * Display main disk page with folders and recent items.
     */
    public function index(Request $request)
    {
        $agency = auth()->user()->agency;

        // Get root folders with statistics
        $folders = DiskFolder::where('agency_id', $agency->id)
            ->active()
            ->with(['children'])
            ->root()
            ->orderBy('sort_order')
            ->orderBy('name')
            ->get();

        // Calculate statistics for each folder (including subfolders)
        foreach ($folders as $folder) {
            $folderIds = $this->getAllSubfolderIds($folder);
            $folder->total_item_count = DiskItem::whereIn('folder_id', $folderIds)
                ->active()
                ->approved()
                ->latestVersions()
                ->count();

            $folder->total_size_bytes = DiskItem::whereIn('folder_id', $folderIds)
                ->active()
                ->approved()
                ->latestVersions()
                ->sum('file_size');
        }

        // Get recent items
        $recentItems = DiskItem::whereHas('folder', function ($query) use ($agency) {
            $query->where('agency_id', $agency->id);
        })
            ->active()
            ->approved()
            ->latestVersions()
            ->with(['folder', 'creator'])
            ->latest()
            ->limit(12)
            ->get();

        // Get storage statistics
        $stats = $this->getStorageStatistics($agency->id);

        return view('agency.disk.index', compact('folders', 'recentItems', 'stats'));
    }

    /**
     * Display all folders in a tree structure.
     */
    public function folders()
    {
        $agency = auth()->user()->agency;

        $folders = DiskFolder::where('agency_id', $agency->id)
            ->active()
            ->with(['parent', 'children'])
            ->orderBy('level')
            ->orderBy('sort_order')
            ->orderBy('name')
            ->get();

        return view('agency.disk.folders.index', compact('folders'));
    }

    /**
     * Show form to create a new folder.
     */
    public function createFolder()
    {
        $agency = auth()->user()->agency;

        $parentFolders = DiskFolder::where('agency_id', $agency->id)
            ->active()
            ->orderBy('path')
            ->get();

        return view('agency.disk.folders.create', compact('parentFolders'));
    }

    /**
     * Store a new folder.
     */
    public function storeFolder(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'parent_id' => 'nullable|exists:disk_folders,id',
            'folder_type' => 'required|string|in:general,tour,hotel,transport,activity,document,contract,invoice,other',
            'color_code' => 'nullable|regex:/^#[a-fA-F0-9]{6}$/',
            'icon' => 'nullable|string|max:50',
            'is_public' => 'boolean'
        ]);

        $agency = auth()->user()->agency;

        // Check if parent folder belongs to the same agency
        if ($request->parent_id) {
            $parentFolder = DiskFolder::find($request->parent_id);
            if ($parentFolder->agency_id !== $agency->id) {
                return back()->withErrors(['parent_id' => 'Geçersiz üst klasör.']);
            }
        }

        // Generate unique slug
        $slug = $this->generateUniqueSlug($request->name);

        $folder = DiskFolder::create([
            'name' => $request->name,
            'slug' => $slug,
            'description' => $request->description,
            'parent_id' => $request->parent_id,
            'agency_id' => $agency->id,
            'folder_type' => $request->folder_type,
            'color_code' => $request->color_code,
            'icon' => $request->icon,
            'is_public' => $request->boolean('is_public', false),
            'sort_order' => DiskFolder::where('parent_id', $request->parent_id)->count()
        ]);

        return redirect()->route('agency.disk.folders.show', $folder)
            ->with('success', 'Klasör başarıyla oluşturuldu.');
    }

    /**
     * Display a specific folder with its items.
     */
    public function showFolder(DiskFolder $folder)
    {
        // Authorization check
        if ($folder->agency_id !== auth()->user()->agency_id) {
            abort(403, 'Bu klasöre erişim yetkiniz yok.');
        }

        $folder->load([
            'parent',
            'children' => function ($query) {
                $query->active()->orderBy('sort_order')->orderBy('name');
            },
            'items' => function ($query) {
                $query->active()
                    ->approved()
                    ->latestVersions()
                    ->orderBy('sort_order')
                    ->orderBy('original_name');
            }
        ]);

        // Get breadcrumbs
        $breadcrumbs = $folder->getPathHierarchy();

        // Get file type statistics for this folder
        $fileTypeStats = DiskItem::where('folder_id', $folder->id)
            ->active()
            ->approved()
            ->latestVersions()
            ->selectRaw('file_type, COUNT(*) as count, SUM(file_size) as total_size')
            ->groupBy('file_type')
            ->get();

        return view('agency.disk.folders.show', compact('folder', 'breadcrumbs', 'fileTypeStats'));
    }

    /**
     * Show form to edit a folder.
     */
    public function editFolder(DiskFolder $folder)
    {
        // Authorization check
        if ($folder->agency_id !== auth()->user()->agency_id) {
            abort(403, 'Bu klasörü düzenleme yetkiniz yok.');
        }

        $agency = auth()->user()->agency;

        $parentFolders = DiskFolder::where('agency_id', $agency->id)
            ->where('id', '!=', $folder->id)
            ->active()
            ->orderBy('path')
            ->get();

        return view('agency.disk.folders.edit', compact('folder', 'parentFolders'));
    }

    /**
     * Update a folder.
     */
    public function updateFolder(Request $request, DiskFolder $folder)
    {
        // Authorization check
        if ($folder->agency_id !== auth()->user()->agency_id) {
            abort(403, 'Bu klasörü düzenleme yetkiniz yok.');
        }

        $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'parent_id' => 'nullable|exists:disk_folders,id',
            'folder_type' => 'required|string|in:general,tour,hotel,transport,activity,document,contract,invoice,other',
            'color_code' => 'nullable|regex:/^#[a-fA-F0-9]{6}$/',
            'icon' => 'nullable|string|max:50',
            'is_public' => 'boolean'
        ]);

        // Prevent setting itself as parent
        if ($request->parent_id == $folder->id) {
            return back()->withErrors(['parent_id' => 'Klasör kendi üst klasörü olamaz.']);
        }

        // Check if parent folder belongs to the same agency
        if ($request->parent_id) {
            $parentFolder = DiskFolder::find($request->parent_id);
            if ($parentFolder->agency_id !== $folder->agency_id) {
                return back()->withErrors(['parent_id' => 'Geçersiz üst klasör.']);
            }
        }

        // Generate unique slug if name changed
        $slug = $folder->slug;
        if ($request->name !== $folder->name) {
            $slug = $this->generateUniqueSlug($request->name, $folder->id);
        }

        $folder->update([
            'name' => $request->name,
            'slug' => $slug,
            'description' => $request->description,
            'parent_id' => $request->parent_id,
            'folder_type' => $request->folder_type,
            'color_code' => $request->color_code,
            'icon' => $request->icon,
            'is_public' => $request->boolean('is_public', false)
        ]);

        return redirect()->route('agency.disk.folders.show', $folder)
            ->with('success', 'Klasör başarıyla güncellendi.');
    }

    /**
     * Delete a folder.
     */
    public function destroyFolder(DiskFolder $folder)
    {
        // Authorization check
        if ($folder->agency_id !== auth()->user()->agency_id) {
            abort(403, 'Bu klasörü silme yetkiniz yok.');
        }

        $folderName = $folder->name;
        $folder->delete();

        return redirect()->route('agency.disk.folders.index')
            ->with('success', "'{$folderName}' klasörü ve içeriği başarıyla silindi.");
    }

    /**
     * Display all items with filters.
     */
    public function items(Request $request)
    {
        $agency = auth()->user()->agency;

        $query = DiskItem::whereHas('folder', function ($q) use ($agency) {
            $q->where('agency_id', $agency->id);
        })
            ->active()
            ->approved()
            ->latestVersions();

        // Filter by folder
        if ($request->folder_id) {
            $query->where('folder_id', $request->folder_id);
        }

        // Filter by file type
        if ($request->file_type) {
            $query->where('file_type', $request->file_type);
        }

        // Search
        if ($request->search) {
            $query->search($request->search);
        }

        // Filter by orientation (for images)
        if ($request->orientation) {
            $query->where('orientation', $request->orientation);
        }

        // Filter by date range
        if ($request->date_from) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }
        if ($request->date_to) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }

        // Sort
        $sortBy = $request->get('sort_by', 'created_at');
        $sortOrder = $request->get('sort_order', 'desc');
        $query->orderBy($sortBy, $sortOrder);

        $items = $query->with(['folder', 'creator'])
            ->paginate(24)
            ->appends($request->all());

        // Get folders for filter dropdown
        $folders = DiskFolder::where('agency_id', $agency->id)
            ->active()
            ->orderBy('path')
            ->get();

        // Get file type counts for filters
        $fileTypeCounts = DiskItem::whereHas('folder', function ($q) use ($agency) {
            $q->where('agency_id', $agency->id);
        })
            ->active()
            ->approved()
            ->latestVersions()
            ->selectRaw('file_type, COUNT(*) as count')
            ->groupBy('file_type')
            ->pluck('count', 'file_type');

        return view('agency.disk.items.index', compact('items', 'folders', 'fileTypeCounts'));
    }

    /**
     * Upload files to a folder.
     */
    public function uploadFiles(Request $request, DiskFolder $folder)
    {
        // Authorization check
        if ($folder->agency_id !== auth()->user()->agency_id) {
            abort(403, 'Bu klasöre dosya yükleme yetkiniz yok.');
        }

        $request->validate([
            'files' => 'required|array',
            'files.*' => 'file|max:51200' // 50MB max
        ]);

        $uploadedFiles = [];
        $errors = [];

        foreach ($request->file('files') as $file) {
            try {
                $uploadedFiles[] = $this->processFileUpload($file, $folder);
            } catch (\Exception $e) {
                $errors[] = $file->getClientOriginalName() . ': ' . $e->getMessage();
            }
        }

        // Update folder statistics
        $folder->updateStatistics();

        $response = [
            'success' => count($uploadedFiles) > 0,
            'message' => count($uploadedFiles) . ' dosya başarıyla yüklendi.',
            'files' => $uploadedFiles
        ];

        if (!empty($errors)) {
            $response['errors'] = $errors;
            $response['message'] .= ' ' . count($errors) . ' dosya yüklenemedi.';
        }

        return response()->json($response);
    }

    /**
     * Show a specific item.
     */
    public function showItem(DiskItem $item)
    {
        // Authorization check
        if ($item->folder->agency_id !== auth()->user()->agency_id) {
            abort(403, 'Bu dosyaya erişim yetkiniz yok.');
        }

        // Increment view count
        $item->incrementViews();

        // Load relationships
        $item->load(['folder', 'creator', 'updater', 'versions', 'parentVersion']);

        return view('agency.disk.items.show', compact('item'));
    }

    /**
     * Show form to edit an item.
     */
    public function editItem(DiskItem $item)
    {
        // Authorization check
        if ($item->folder->agency_id !== auth()->user()->agency_id) {
            abort(403, 'Bu dosyayı düzenleme yetkiniz yok.');
        }

        $agency = auth()->user()->agency;

        $folders = DiskFolder::where('agency_id', $agency->id)
            ->active()
            ->orderBy('path')
            ->get();

        return view('agency.disk.items.edit', compact('item', 'folders'));
    }

    /**
     * Update an item's metadata.
     */
    public function updateItem(Request $request, DiskItem $item)
    {
        // Authorization check
        if ($item->folder->agency_id !== auth()->user()->agency_id) {
            abort(403, 'Bu dosyayı düzenleme yetkiniz yok.');
        }

        $request->validate([
            'title' => 'nullable|string|max:255',
            'description' => 'nullable|string',
            'alt_text' => 'nullable|string|max:255',
            'tags' => 'nullable|string',
            'folder_id' => 'required|exists:disk_folders,id',
            'copyright' => 'nullable|string|max:255',
            'author' => 'nullable|string|max:255',
            'language' => 'nullable|string|max:10',
            'is_featured' => 'boolean',
            'is_public' => 'boolean'
        ]);

        // Process tags
        $tags = $request->tags ? array_map('trim', explode(',', $request->tags)) : [];

        // Check if new folder belongs to the same agency
        $newFolder = DiskFolder::find($request->folder_id);
        if ($newFolder->agency_id !== $item->folder->agency_id) {
            return back()->withErrors(['folder_id' => 'Geçersiz klasör.']);
        }

        $oldFolderId = $item->folder_id;

        $item->update([
            'title' => $request->title,
            'description' => $request->description,
            'alt_text' => $request->alt_text,
            'tags' => $tags,
            'folder_id' => $request->folder_id,
            'copyright' => $request->copyright,
            'author' => $request->author,
            'language' => $request->language,
            'is_featured' => $request->boolean('is_featured', false),
            'is_public' => $request->boolean('is_public', false) // Default false
        ]);

        // Update folder statistics if folder changed
        if ($oldFolderId !== $item->folder_id) {
            DiskFolder::find($oldFolderId)?->updateStatistics();
            $newFolder->updateStatistics();
        }

        return redirect()->route('agency.disk.items.show', $item)
            ->with('success', 'Dosya bilgileri başarıyla güncellendi.');
    }

    /**
     * Delete an item.
     */
    public function destroyItem(DiskItem $item)
    {
        // Authorization check
        if ($item->folder->agency_id !== auth()->user()->agency_id) {
            abort(403, 'Bu dosyayı silme yetkiniz yok.');
        }

        $fileName = $item->original_name;
        $item->delete();

        return redirect()->route('agency.disk.items.index')
            ->with('success', "'{$fileName}' dosyası başarıyla silindi.");
    }

    /**
     * Download an item.
     */
    public function downloadItem(DiskItem $item)
    {
        // Authorization check
        if ($item->folder->agency_id !== auth()->user()->agency_id) {
            abort(403, 'Bu dosyayı indirme yetkiniz yok.');
        }

        // Increment download count
        $item->incrementDownloads();

        // Download file
        return Storage::download($item->file_path, $item->original_name);
    }

    /**
     * Upload a new version of an existing item.
     */
    public function uploadVersion(Request $request, DiskItem $item)
    {
        // Authorization check
        if ($item->folder->agency_id !== auth()->user()->agency_id) {
            abort(403, 'Bu dosyaya yeni versiyon yükleme yetkiniz yok.');
        }

        $request->validate([
            'file' => 'required|file|max:51200', // 50MB max
            'version_notes' => 'nullable|string'
        ]);

        $file = $request->file('file');

        // Check if file extension matches
        if ($file->getClientOriginalExtension() !== $item->extension) {
            return back()->withErrors(['file' => 'Yüklenen dosyanın uzantısı orijinal dosya ile uyuşmuyor.']);
        }

        try {
            // Process the new file
            $fileData = $this->processFileUpload($file, $item->folder);

            // Create new version
            $newVersion = $item->createVersion([
                'title' => $item->title,
                'description' => $item->description,
                'alt_text' => $item->alt_text,
                'tags' => $item->tags,
                'original_name' => $fileData->original_name,
                'filename' => $fileData->filename,
                'file_path' => $fileData->file_path,
                'file_url' => $fileData->file_url,
                'mime_type' => $fileData->mime_type,
                'extension' => $fileData->extension,
                'file_size' => $fileData->file_size,
                'file_type' => $fileData->file_type,
                'file_hash' => $fileData->file_hash,
                'width' => $fileData->width ?? null,
                'height' => $fileData->height ?? null,
                'aspect_ratio' => $fileData->aspect_ratio ?? null,
                'orientation' => $fileData->orientation ?? null,
                'thumbnail_path' => $fileData->thumbnail_path ?? null,
                'version_notes' => $request->version_notes,
                'is_active' => true,
                'is_public' => $item->is_public,
                'is_approved' => true,
                'approved_at' => now(),
                'approved_by' => auth()->id()
            ]);

            // Update folder statistics
            $item->folder->updateStatistics();

            return redirect()->route('agency.disk.items.show', $newVersion)
                ->with('success', 'Yeni versiyon başarıyla yüklendi. (v' . $newVersion->version_number . ')');

        } catch (\Exception $e) {
            return back()->withErrors(['file' => 'Dosya yüklenirken bir hata oluştu: ' . $e->getMessage()]);
        }
    }

    /**
     * Restore a previous version.
     */
    public function restoreVersion(DiskItem $item, DiskItem $version)
    {
        // Authorization check
        if ($item->folder->agency_id !== auth()->user()->agency_id) {
            abort(403, 'Versiyon geri yükleme yetkiniz yok.');
        }

        // Check if version belongs to the item
        if ($version->parent_version_id !== $item->id && $version->id !== $item->id) {
            abort(403, 'Geçersiz versiyon.');
        }

        // Mark all versions as not latest
        DiskItem::where('parent_version_id', $item->id)
            ->orWhere('id', $item->id)
            ->update(['is_latest_version' => false]);

        // Mark selected version as latest
        $version->update(['is_latest_version' => true]);

        return redirect()->route('agency.disk.items.show', $version)
            ->with('success', 'Versiyon ' . $version->version_number . ' geri yüklendi.');
    }

    /**
     * Process file upload and create DiskItem.
     */
    private function processFileUpload($file, DiskFolder $folder)
    {
        $originalName = $file->getClientOriginalName();
        $extension = $file->getClientOriginalExtension();
        $mimeType = $file->getMimeType();
        $fileSize = $file->getSize();

        // Generate unique filename
        $filename = time() . '_' . Str::random(10) . '.' . $extension;
        $path = "disk/{$folder->agency_id}/{$folder->id}";

        // Store file
        $filePath = $file->storeAs($path, $filename, 'public');
        $fileUrl = Storage::url($filePath);

        // Determine file type
        $fileType = DiskItem::determineFileType($mimeType);

        // Generate file hash
        $fileHash = hash_file('sha256', $file->getRealPath());

        // Check for duplicates
        $duplicate = DiskItem::where('file_hash', $fileHash)
            ->where('folder_id', $folder->id)
            ->latestVersions()
            ->first();

        if ($duplicate) {
            // Delete uploaded file
            Storage::delete($filePath);
            throw new \Exception('Bu dosya zaten klasörde mevcut: ' . $duplicate->original_name);
        }

        // Initialize data
        $itemData = [
            'folder_id' => $folder->id,
            'original_name' => $originalName,
            'filename' => $filename,
            'file_path' => $filePath,
            'file_url' => $fileUrl,
            'mime_type' => $mimeType,
            'extension' => $extension,
            'file_size' => $fileSize,
            'file_type' => $fileType,
            'file_hash' => $fileHash,
            'is_processed' => false,
            'is_active' => true,
            'is_public' => false, // Default: Private/Özel
            'is_approved' => true,
            'approved_at' => now(),
            'approved_by' => auth()->id()
        ];

        // Process based on file type
        if ($fileType === 'image') {
            $imageData = $this->processImage($file, $path, $filename);
            $itemData = array_merge($itemData, $imageData);
        } elseif ($fileType === 'document' && in_array($extension, ['pdf'])) {
            $documentData = $this->processDocument($file);
            $itemData = array_merge($itemData, $documentData);
        }

        // Create item
        return DiskItem::create($itemData);
    }

    /**
     * Process image files (dimensions, thumbnail, etc).
     */
    private function processImage($file, $path, $filename)
    {
        $data = [];

        // Get image dimensions
        $imageInfo = getimagesize($file->getRealPath());
        if ($imageInfo) {
            $width = $imageInfo[0];
            $height = $imageInfo[1];

            $data['width'] = $width;
            $data['height'] = $height;
            $data['aspect_ratio'] = $width && $height ? round($width / $height, 3) : null;

            // Calculate orientation
            if ($width > $height) {
                $data['orientation'] = 'landscape';
            } elseif ($width < $height) {
                $data['orientation'] = 'portrait';
            } else {
                $data['orientation'] = 'square';
            }
        }

        // Create thumbnail
        $thumbnailPath = $this->createThumbnail($file, $path, $filename);
        if ($thumbnailPath) {
            $data['thumbnail_path'] = $thumbnailPath;
            $data['preview_type'] = 'thumbnail';
        }

        $data['is_processed'] = true;

        return $data;
    }

    /**
     * Process document files (page count, etc).
     */
    private function processDocument($file)
    {
        $data = [];

        try {
            // For PDF files, get page count
            if (class_exists('\Smalot\PdfParser\Parser')) {
                $parser = new \Smalot\PdfParser\Parser();
                $pdf = $parser->parseFile($file->getRealPath());
                $pages = $pdf->getPages();
                $data['page_count'] = count($pages);

                // Extract text for search
                $text = $pdf->getText();
                if ($text) {
                    $data['extracted_text'] = substr($text, 0, 10000); // First 10k chars
                }
            }
        } catch (\Exception $e) {
            // Silently fail - PDF processing is optional
        }

        $data['is_processed'] = true;
        $data['preview_type'] = 'pdf_preview';

        return $data;
    }

    /**
     * Create thumbnail for images.
     */
    private function createThumbnail($file, $path, $filename)
    {
        try {
            $thumbnailFilename = 'thumb_' . $filename;
            $thumbnailPath = $path . '/' . $thumbnailFilename;
            $fullPath = storage_path('app/public/' . $thumbnailPath);

            // Create directory if not exists
            if (!is_dir(dirname($fullPath))) {
                mkdir(dirname($fullPath), 0755, true);
            }

            // Get image info
            $info = getimagesize($file->getRealPath());
            if (!$info) {
                return null;
            }

            [$width, $height, $type] = $info;

            // Calculate new dimensions
            $maxSize = 300;
            $ratio = min($maxSize / $width, $maxSize / $height);
            $newWidth = intval($width * $ratio);
            $newHeight = intval($height * $ratio);

            // Load source image
            $source = null;
            switch ($type) {
                case IMAGETYPE_JPEG:
                    $source = imagecreatefromjpeg($file->getRealPath());
                    break;
                case IMAGETYPE_PNG:
                    $source = imagecreatefrompng($file->getRealPath());
                    break;
                case IMAGETYPE_GIF:
                    $source = imagecreatefromgif($file->getRealPath());
                    break;
                case IMAGETYPE_WEBP:
                    $source = imagecreatefromwebp($file->getRealPath());
                    break;
                default:
                    return null;
            }

            if (!$source) {
                return null;
            }

            // Create thumbnail
            $thumb = imagecreatetruecolor($newWidth, $newHeight);

            // Preserve transparency for PNG and GIF
            if ($type === IMAGETYPE_PNG || $type === IMAGETYPE_GIF) {
                imagealphablending($thumb, false);
                imagesavealpha($thumb, true);
                $transparent = imagecolorallocatealpha($thumb, 255, 255, 255, 127);
                imagefilledrectangle($thumb, 0, 0, $newWidth, $newHeight, $transparent);
            }

            imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

            // Save thumbnail
            switch ($type) {
                case IMAGETYPE_JPEG:
                    imagejpeg($thumb, $fullPath, 85);
                    break;
                case IMAGETYPE_PNG:
                    imagepng($thumb, $fullPath, 8);
                    break;
                case IMAGETYPE_GIF:
                    imagegif($thumb, $fullPath);
                    break;
                case IMAGETYPE_WEBP:
                    imagewebp($thumb, $fullPath, 85);
                    break;
            }

            imagedestroy($source);
            imagedestroy($thumb);

            return $thumbnailPath;

        } catch (\Exception $e) {
            return null;
        }
    }

    /**
     * Get storage statistics for the agency.
     */
    private function getStorageStatistics($agencyId)
    {
        $stats = [];

        // Total items
        $stats['total_items'] = DiskItem::whereHas('folder', function ($q) use ($agencyId) {
            $q->where('agency_id', $agencyId);
        })
            ->active()
            ->latestVersions()
            ->count();

        // Total size
        $stats['total_size'] = DiskItem::whereHas('folder', function ($q) use ($agencyId) {
            $q->where('agency_id', $agencyId);
        })
            ->active()
            ->latestVersions()
            ->sum('file_size');

        // File type breakdown
        $stats['by_type'] = DiskItem::whereHas('folder', function ($q) use ($agencyId) {
            $q->where('agency_id', $agencyId);
        })
            ->active()
            ->latestVersions()
            ->selectRaw('file_type, COUNT(*) as count, SUM(file_size) as size')
            ->groupBy('file_type')
            ->get()
            ->keyBy('file_type');

        // Total folders
        $stats['total_folders'] = DiskFolder::where('agency_id', $agencyId)
            ->active()
            ->count();

        return $stats;
    }

    /**
     * Get all subfolder IDs recursively.
     */
    private function getAllSubfolderIds(DiskFolder $folder)
    {
        $ids = [$folder->id];

        $children = DiskFolder::where('parent_id', $folder->id)->active()->get();

        foreach ($children as $child) {
            $ids = array_merge($ids, $this->getAllSubfolderIds($child));
        }

        return $ids;
    }

    /**
     * Generate a unique slug for folder.
     */
    private function generateUniqueSlug($name, $excludeId = null)
    {
        $slug = Str::slug($name);
        $originalSlug = $slug;
        $counter = 1;

        // Check if slug exists (excluding current folder if updating)
        while (true) {
            $query = DiskFolder::where('slug', $slug);

            if ($excludeId) {
                $query->where('id', '!=', $excludeId);
            }

            if (!$query->exists()) {
                break;
            }

            // Append counter to make it unique
            $slug = $originalSlug . '-' . $counter;
            $counter++;
        }

        return $slug;
    }
}
