<?php

namespace idoit\Module\Forms\Model\Validators\Category;

use idoit\Module\Forms\Model\Validators\GenericValidator;
use idoit\Module\Forms\Model\Validators\ValidatorInterface;
use isys_application;
use isys_cmdb_dao_category;
use isys_tenantsettings;

class PersonLoginValidator extends AbstractCategoryValidator implements ValidatorInterface
{
  public const CATEGORY_CONST = 'C__CATS__PERSON_LOGIN';

  /**
   * @param array                  $formData
   * @param isys_cmdb_dao_category $categoryDao
   *
   * @return array|null
   * @throws \Exception
   */
  public function validate(array $formData, isys_cmdb_dao_category $categoryDao): ?array
  {
    $genericValidator = (GenericValidator::factory());
    $language = isys_application::instance()->container->get('language');
    $passwordMinLength = (int)isys_tenantsettings::get('minlength.login.password', 4);
    $issues = [];

    if (isset($formData['user_pass'], $formData['user_pass2']) && $formData['user_pass'] != $formData['user_pass2']) {
      $issues['user_pass'] = $issues['user_pass2'] = $language
        ->get("LC__LOGIN__PASSWORDS_DONT_MATCH");
    }

    if (isset($formData['user_pass']) && mb_strlen($formData['user_pass']) < $passwordMinLength) {
      $issues['user_pass'] = $language
        ->get("LC__LOGIN__SAVE_ERROR", $passwordMinLength);
    }

    if (isset($formData['user_pass2']) && mb_strlen($formData['user_pass2']) < $passwordMinLength) {
      $issues['user_pass2'] = $language
        ->get("LC__LOGIN__SAVE_ERROR", $passwordMinLength);
    }

    unset($formData['user_pass'], $formData['user_pass2']);

    $generalIssues = $genericValidator->validate($formData, $categoryDao);

    if (is_array($generalIssues)) {
      $issues = array_merge($generalIssues, $issues);
    }

    return !empty($issues) ? $issues : null;
  }
}
