<?php

declare(strict_types=1);

namespace Install\Services;

final class InstallationProgress
{
    public function reset(): void
    {
        $_SESSION['install_progress'] = [
            'percent' => 0,
            'message' => 'Préparation de l’installation.',
            'log' => [],
        ];
    }

    public function update(
        int $percent,
        string $message
    ): void {
        $progress = $_SESSION['install_progress'] ?? [
            'percent' => 0,
            'message' => '',
            'log' => [],
        ];

        $progress['percent'] = max(
            0,
            min(100, $percent)
        );

        $progress['message'] = $message;
        $progress['log'][] = [
            'time' => date('H:i:s'),
            'message' => $message,
        ];

        $_SESSION['install_progress'] = $progress;
    }

    /**
     * @return array<string,mixed>
     */
    public function current(): array
    {
        return is_array(
            $_SESSION['install_progress'] ?? null
        )
            ? $_SESSION['install_progress']
            : [
                'percent' => 0,
                'message' => 'En attente.',
                'log' => [],
            ];
    }
}
