<?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|regex_match[/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/]',
        '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
    {
        return $this->asObject(UserSNSEntity::class)->where($field, $value)->first();
    }
    public function getEntity(int $uid): ?UserSNSEntity
    {
        return $this->getEntityByField($this->primaryKey, $uid);
    }
    public function create(string $site, array $datas): UserSNSEntity
    {
        $entity = new UserSNSEntity();
        $entity->site = $site;
        $entity->id = $datas['id'];
        $entity->name = $datas['name'];
        $entity->email = $datas['email'];
        $entity->detail = json_encode($datas);
        return $this->create_process($entity);
    }
    public function modify(UserSNSEntity $entity, array $datas): UserSNSEntity
    {
        foreach ($datas as $field => $value) {
            if ($entity->$field != $datas[$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);
    }
}
