<?php

namespace App\Services\Install;

/**
 * The installer runs before the app's DB-backed session driver is fully
 * usable (Step 3 configures the DB!), but CodeIgniter's session service
 * defaults to its FileHandler regardless of what .env eventually
 * specifies, so it's safe to use here. Using CI4's own session() service
 * (rather than raw PHP session_start()) avoids double-initializing the
 * session — CodeIgniter's CodeIgniter::storePreviousURL() also touches
 * the session service on every GET request, and calling session_start()
 * directly conflicts with that (ini_set() fails once a session is active).
 */
class InstallSession
{
    private const KEY = 'installer_wizard_state';
    private \CodeIgniter\Session\Session $session;

    public function __construct()
    {
        $this->session = session();
        if ($this->session->get(self::KEY) === null) {
            $this->session->set(self::KEY, []);
        }
    }

    public function set(string $step, array $data): void
    {
        $state = $this->session->get(self::KEY);
        $state[$step] = $data;
        $this->session->set(self::KEY, $state);
    }

    public function get(string $step): array
    {
        $state = $this->session->get(self::KEY);
        return $state[$step] ?? [];
    }

    public function all(): array
    {
        return $this->session->get(self::KEY) ?? [];
    }

    public function markStepComplete(int $step): void
    {
        $state = $this->session->get(self::KEY);
        $state['completed'][$step] = true;
        $this->session->set(self::KEY, $state);
    }

    public function isStepComplete(int $step): bool
    {
        $state = $this->session->get(self::KEY);
        return $state['completed'][$step] ?? false;
    }

    public function highestCompletedStep(): int
    {
        $state = $this->session->get(self::KEY);
        $completed = $state['completed'] ?? [];
        return $completed ? max(array_keys($completed)) : 0;
    }

    public function clear(): void
    {
        $this->session->remove(self::KEY);
    }
}
