<?php

namespace App\Forms\Part;

class CSForm extends PartForm
{
  public function __construct()
  {
    parent::__construct();
  }
  public function action_init_process(string $action, array $formDatas = []): void
  {
    $fields = [
      "type",
      "ip",
      "accountid",
      "domain",
      "price",
    ];
    $filters = [
      "clientinfo_uid",
      'serverinfo_uid',
      'type',
      'status'
    ];
    $indexFilter     = $filters;
    $batchjobFilters = ['status'];
    switch ($action) {
      case 'create':
      case 'create_form':
      case 'modify':
      case 'modify_form':
        $fields = [...$fields, 'status'];
        break;
      case 'view':
        $fields = [
          ...$fields,
          "clientinfo_uid",
          'serverinfo_uid',
          'type',
          'ip',
          'accountid',
          'domain',
          'price',
          'status',
          'created_at'
        ];
        break;
      case 'index':
      case 'download':
        $fields = [
          ...$fields,
          "clientinfo_uid",
          'serverinfo_uid',
          'type',
          'ip',
          'accountid',
          'domain',
          'price',
          'status',
          'created_at'
        ];
        break;
    }
    $this->setFormFields($fields);
    $this->setFormRules($action, $fields);
    $this->setFormFilters($filters);
    $this->setFormOptions($action, $filters, $formDatas);
    $this->setIndexFilters($indexFilter);
    $this->setBatchjobFilters($batchjobFilters);
  }
  public function getFormRule(string $action, string $field, array $formRules): array
  {
    switch ($field) {
      case "type":
        $formRules[$field] = "required|trim|string";
        break;
      case "ip": //ipv4 , ipv6 , both(ipv4,ipv6)
        $formRules[$field] = sprintf("required|trim|valid_ip[both]%s", in_array($action, ["create", "create_form"]) ? "|is_unique[{$this->getAttribute('table')}.{$field}]" : "");
        break;
      case "accountid":
      case "domain":
        $formRules[$field] = "permit_empty|trim|string";
        break;
      case "status":
        $formRules[$field] = "required|trim|string";
        break;
      default:
        $formRules =  parent::getFormRule($action, $field, $formRules);
        break;
    }
    return $formRules;
  }
}
