<?php

namespace App\Controllers\Admin\Equipment;

use Psr\Log\LoggerInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\RedirectResponse;
use App\Services\Equipment\ServerPartService;

class ServerPartController extends EquipmentController
{
  public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
  {
    parent::initController($request, $response, $logger);
    $this->content_title = lang("{$this->getService()->getClassName()}.title");
    $this->class_path .= $this->getService()->getClassName();
    $this->uri_path .= strtolower($this->getService()->getClassName('/')) . '/';
    // $this->view_path .= strtolower($this->getService()->getClassName()) . DIRECTORY_SEPARATOR;
  }
  public function getService(): ServerPartService
  {
    if (!$this->_service) {
      $this->_service = new ServerPartService();
    }
    return $this->_service;
  }
  //Index,FieldForm관련
  protected function getResultSuccess(string $message = MESSAGES["SUCCESS"], ?string $actionTemplate = null): RedirectResponse|string
  {
    switch ($this->getService()->getAction()) {
      case 'create_form':
      case 'modify_form':
        $this->service = $this->getService();
        $this->control = $this->getService()->getControlDatas();
        $this->getService()->getHelper()->setViewDatas($this->getViewDatas());
        $actionTemplate = $this->request->getVar('ActionTemplate') ?? $actionTemplate ?? 'serverpart';
        if ($actionTemplate) {
          $view_file = $this->view_path . $actionTemplate . DIRECTORY_SEPARATOR . $this->getService()->getAction();
        } else {
          $view_file = $this->view_path . $this->getService()->getAction();
        }
        $result = view($view_file, ['viewDatas' => $this->getViewDatas()]);
        break;
      case 'history':
        $result = redirect()->to($this->request->getGET('return_url'))->with('error', $message);
        break;
      default:
        $result = parent::getResultSuccess($message, $actionTemplate);
        break;
    }
    return $result;
  }

  //생성관련
  protected function create_form_process(): void
  {
    //Form 기본값정의
    $formDatas = $this->getService()->getFormDatas();
    $formDatas['billing'] = 'base';
    $formDatas['cnt'] = 1;
    $this->getService()->setFormDatas($formDatas);
    parent::create_form_process();
  }

  //팝업상태에서 삭제처리용
  public function delete(mixed $uid): RedirectResponse|string
  {
    //Transaction Start
    $db = \Config\Database::connect();
    $db->transStart();
    try {
      $this->getService()->setAction(__FUNCTION__);
      //기존 Entity 가져오기
      $entity = $this->getService()->getEntity($uid);
      if (!$entity) {
        throw new \Exception("{$uid}에 대한 정보를 찾을수 없습니다.");
      }
      $this->delete_process($entity);
      $db->transCommit();
      return "<script>alert('{$entity->getTitle()} 항목이 삭제되었습니다.');history.back();</script>";
    } catch (\Exception $e) {
      $db->transRollback();
      return $this->getResultFail($e->getMessage());
    }
  }
}
