<?php

namespace App\Filament\Tenant\Pages;

use App\Models\Central\Company;
use App\Services\TenantBackupService;
use App\Tenancy\TenantManager;
use Filament\Notifications\Notification;
use Filament\Pages\Page;

class Backup extends Page
{
    protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-archive-box-arrow-down';

    protected static ?string $navigationLabel = 'Backup';

    protected static string|\UnitEnum|null $navigationGroup = 'Admin';

    protected static ?int $navigationSort = 96;

    protected static ?string $title = 'Backup & Export date';

    protected string $view = 'filament.tenant.pages.backup';

    public function downloadBackup()
    {
        $tenant = app(TenantManager::class)->current();
        if (! $tenant) abort(404);

        // Re-fetch via central scope to avoid issues.
        $company = Company::withoutGlobalScopes()->find($tenant->id);
        if (! $company) abort(404);

        $svc = app(TenantBackupService::class);
        $file = $svc->export($company);
        $filename = $svc->filename($company);

        return response()->download($file, $filename, [
            'Content-Type' => 'application/zip',
        ])->deleteFileAfterSend();
    }
}
