<?php

namespace App\Controllers\Mangboard\Admin;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

use App\Controllers\CommonController;
use App\Models\Mangboard\UserModel;

class UserController extends CommonController
{
    private $_model = null;
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
    }

    private function getModel(): UserModel
    {
        if ($this->_model === null) {
            $this->_model = new UserModel();
        }
        return $this->_model;
    }

    public function point(string $id, string $point, string $sign = "+"): string
    {
        try {
            $entity = is_numeric($id) ? $this->getModel()->getEntityByPK(intval($id)) : $this->getModel()->getEntityByID($id);
            if (!$entity) {
                throw new \Exception("해당 {$id}의 회원이 없습니다.");
            }
            $this->getModel()->setPoint($entity, intval($point), $sign);
            return __FUNCTION__ . " 작업이 완료되었습니다.";
        } catch (\Exception $e) {
            log_message("error",  $e->getMessage());
            return $e->getMessage();
        }
    }
    public function level(string $id, string $level): string
    {
        try {
            $entity = is_numeric($id) ? $this->getModel()->getEntityByPK(intval($id)) : $this->getModel()->getEntityByID($id);
            if (!$entity) {
                throw new \Exception("해당 {$id}의 회원이 없습니다.");
            }
            $this->getModel()->setLevel($entity, intval($level));
            log_message("notice", "Mangboard->level 작업이 완료되었습니다.");
            return __FUNCTION__ . " 작업이 완료되었습니다.";
        } catch (\Exception $e) {
            log_message("error",  $e->getMessage());
            return $e->getMessage();
        }
    }

    public function check_level($id = false): string
    {
        try {
            if (!$id) {
                foreach ($this->getModel()->getEntitys() as $entity) {
                    $level = $this->getModel->checkLevel($entity);
                    $this->getModel()->setLevel($entity, intval($level));
                }
            } else {
                $entity = is_numeric($id) ? $this->getModel()->getEntityByPK(intval($id)) : $this->getModel()->getEntityByID($id);
                if (!$entity) {
                    throw new \Exception("해당 {$id}의 회원이 없습니다.");
                }
                $level = $this->getModel->checkLevel($entity);
                $this->getModel()->setLevel($entity, intval($level));
            }
            return __FUNCTION__ . " 작업이 완료되었습니다.";
        } catch (\Exception $e) {
            log_message("error",  $e->getMessage());
            return $e->getMessage();
        }
    }
}
