<?php

use api\classes\API_mailsettings;
use api\classes\API_portalsettings;

session_start();
require_once "{$_SERVER['DOCUMENT_ROOT']}/api/classes/API_mailsettings.php";
require_once "{$_SERVER['DOCUMENT_ROOT']}/api/classes/API_portalsettings.php";

$API_mailsettings = new API_mailsettings();

if ($API_mailsettings->request_method === 'PUT') {
    # Edit the mailsettings of the platform

    $API_mailsettings->checkPermissions('admin-mailsettings', 'RW');

    $requiredFields = [
        'portal_uuid' => ['type' => 'uuid'],
        'mail_from_name' => ['type' => 'string'],
        'mail_from_address' => ['type' => 'email'],
        'mail_smtp_host' => ['type' => 'string'],
        'mail_smtp_secure' => ['type' => 'enum', 'values' => ['tls', 'ssl', 'no']],
        'mail_smtp_port' => ['type' => 'int', 'min' => 4, 'max' => 65535],
        'mail_smtp_auth' => ['type' => 'boolean'],
        'mail_smtp_user' => ['type' => 'string'],
        'mail_smtp_pass' => ['type' => 'string']
    ];
    # check if the password is changed
    $updatePassword = !str_contains($API_mailsettings->postedData['mail_smtp_pass'], '******');
    if ($updatePassword) {
        if (strlen($API_mailsettings->postedData['mail_smtp_pass']) < 12) {
            $API_mailsettings->apiOutput(400, ['error' => 'Password too short']);
        }

        if (preg_match('/^(.)\1{5,}$/', $API_mailsettings->postedData['mail_smtp_pass'])) {
            $API_mailsettings->apiOutput(400, ['error' => 'Password insecure']);
        }
    }

    $API_portalsettings = new  API_portalsettings();
    if (count($API_portalsettings->getPortalSettings()) !== 1) {
        $API_mailsettings->apiOutput(400, ['error' => 'Invalid portal_uuid']);
    }

    $API_mailsettings->validateData($requiredFields);

    # Update the permission
    $API_mailsettings->updateMailSettings($updatePassword);

}