<?php

namespace Controllers;

use models\LdapUserAdapter;
use Services\Ldap\Implementations\Ldap;
use Slim\Http\Request;

class AuthController extends BaseController
{
    public function login(Request $request, $response)
    {
        $authData = $request->getParsedBody();
        if (!key_exists('username', $authData)) {
            throw new \InvalidArgumentException('Username is required.');
        }

        if (!key_exists('password', $authData)) {
            throw new \InvalidArgumentException('Password is required.');
        }
        $config = $this->container->get('ldap');
        $ldap = new Ldap($config);

        if ($ldap->authAttempt($authData['username'], $authData['password'])) {
            /**
             * @var $ldapUser User
             */
            $user = new LdapUserAdapter($config);
            $user->setLdapUser($ldap->getUser($authData['username']));

            return $response->withJson([
                'success' => true,
                'data' => $user->toArray(),
                'message' => 'You are successfully authenticated',
            ]);
        } else {
            return $response->withStatus(401)->withJson([
                'success' => false,
                'message' => 'Incorrect username or password.',
            ]);
        }
    }
}
