<?php

namespace App\Models;

use App\Entities\UserSNSEntity;

class UserSNSModel extends CommonModel
{
    protected $table            = 'tw_user_sns';
    // protected $primaryKey       = 'uid';
    // protected $useAutoIncrement = true;
    protected $allowedFields    = ['user_uid', 'site', 'id', 'name', 'email', 'detail', 'status', 'updated_at', 'created_at'];
    protected $validationRules      = [
        'user_uid'          => 'if_exist|number',
        'site'              => 'required|string',
        'id'                => 'required|string',
        'name'              => 'required|string',
        'email'             => 'required|valid_email',
        'detail'            => 'required|string',
        'status'            => 'if_exist|string',
        'updated_at'        => 'if_exist|valid_date',
        'created_at'        => 'if_exist|valid_date',
    ];

    public function getEntityByField($field, $value): ?UserSNSEntity
    {
        $entity = $this->asObject(UserSNSEntity::class)->where($field, $value)->first();
        if (is_null($entity)) {
            throw new \Exception("해당 데이터가 없습니다.\n {$field}->{$value}");
        }
        return $entity;
    }
    public function getEntity($uid): ?UserSNSEntity
    {
        return $this->getEntityByField($this->primaryKey, $uid);
    }
    public function getFieldFormOptions(array $wheres = array(), $temps = array()): array
    {
        foreach ($this->asObject(UserSNSEntity::class)->where($wheres)->findAll() as $entity) {
            $temps[$entity->getPrimaryKey()] = $entity->getTitle();
        }
        return $temps;
    }
    public function create(string $site, array $formDatas): UserSNSEntity
    {
        $entity = new UserSNSEntity();
        $entity->site = $site;
        $entity->id = $formDatas['id'];
        $entity->name = $formDatas['name'];
        $entity->email = $formDatas['email'];
        $entity->detail = json_encode($formDatas);
        $entity->status = 'standby';
        return $this->create_process($entity);
    }
    public function modify(UserSNSEntity $entity, array $formDatas): UserSNSEntity
    {
        foreach ($formDatas as $field => $value) {
            if ($entity->$field != $formDatas[$field]) {
                $entity->$field =  $value;
            }
        }
        return $this->modify_process($entity);
    }

    //Index관련
    public function setIndexWordFilter(string $word)
    {
        parent::setIndexWordFilter($word);
        $this->orLike('name', $word, 'both');
        $this->orLike('email', $word, 'both'); //befor , after , both
    }
    public function setIndexOrderBy($field, $order = 'ASC')
    {
        $this->orderBy("name", "ASC");
        parent::setIndexOrderBy($field, $order);
    }
}
