<?php

namespace App\Controllers\Admin;

use App\Models\UserModel;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

class UserController extends AdminController
{
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        $this->_model = new UserModel();
        parent::initController($request, $response, $logger);
        $this->_viewDatas['title'] = lang($this->_model->getClassName() . '.title');
        $this->_viewPath .= strtolower($this->_model->getClassName());
        helper($this->_model->getClassName());
    }

    //Field별 Form Datas 처리용
    protected function getFieldFormData(string $field, $entity = null): array
    {
        switch ($field) {
            case 'passwd':
                $this->_viewDatas['fieldDatas'][$field] = $this->request->getVar($field);
                $this->_viewDatas['fieldDatas']['confirmpassword'] = $this->request->getVar('confirmpassword');
                break;
            default:
                return parent::getFieldFormData($field, $entity);
                break;
        }
        return $this->_viewDatas['fieldDatas'];
    }

    public function getFields(string $action = ""): array
    {
        $fields = ["id", "passwd", 'name', "email", "role", "status"];
        switch ($action) {
            case "index":
            case "excel":
                return ["id", 'name', "email", "role", "status", 'created_at'];
                break;
            case "view":
                return ["id", 'name', "email", "role", "status", 'updated_at', 'created_at'];
                break;
            default:
                return $fields;
                break;
        }
    }
    public function getFieldFilters(): array
    {
        return ["role", "status"];
    }
    public function getFieldBatchFilters(): array
    {
        return parent::getFieldBatchFilters();
    }

    protected function insert_validate()
    {
        $rules = [];
        foreach ($this->_viewDatas['fieldRules'] as $field => $rule) {
            switch ($field) {
                case 'role':
                    $rules[$field . '.*'] = $rule;
                    break;
                default:
                    $rules[$field] = $rule;
                    break;
            }
        }
        //fieldData Rule 검사
        if (!$this->validate($rules)) {
            throw new \Exception("{$this->_viewDatas['title']}의 검증 오류발생\n" . implode("\n", $this->validator->getErrors()));
        }
        //fieldData 적용
        $this->_viewDatas['fieldDatas'] = array();
        foreach ($this->_viewDatas['fields'] as $field) {
            $this->_viewDatas['fieldDatas'] = $this->getFieldFormData($field);
        }
    }
}
