<?php

namespace App\Filament\Pages;

use App\Models\BackupLog;
use Filament\Pages\Page;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Auth;

class BackupRetentie extends Page
{
    protected static ?string $navigationIcon = 'heroicon-o-server-stack';
    protected static ?string $navigationLabel = 'Backup & Retenție';
    protected static ?string $title = 'Backup și retenție date';
    protected static ?string $navigationGroup = 'Administrare';
    protected static ?int $navigationSort = 100;
    protected static string $view = 'filament.pages.backup-retentie';

    public static function canAccess(): bool
    {
        $user = Auth::user();
        return $user && $user->hasAnyRole(['admin', 'director']);
    }

    public function getBackupLogs(): \Illuminate\Support\Collection
    {
        return BackupLog::orderByDesc('creat_la')->limit(50)->get();
    }

    public function getDbSize(): string
    {
        $dbPath = database_path('database.sqlite');
        if (!file_exists($dbPath)) return 'N/A';
        $size = filesize($dbPath);
        if ($size > 1048576) return number_format($size / 1048576, 1) . ' MB';
        return number_format($size / 1024, 1) . ' KB';
    }

    public function getBackupCount(): int
    {
        return BackupLog::where('status', 'succes')->count();
    }

    public function runBackup(): void
    {
        Artisan::call('catalog:backup');
        $this->dispatch('$refresh');
    }
}
