<?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->_viewPath .= strtolower($this->_model->getClassName());
    }

    //Field별 Form Datas 처리용
    protected function getFieldFormData(string $field, $entity = null): array
    {
        switch ($field) {
            case 'passwd':
                $passwd = $this->request->getVar($field) ?: false;
                $confirmpassword = $this->request->getVar('confirmpassword') ?: false;
                if ($passwd && $confirmpassword) {
                    $this->_viewDatas['fieldDatas'][$field] = $passwd;
                    $this->_viewDatas['fieldDatas']['confirmpassword'] = $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':
                    //checkbox형태로 들어오면 $fieldDatas['role']가 array이기때문에
                    $rules[$field . '.*'] = $rule;
                    break;
                default:
                    $rules[$field] = $rule;
                    break;
            }
        }
        parent::insert_validate();
    }
}
