<?php

require_once __DIR__ . '/../lib/CfSettings.php';

/**
 * Class CFAuthService
 */
class CFAuthService
{
    public const SETTING_LDAP_ENABLED = 'ldapEnabled';

    private $pestClient;
    private $cfSettingsService;

    public function __construct()
    {
        $this->cfSettingsService = CfSettings::getInstance();
        // todo: fix it later(needed for removing quotes, db column format is json, which doesn't allow save without quotes)
        $ldapApiUrl = LDAP_API_URL;
        $this->pestClient = new Pest($ldapApiUrl);
    }

    public function auth($userName, $password)
    {
        $user = new CfUsers($userName);
        return ($this->cfSettingsService->getSetting(self::SETTING_LDAP_ENABLED) === 'true' && (!$user->getUser() || $user->isExternal()))
            ? $this->ldapAuth($userName, $password)
            : $this->cfApiAuth($userName, $password);
    }
    /**
     * @param string $userName
     * @param string $password
     * @return boolean
     */
    public static function checkPasswordValid(string $userName, string $password)
    {
        return cfapi_auth($userName, $password) != false;
    }
    /**
     * @param $userName
     * @param $password
     * @return mixed
     */
    private function ldapAuth($userName, $password)
    {
        $isSuccess = false;
        try {
            $response = $this->pestClient->post('/login', [
                'username' => $userName,
                'password' => $password
            ]);

            $responseArray = json_decode($response);

            if ($responseArray->success) {
                $data = $responseArray->data;

                $roles = [];
                //Get default role is role from ldap server is empty.
                if (!$data->roles) {
                    $roleModel = new CfRole();
                    $defaultRole = $roleModel->getDefaultRole();
                    $roles = $defaultRole ? [$defaultRole['name']] : [];
                }

                $user = new CfUsers($data->id, $data->email, $roles);
                $isFirstLogin = !$user->checkUserExistingAndCreateIfNot();
                $user->syncLdapRoles($this->cfSettingsService->getSettings(), $data->roles, $isFirstLogin);
                $isSuccess = true;
            }
        } catch (Exception $e) {
            syslog(LOG_DEBUG, 'Can\'t auth . Error:' . $e->getMessage() . ' ' . $e->getFile() . ' line:' . $e->getLine());
            return null;
        }

        return $isSuccess ? $user->getUserName() : null;
    }

    /**
     * @param string $userName
     * @param string $password
     * @return mixed
     */
    private function cfApiAuth(string $userName, string $password)
    {
        return cfapi_auth($userName, $password);
    }
}
