<?php

/**
 * Class LdapMigrationService
 */
class LdapMigrationService
{
    private $ci;
    private $url;
    private $cfsettings;

    public function __construct($url)
    {
        $this->url = $url;
        $this->ci = &get_instance();
        $this->ci->load->library('ldap_api');
        $this->ci->load->model('settings_rest_model');
        $this->ci->settings_rest_model->setRestClient($this->getRestClient());
        $this->cfsettings = $this->ci->load->database('cfsettings', true);
    }

    private function getRestClient()
    {
        $config = [
            'base_url' => $this->url,
        ];
        $this->ci->load->library('http_client', $config);
        $this->ci->http_client->setupOauthAuth();
        return $this->ci->http_client;
    }

    /**
     * @return bool
     * @var $url string
     * @throws Exception
     */
    public function migrateLDAPSettings()
    {
        $cfLDAPSettings = [];
        try {
            foreach ($this->cfsettings->query('SELECT * FROM settings')->result() as $item) {
                $cfLDAPSettings[$item->key] = trim($item->value, '"');
            }

            $pestClient = new Http_client(['base_url' => $this->url]);
            $newLdapSettings = $this->ci->ldap_api->getSettings($pestClient);

            if (
                !isset($cfLDAPSettings['ldapEnabled']) ||
                $cfLDAPSettings['ldapEnabled'] !== 'true' ||
                $newLdapSettings['domain_controller'] != ''
            ) {
                return false;
            }

            $result = $this->ci->ldap_api->saveSettings($pestClient, $this->prepareServerSettings($cfLDAPSettings));

            if ($result['success'] == true) {
                echo "Ldap settings successfully migrated. \n";
            }
        } catch (Exception $e) {
            log_message(log_level_for_exception($e), 'Cannot migrate previous LDAP settings: ' . $e->getMessage());
            echo $e->getMessage();
            throw $e;
        }
    }

    /**
     * Map old ldap settings.
     * @param $cfLDAPSettings
     * @return array
     */
    private function prepareServerSettings($cfLDAPSettings)
    {
        $data = [
            'domain_controller' => $cfLDAPSettings['ldapHost'],
            'base_dn' => $cfLDAPSettings['ldapBaseDN'],
            'login_attribute' => $cfLDAPSettings['ldapLoginAttribute'],
            'port' => $cfLDAPSettings['ldapPort'],
            'ldap_filter' => $cfLDAPSettings['ldapFilter'],
            'admin_username' => $cfLDAPSettings['ldapUsername'],
            'admin_password' => $cfLDAPSettings['ldapPassword'],
        ];

        $data['use_ssl'] = $cfLDAPSettings['ldapEncryption'] == 'ssl' ? 'true' : 'false';
        $data['use_tls'] = $cfLDAPSettings['ldapEncryption'] == 'tls' ? 'true' : 'false';

        if ($data['use_ssl'] == 'true' || $data['use_tls'] == 'true') {
            $data['port'] = $cfLDAPSettings['ldapPortSSL'];
        }

        return $data;
    }
}
