<?php

namespace Buckhill\LaravelSAML\Services;

use Buckhill\Support\Traits\DotNotationAccessorTrait;

class AuthenticatedUser
{
    use DotNotationAccessorTrait;

    protected $model = [];
    protected $authenticated = false;
    protected $is_buckhill;

    /**
     * @return AuthenticatedUser
     */
    public static function fromSession()
    {
        return new static(session(config('sso.SP.sessionKeyName'), []));
    }

    /**
     * @param array|null $data
     * @return $this
     */
    public function saveToSession(array $data = null)
    {
        if(!empty($data))
        {
            $this->model = array_merge($this->model, $data);
        }

        session()->put(config('sso.SP.sessionKeyName'), $this->model);

        return $this;
    }

    /**
     * AuthenticatedUser constructor.
     * @param array|null $model
     */
    public function __construct(array $model = null)
    {
        $this->model = $model;
        $this->authenticated = sizeof($model) !== 0;
    }

    /**
     * @return string
     */
    public function getId()
    {
        return $this->dotNotationFromModel('id');
    }

    /**
     * @return int
     */
    public function getOrganizationId()
    {
        return $this->dotNotationFromModel('organization.id');
    }

    /**
     * @return int
     */
    public function getAccountId()
    {
        if($this->hasOrganization())
        {
            return $this->getOrganizationId();
        }

        return $this->getId();
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->dotNotationFromModel('account_name');
    }

    /**
     * @return string
     */
    public function getUsername()
    {
        return $this->dotNotationFromModel('username');
    }

    /**
     * @return bool
     */
    public function hasOrganization()
    {
        $organization = $this->dotNotationFromModel('organization');

        return !empty($organization);
    }

    /**
     * @return bool
     */
    public function isConfirmed()
    {
        return $this->dotNotationFromModel('confirmed', false);
    }

    /**
     * @return bool
     */
    public function isManager()
    {
        return $this->hasOrganization() && $this->dotNotationFromModel('manager', false);
    }

    /**
     * @return bool
     */
    public function isAuthenticated()
    {
        return $this->authenticated;
    }

    /**
     * @param $path
     * @param null $default
     * @return null
     */
    public function get($path, $default = null)
    {
        return $this->dotNotationFromModel($path, $default);
    }
}