<?php

namespace App\Livewire\Admin;

use Livewire\Component;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Storage;

class DiskUsageComponent extends Component
{
    public array $disks = [];
    public  $disksData;



    public function mount()
    {
        $availableDisks = Config::get('filesystems.disks');

        $this->disks = collect($availableDisks)
            ->filter(function ($config, $name) {
                // Customize this list to avoid local/temp/test disks if needed
                return in_array($name, ['public', 'public_upload', 'google', 'dropbox', 'onedrive']);
            })
            ->map(function ($config, $name) {
                return [
                    'key' => $name,
                    'name' => ucfirst($name),
                    'max' => 5 * 1024 * 1024 * 1024, // 10 GB default quota
                    'icon' => match ($name) {
                        'google' => 'lni lni-google-drive',
                        'dropbox' => 'lni lni-dropbox-original',
                        'onedrive' => 'bx bxs-door-open',
                        default => 'bx bx-hdd',
                    },
                    'bg' => match ($name) {
                        'google' => 'bg-primary',
                        'dropbox' => 'bg-danger',
                        'onedrive' => 'bg-warning text-dark',
                        default => 'bg-secondary',
                    }
                ];
            })->values()->toArray();
    }

    public function getDiskUsage($diskKey)
    {
        try {
            $disk = Storage::disk($diskKey);
            $files = $disk->allFiles();
            $totalSize = 0;

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

            return $totalSize;
        } catch (\Throwable $e) {
            return 0;
        }
    }

    public function render()
    {
        $this->disksData = collect($this->disks)->map(function ($disk) {
            $used = $this->getDiskUsage($disk['key']);
            $disk['used'] = $used;
            $disk['percent'] = $disk['max'] > 0 ? round(($used / $disk['max']) * 100, 2) : 0;
            return $disk;
        });
        return view('livewire.admin.disk-usage-component');
    }
}
