<?php

namespace App\Models\Cloudflare;

use App\Models\CommonModel;
use App\Entities\Cloudflare\AuthEntity;
use App\Entities\Cloudflare\AccountEntity;

class AccountModel extends CommonModel
{
    const TABLE = "cloudflareaccount";
    const PK    = "uid";
    const TITLE = "title";
    const PARENT = "auth_uid";
    protected $table = self::TABLE;
    protected $primaryKey = self::PK;
    protected $useAutoIncrement = false;
    protected $returnType = AccountEntity::class; //object,array,entity명::class
    protected $allowedFields = [self::PK, self::PARENT, self::TITLE, 'type', 'status', 'updated_at', 'created_at'];
    protected $useTimestamps = true;
    public function __construct()
    {
        parent::__construct();
    }
    public function getTitleField(): string
    {
        return self::TITLE;
    }
    public function getFieldRule(string $action, string $field): string
    {
        switch ($field) {
            case self::PK:
                $rule = "required|trim|alpha_numeric";
                $rule .= $action == "create" ? "|is_unique[{$this->table}.{$field}]" : "";
                break;
            case self::PARENT:
                $rule = "required|numeric";
                break;
            case self::TITLE:
                $rule = "required|trim|string";
                break;
            case "type":
                $rule = "if_exist|in_list[standard,enterprise]";
                break;
            default:
                $rule = parent::getFieldRule($action, $field);
                break;
        }
        return $rule;
    }
    public function getFormFieldOption(string $field, array $options = []): array
    {
        switch ($field) {
            default:
                $this->orderBy(self::TITLE, 'asc');
                $options = parent::getFormFieldOption($field, $options);
                break;
        }
        return $options;
    }
    public function getEntityByPK(string $uid): null|AccountEntity
    {
        $this->where($this->getPKField(), $uid);
        return $this->getEntity();
    }
    public function getEntityByID(string $id): null|AccountEntity
    {
        $this->where(self::TITLE, $id);
        return $this->getEntity();
    }
    public function getEntitysByParent(AuthEntity $auth_entity)
    {
        $this->where(self::PARENT, $auth_entity->getPK());
        return $this->getEntitys();
    }
    //create용
    public function create(array $formDatas = []): AccountEntity
    {
        return $this->create_process(new AccountEntity(), $formDatas);
    }
    //modify용
    public function modify(AccountEntity $entity, array $formDatas): AccountEntity
    {
        return $this->modify_process($entity, $formDatas);
    }
}
