<?php

namespace App\Models\Customer;

use App\Entities\Customer\ClientEntity;

class ClientModel extends CustomerModel
{
    const TABLE = "clientinfo";
    const PK = "uid";
    const TITLE = "name";
    protected $table            = self::TABLE;
    // protected $useAutoIncrement = false;
    protected $primaryKey       = self::PK;
    protected $returnType       = ClientEntity::class;
    protected $allowedFields = [
        "uid",
        "user_uid",
        "site",
        "role",
        "name",
        "phone",
        "email",
        "history",
        "account_balance",
        "coupon_balance",
        "point_balance",
        "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 "user_uid":
                $rule = "required|numeric";
                break;
            case "name":
                $rule  = "required|trim|string";
                $rule .= in_array($action, ["create", "create_form"]) ? "|is_unique[{$this->table}.{$field}]" : "";
                break;
            case "site":
            case "role":
                $rule  = "required|trim|string";
                break;
            case "email":
                $rule = "permit_empty|trim|valid_email";
                break;
            case "phone":
            case "history":
                $rule = "permit_empty|trim|string";
                break;
            case "account_balance":
            case "coupon_balance":
            case "point_balance":
                $rule  = "permit_empty|numeric";
                break;
            default:
                $rule = parent::getFormRule($action, $field);
                break;
        }
        return $rule;
    }
    //입력전 코드처리
    final public function create(array $formDatas): ClientEntity
    {
        // 관리자 UID는 현재 인증된 사용자로 설정
        $formDatas['user_uid'] = $this->getMyAuth()->getUIDByAuthInfo();
        return parent::create($formDatas);
    }
}
