<?php

namespace App\Controllers\Admin\Part;

use App\Entities\Part\DISKEntity;
use App\Services\Part\DISKService;
use CodeIgniter\HTTP\RedirectResponse;

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

class DISKController extends PartController
{
    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(): DISKService
    {
        if (!$this->_service) {
            $this->_service = new DISKService();
        }
        return $this->_service;
    }

    public function complete(int $uid): RedirectResponse|string
    {
        //Transaction Start
        $db = \Config\Database::connect();
        $db->transStart();
        try {
            $this->getService()->setAction(__FUNCTION__);
            //기존 Entity 가져오기
            $entity = $this->getService()->getEntity($uid);
            if (!$entity instanceof DISKEntity) {
                throw new \Exception("{$uid}에 대한 정보를 찾을수 없습니다.");
            }
            $formDatas           = [];
            $formDatas['format'] = 0;
            $formDatas['stock'] = $entity->getStock() + $entity->getFormat();
            $this->entity = $this->getService()->modify($entity, $formDatas);
            $db->transCommit();
            return "<script>alert('포맷처리가 완료되었습니다.'); history.back();</script>";
        } catch (\Exception $e) {
            $db->transRollback();
            return $this->getResultFail($e->getMessage());
        }
    }
    //Index,FieldForm관
}
