<?php

namespace App\Models\Customer;

use App\Entities\Customer\ServiceEntity;
use tidy;

class ServiceModel extends CustomerModel
{
    const TABLE = "serviceinfo";
    const PK = "uid";
    const TITLE = "title";
    protected $table            = self::TABLE;
    // protected $useAutoIncrement = false;
    protected $primaryKey       = self::PK;
    protected $returnType       = ServiceEntity::class;
    protected $allowedFields = [
        "uid",
        "user_uid",
        "clientinfo_uid",
        "serverinfo_uid",
        "payment_uid",
        "code",
        "title",
        "site",
        "location",
        "rack",
        "line",
        "billing_at",
        "sale",
        "amount",
        "start_at",
        "end_at",
        "history",
        "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":
            case "clientinfo_uid":
            case "serverinfo_uid":
            case "amount":
            case "rack":
            case "line":
                $rule  = "required|numeric";
                break;
            case "sale":
            case "payment_uid":
                $rule = "permit_empty|numeric";
                break;
            case "site":
            case "location":
            case "status":
                $rule = "required|trim|string";
                break;
            case "billing_at":
            case "start_at":
                $rule = "required|valid_date";
                break;
            case "end_at":
                $rule = "permit_empty|valid_date";
                break;
            case 'title':
            case "history":
                $rule = "permit_empty|trim|string";
                break;
            default:
                $rule = parent::getFormRule($action, $field);
                break;
        }
        return $rule;
    }
    //입력전 코드처리
    final public function create(array $formDatas): ServiceEntity
    {
        $formDatas['code'] = $formDatas['site'] . "_s" . uniqid();
        // 관리자 UID는 현재 인증된 사용자로 설정
        $formDatas['user_uid'] = $this->getMyAuth()->getUIDByAuthInfo();
        return parent::create($formDatas);
    }
}
