<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class Settings_rest_model extends Cf_Model
{
    public $errors;

    public const PASSWORD_COMPLEXITY = 'passwordComplexity';
    public const MIN_PASSWORD_LENGTH = 'minPasswordLength';
    public const PASSWORD_EXPIRATION_AFTER_RESET_HOURS = 'passwordExpirationAfterResetHours';

    public const DEFAULT_FIELDS = [
        'appemail' => null,
        'rbac' => null,
        'ldapEnabled' => null,
        'ldapHost' => null,
        'blueHostHorizon' => null,
        'logLevel' => null,
        'ldapFilter' => null,
        'ldap_roles_list_to_sync' => [],
        self::MIN_PASSWORD_LENGTH => 8,
        self::PASSWORD_COMPLEXITY => 3,
        self::PASSWORD_EXPIRATION_AFTER_RESET_HOURS => 48,
    ];

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Gets app settings through rest interface
     *
     * @return array
     * @throws Exception
     */
    public function get_app_settings()
    {
        try {
            $settings = $this->rest->get('/settings');
            $data = $this->checkData($settings);
            if (is_array($data) && $this->hasErrors() == 0) {
                $dataMergedWithDefault = array_merge(self::DEFAULT_FIELDS, $data['data'][0]);
                //ldap_roles_list_to_sync stores as JSON, decode it back to array
                if (
                    !empty($dataMergedWithDefault['ldap_roles_list_to_sync']) &&
                    is_string($dataMergedWithDefault['ldap_roles_list_to_sync'])
                ) {
                    $dataMergedWithDefault['ldap_roles_list_to_sync'] =
                        json_decode(json: $dataMergedWithDefault['ldap_roles_list_to_sync'], associative: true) ?? [];
                }
                return $dataMergedWithDefault;
            } else {
                throw new Exception($this->getErrorsString());
            }
        } catch (HttpClient_UnknownResponse $e) {
            log_message('error', $e->getMessage() . ' ' . $e->getFile() . ' line:' . $e->getLine());
            throw new Exception('Cannot find the rest server.');
        } catch (Exception $e) {
            log_message(log_level_for_exception($e), $e->getMessage() . ' ' . $e->getFile() . ' line:' . $e->getLine());
            throw $e;
        }
    }

    public function updateData($data)
    {
        if (is_array($data) && !empty($data)) {
            try {
                // get current settings
                $settings = $this->rest->get('/settings');
                $settings = $this->checkData($settings);
                if (is_array($settings) && !empty($settings)) {
                    // merge new settings with current (case of host identifier, for example)
                    $settings = array_merge($settings['data'][0], $data);
                    try {
                        log_message('debug', 'model->_updateData(): Trying to update data via REST ');
                        $this->rest->patch('/settings', $settings);
                    } catch (Exception $e) {
                        log_message('error', $e->getMessage() . ' ' . $e->getFile() . ' line:' . $e->getLine());
                        throw $e;
                    }
                } else {
                    throw new Exception($this->getErrorsString());
                }
            } catch (HttpClient_InvalidRecord $e) {
                return json_decode($e->getMessage(), associative: true);
            } catch (Exception $e) {
                log_message(
                    log_level_for_exception($e),
                    $e->getMessage() . ' ' . $e->getFile() . ' line:' . $e->getLine(),
                );
                throw $e;
            }
            return ['success' => true];
        }
    }

    public function app_settings_get_item($item)
    {
        $settings = $this->get_app_settings();
        return $settings[$item];
    }
}
