<?php

namespace App\Controllers\Admin\Customer;

use App\Entities\Equipment\ServerEntity;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use RuntimeException;

class ServiceController extends CustomerController
{
  public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
  {
    parent::initController($request, $response, $logger);
    if ($this->service === null) {
      $this->service = service('customer_serviceservice');
    }
    $this->addActionPaths(path: 'service');
    $this->layouts['footerScripts'][] = '<script src="/js/admin/clipboard.js"></script>';
    $this->layouts['footerScripts'][] = '<script src="/js/admin/service.js"></script>';
  }
  //기본 함수 작업
  //Custom 추가 함수
  public function create_form_process(array $formDatas = []): array
  {
    $formDatas = parent::create_form_process($formDatas);
    $formDatas['location'] = 'chiba';
    $formDatas['rack'] = '100000';
    $formDatas['line'] = '300000';
    $formDatas['sale'] = 0;
    $formDatas['billing_at'] = date("Y-m-d");
    $formDatas['start_at'] = date("Y-m-d");
    $formDatas['status'] = STATUS['AVAILABLE'];
    return $formDatas;
  }
  protected function index_process(string $action): void
  {
    //서비스별 미납 Count
    $this->addViewDatas('unPaids', service('paymentservice')->getUnPaids('serviceinfo_uid'));
    parent::index_process($action);
  }

  public function history(int $uid): RedirectResponse|string
  {
    try {
      $action = __FUNCTION__;
      $fields = ['history'];
      $this->service->getFormService()->setFormFields($fields);
      $this->service->getFormService()->setFormRules($action, $fields);
      $this->addViewDatas('entity', $this->service->modify($uid, $this->service->createDTO($this->request->getPost())));
      return $this->action_redirect_process('info', static::class . '->' . __FUNCTION__ . "에서 {$this->getTitle()} 비고설정이 완료되었습니다.");
    } catch (\Throwable $e) {
      return $this->action_redirect_process('error', static::class . '->' . __FUNCTION__ . "에서 {$this->getTitle()} 비고설정 오류:" . $e->getMessage());
    }
  }

  //대체서버 추가
  public function alternative_create_form(int $uid): string|RedirectResponse
  {
    try {
      $action = __FUNCTION__;
      $this->action_init_process($action, $this->request->getVar());
      return $this->action_render_process($action, $this->getViewDatas(), $this->request->getVar('ActionTemplate') ?? 'server');
    } catch (\Throwable $e) {
      return $this->action_redirect_process('error', static::class . '->' . __FUNCTION__ . "에서 {$this->getTitle()} 대체서버 추가폼 오류:" . $e->getMessage());
    }
  }
  public function alternative_create(int $uid): string|RedirectResponse
  {
    try {
      $action = __FUNCTION__;
      $fields = ['serverinfo_uid'];
      $this->service->getFormService()->setFormFields($fields);
      $this->service->getFormService()->setFormRules($action, $fields);
      //서비스정보 가져오기
      $entity = $this->service->getEntity($uid);
      //대체서버 추가
      service('equipment_serverservice')->attachToService($entity, $this->request->getPost('serverinfo_uid'));
      return $this->action_redirect_process('info', static::class . '->' . __FUNCTION__ . "에서 {$this->getTitle()} 대체서버 추가가 완료되었습니다.");
    } catch (\Throwable $e) {
      return $this->action_redirect_process('error', static::class . '->' . __FUNCTION__ . "에서 {$this->getTitle()} 대체서버 추가 오류:" . $e->getMessage());
    }
  }

  //대체서버 -> 메인서버로 바꾼다.
  public function alternative_modify(int $uid): string|RedirectResponse
  {
    try {
      $action = __FUNCTION__;
      $fields = ['serverinfo_uid'];
      $this->service->getFormService()->setFormFields($fields);
      $this->service->getFormService()->setFormRules($action, $fields);
      //변경값 정의
      $formDatas = $this->request->getGet();
      //서버 타이틀을 서비스 타이틀로 변경하기 위함
      $serverEntity = service('equipment_serverservice')->getEntity($formDatas['serverinfo_uid']);
      if (!$serverEntity instanceof ServerEntity) {
        throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: 해당하는 서버정보을 찾을수 없습니다.");
      }
      $formDatas['title'] = $serverEntity->getCustomTitle();
      //대체서버를 메인서버로 설정
      $this->service->modify($uid, $this->service->createDTO($formDatas));
      return $this->action_redirect_process('info', static::class . '->' . __FUNCTION__ . "에서 {$this->getTitle()} 메인서버 설정이 완료되었습니다.");
    } catch (\Throwable $e) {
      return $this->action_redirect_process('error', static::class . '->' . __FUNCTION__ . "에서 {$this->getTitle()} 메인서버 설정 오류:" . $e->getMessage());
    }
  }
  public function alternative_delete(int $uid): string|RedirectResponse
  {
    try {
      $action = __FUNCTION__;
      $fields = ['serverinfo_uid'];
      $this->service->getFormService()->setFormFields($fields);
      $this->service->getFormService()->setFormRules($action, $fields);
      //서비스정보 가져오기
      $entity = $this->service->getEntity($uid);
      //대체서버 해지
      service('equipment_serverservice')->detachFromService($entity, $this->request->getGet('serverinfo_uid'));
      return $this->action_redirect_process('info', static::class . '->' . __FUNCTION__ . "에서 {$this->getTitle()} 대체서버 해지가 완료되었습니다.");
    } catch (\Throwable $e) {
      return $this->action_redirect_process('error', static::class . '->' . __FUNCTION__ . "에서 {$this->getTitle()} 대체서버 해지 오류:" . $e->getMessage());
    }
  }
}
