<?php

namespace onespace\tools\components;

use Yii;


/**
 * Gets, sets and otherwise handles data from $_SESSION pertaining to the estate manager's selected estate.
 */

final class SelectedEstate {

    private const ESTATE_CACHE_SESSION_NAME_MANAGER = 'estate.current';
    private const ESTATE_CACHE_SESSION_NAME_RESIDENT = 'estate.resident.current';


    /**
     * Return the session data for the estate set in the session.
     * 
     * @return  array|false Returns false if the session value is not set.
     * 
     * @static
     * @access  public
     */

    public static function getCache(string $context = 'm'): array|false {
        $sessionName = match ($context) {
            'r' => self::ESTATE_CACHE_SESSION_NAME_RESIDENT,
            default => self::ESTATE_CACHE_SESSION_NAME_MANAGER,
        };
        return Yii::$app->session->get($sessionName . Yii::$app->user->id, false);
    }


    /**
     * Sets the session cache with parsed data.
     * 
     * @param   int     $selectedEstateId   The id of the selected estate.
     * @param   string  $selectedEstateName The name of the selected estate.
     * @param   string  $selectedEstateGuid The guid for the selected estate.
     * 
     * @static
     * @access  public
     */
    public static function setCache(int $selectedEstateId, string $selectedEstateName, string $selectedEstateGuid, string $context = 'm'): void {
        $sessionName = match ($context) {
            'r' => self::ESTATE_CACHE_SESSION_NAME_RESIDENT,
            default => self::ESTATE_CACHE_SESSION_NAME_MANAGER,
        };
        Yii::$app->session->set($sessionName . Yii::$app->user->id, [
            'id' => $selectedEstateId,
            'name' => $selectedEstateName,
            'onespace_site_serial' => $selectedEstateGuid
        ]);
    }
}
