<?php

namespace App\Services;

use App\Models\UserModel;
use App\Helpers\UserHelper;
use App\Forms\UserForm;
use App\Entities\UserEntity;


class UserService extends CommonService
{
    protected string $formClass = UserForm::class;
    protected string $helperClass = UserHelper::class;

    public function __construct(UserModel $model)
    {
        parent::__construct($model);
        $this->addClassPaths('User');
    }
    public function getEntityClass(): string
    {
        return UserEntity::class;
    }
    //기본 기능부분
    protected function getEntity_process(mixed $entity): UserEntity
    {
        return $entity;
    }
    protected function actionForm_fieldhook_process(string $field, $value, array $formDatas): array
    {
        switch ($field) {
            case 'role':
                if (is_string($value)) {
                    $formDatas['role'] = explode(',', $value) ?? [];
                }
                break;
            default:
                $formDatas = parent::actionForm_fieldhook_process($field, $value, $formDatas);
                break;
        }
        return $formDatas;
    }

    protected function save_before_fill(array $formDatas): array
    {
        // 1) DB 컬럼 아닌 값 제거
        unset($formDatas['confirmpassword']);

        // 2) role은 무조건 문자열로
        if (array_key_exists('role', $formDatas)) {
            $arr = is_array($formDatas['role'])
                ? $formDatas['role']
                : explode(',', (string) $formDatas['role']);

            $arr = array_values(array_filter(array_map('trim', $arr)));
            sort($arr);
            $formDatas['role'] = implode(',', $arr);
        }

        // 3) passwd는 빈 값이면 업데이트 제외 (원하면)
        if (array_key_exists('passwd', $formDatas) && $formDatas['passwd'] === '') {
            unset($formDatas['passwd']);
        }

        return $formDatas;
    }
    //List 검색용
    //FormFilter 조건절 처리
    public function setFilter(string $field, mixed $filter_value): void
    {
        switch ($field) {
            case 'role':
                //FIND_IN_SET()은 MySQL 함수이므로 CodeIgniter가 이를 일반 컬럼명으로 착각하고 escape하게 되면 오류가 발생
                // 따라서 ->where($sql, null, false)로 명시하여 escape를 꺼줘야 정상 작동
                $where = "FIND_IN_SET(" . $this->model->escape($filter_value) . ", {$this->model->getTable()}.{$field}) > 0";
                $this->model->where($where, null, false);
                break;
            default:
                parent::setFilter($field, $filter_value);
                break;
        }
    }
    //검색어조건절처리
    public function setSearchWord(string $word): void
    {
        $this->model->orLike($this->model->getTable() . '.id', $word, 'both');
        $this->model->orLike($this->model->getTable() . '.email', $word, 'both');
        parent::setSearchWord($word);
    }
}
