<?php

namespace App\Controllers\Admin\Equipment;

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

class ServerController extends EquipmentController
{
  public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
  {
    parent::initController($request, $response, $logger);
    if ($this->service === null) {
      $this->service = service('equipment_serverservice');
    }
    $this->addActionPaths('server');
    $this->layouts['footerScripts'][] = '<script src="/js/admin/clipboard.js"></script>';
  }
  //기본 함수 작업
  //Custom 추가 함수
  public function create_form_process(array $formDatas = []): array
  {
    $formDatas = parent::create_form_process($formDatas);
    $formDatas['code'] = sprintf("%d%dXX-M%d", date("y"), ceil((int) date("m") / 3), $this->service->getNextPK());
    return $formDatas;
  }

  protected function modify_form_result_process(string $action): string|RedirectResponse
  {
    return $this->action_render_process($action, $this->getViewDatas(), $this->request->getVar('ActionTemplate') ?? 'server');
  }

  protected function console_result_process(string $action): string
  {
    return $this->action_render_process($action, $this->getViewDatas(), $this->request->getVar('ActionTemplate') ?? 'server');
  }
  public function console(int $uid): string|RedirectResponse
  {
    try {
      if (!$uid) {
        throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 {$this->getTitle()}에 번호가 정의 되지 않았습니다.");
      }
      //View처리
      $entity = $this->view_process($uid);
      $action = __FUNCTION__;
      //FormService에서 필요한 기존 데이터를 $entity에서 추출해서 넘김
      $this->action_init_process($action, $entity->toArray());
      $this->addViewDatas('entity', $entity);
      return $this->console_result_process($action);
    } catch (\Throwable $e) {
      return $this->action_redirect_process('error', static::class . '->' . __FUNCTION__ . "에서 {$this->getTitle()} 상세보기 오류:" . $e->getMessage());
    }
  }
}
