<?php

namespace App\Models;

use App\Entities\UserEntity;

class UserModel extends CommonModel
{
    const TABLE = "user";
    const PK = "uid";
    const TITLE = "name";
    protected $table            = self::TABLE;
    protected $primaryKey       = self::PK;
    protected $returnType       = UserEntity::class;
    protected $allowedFields = [
        "uid",
        "id",
        "passwd",
        "name",
        "email",
        "mobile",
        "role",
        "status",
        "updated_at"
    ];
    public function __construct()
    {
        parent::__construct();
    }
    public function getFormRule(string $action, string $field): string
    {
        if (is_array($field)) {
            throw new \Exception(__FUNCTION__ . "=> field가 array 입니다.\n" . var_export($field, true));
        }
        switch ($field) {
            case "id":
                $rule = "required|trim|min_length[4]|max_length[20]";
                $rule .= in_array($action, ["create", "create_form"]) ? "|is_unique[{$this->table}.{$field}]" : "";
                break;
            case "passwd":
                $rule = in_array($action, ["create", "create_form"]) ? "required|trim|string" : "permit_empty|trim|string";
                break;
            case "confirmpassword":
                $rule = in_array($action, ["create", "create_form"]) ? "required|trim|string|matches[passwd]" : "permit_empty|trim|string|matches[passwd]";
                break;
            case "email":
                $rule = "required|trim|valid_email";
                $rule .= in_array($action, ["create", "create_form"]) ? "|is_unique[{$this->table}.{$field}]" : "";
                break;
            case "role":
                $rule  = "required|trim|string";
                break;
            default:
                $rule = parent::getFormRule($action, $field);
                break;
        }
        return $rule;
    }
    protected function convertFormDatas(string $action, string $field, array $formDatas): mixed
    {
        // 필드 값 존재 여부 확인
        $value = array_key_exists($field, $formDatas) ? $formDatas[$field] : null;
        switch ($field) {
            case "passwd":
                $value = password_hash($value, PASSWORD_DEFAULT);
                break;
            case "confirmpassword":
                $value = password_hash($value, PASSWORD_DEFAULT);
                break;
            default:
                $value = parent::convertFormDatas($action, $field, $formDatas);
                break;
        }
        return $value;
    }
}
