<?php

namespace App\Forms;

use App\Forms\CommonForm;

class UserForm extends CommonForm
{
  public function __construct()
  {
    parent::__construct();
  }
  public function action_init_process(string $action, array &$formDatas = []): void
  {
    parent::action_init_process($action, $formDatas);
    $fields = [
      'id',
      'passwd',
      'confirmpassword',
      'name',
      'email',
      'mobile',
      'role',
      'status'
    ];
    $filters = ['role', 'status'];
    $indexFilter = $filters;
    $batchjobFilters = ['status'];
    switch ($action) {
      case 'view':
        $fields = ['id', 'name', 'email', 'mobile', 'role', 'status', 'created_at'];
        break;
      case 'index':
      case 'download':
        $fields = ['id', 'name', 'email', 'mobile', 'role', 'status', 'created_at'];
        break;
    }
    $this->setFormFields($fields);
    $this->setFormRules($fields);
    $this->setFormFilters($filters);
    $this->setFormOptions($filters, $formDatas);
    $this->setIndexFilters($indexFilter);
    $this->setBatchjobFilters($batchjobFilters);
  }
  public function getFormRule(string $field, array $formRules): array
  {
    switch ($field) {
      case "id":
        $formRules[$field] = sprintf("required|trim|min_length[4]|max_length[20]%s", in_array($this->_action, ["create", "create_form"]) ? "|is_unique[{$this->getAttribute('table')}.{$field}]" : "");
        break;
      case "passwd":
        $formRules[$field] = sprintf("%s|%s", in_array($this->_action, ["create", "create_form"]) ? "required" : "permit_empty", "trim|string");
        break;
      case "confirmpassword":
        $formRules[$field] = sprintf("%s|%s", in_array($this->_action, ["create", "create_form"]) ? "required" : "permit_empty", "trim|string|matches[passwd]");
        break;
      case "email":
        $formRules[$field] = sprintf("required|trim|valid_email%s", in_array($this->_action, ["create", "create_form"]) ? "|is_unique[{$this->getAttribute('table')}.{$field}]" : "");
        break;
      case "role":
        // $formRules[$field] = 'required|trim|string';
        $formRules[$field] = 'required|is_array|at_least_one';
        $formRules['role.*'] = 'permit_empty|trim|in_list[manager,cloudflare,firewall,security,director,master]';
        break;
      default:
        $formRules = parent::getFormRule($field, $formRules);
        break;
    }
    return $formRules;
  }
}
