<?php

namespace Buckhill\LaravelSAML\Http\Controllers;

use AuthStack\SP\AttributeCollection;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use AuthStack\SP\ServiceProvider;
use function AuthStack\SP\authn;
use function AuthStack\SP\metadata;

class SSO extends Controller
{
    /**
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function metadata()
    {
        $metadata = metadata(config('sso'));

        $xml = $metadata->toXml();

        return response($xml, 200, ['Content-Type' => 'application/xml']);
    }

    /**
     * @param Request $request
     */
    public function authn(Request $request)
    {
        $sp = new ServiceProvider(config('sso'), config('sso.SP.IdP'));

        $authn = $sp->authn();

        if($request->has('RelayState'))
        {
            $authn->getAuthN()->setRelayState($request->input('RelayState'));
        }

        $authn->initiate();

        exit;
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function acs(Request $request)
    {
        $collection = authn(config('sso'), config('sso.SP.IdP'), $request)->consume();

        $this->saveToSession($collection);

        $this->afterACS($request, $collection);

        return $this->redirect($request);
    }

    /**
     * @param AttributeCollection $collection
     */
    protected function saveToSession(AttributeCollection $collection)
    {
        session()->put(config('sso.SP.sessionKeyName'), $collection->toArray(true));
    }

    /**
     * @param Request $request
     * @param AttributeCollection $collection
     */
    protected function afterACS(Request $request, AttributeCollection $collection)
    {
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function redirect(Request $request)
    {
        $redirect = $request->input('RelayState', config('sso.SP.redirectAfterSuccess'));

        return redirect($redirect);
    }
}