<?php

namespace App\Controllers\Admin\Customer;

use App\Entities\Customer\ClientEntity;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use RuntimeException;

class ClientController extends CustomerController
{
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        if ($this->service === null) {
            $this->service = service('customer_clientservice');
        }
        $this->addActionPaths('client');
    }
    //기본 함수 작업
    //Custom 추가 함수
    //고객 상세정보
    public function detail(mixed $uid): string|RedirectResponse
    {
        try {
            $action = __FUNCTION__;
            $this->action_init_process($action);
            //Return Url정의
            $this->getAuthContext()->pushCurrentUrl($this->request->getUri()->getPath() . ($this->request->getUri()->getQuery() ? "?" . $this->request->getUri()->getQuery() : ""));
            //일괄작업용 Fields정의
            $entity = $this->service->getEntity($uid);
            if (!$entity instanceof ClientEntity) {
                throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 {$uid}에 해당하는 고객정보를 찾을수 없습니다.");
            }
            $this->addViewDatas('totalCounts', service('equipment_serverservice')->getTotalServiceCount(['serviceinfo.clientinfo_uid' => $entity->getPK()]));
            $this->addViewDatas('totalAmounts', service('customer_serviceservice')->getTotalAmounts([
                'clientinfo_uid' => $entity->getPK(),
                'status' => STATUS['AVAILABLE']
            ]));
            //서비스별 미납 Count
            $this->addViewDatas('unPaids', service('paymentservice')->getUnPaids('clientinfo_uid', [
                'clientinfo_uid' => $entity->getPK()
            ]));
            $this->addViewDatas('serviceEntities', service('customer_serviceservice')->getEntities(['clientinfo_uid' => $entity->getPK()]));
            $this->addViewDatas('entity', $entity);
            helper(['form']);
            return $this->action_render_process($action, $this->getViewDatas(), $this->request->getVar('ActionTemplate') ?? 'client');
        } catch (\Throwable $e) {
            return $this->action_redirect_process('error', static::class . '->' . __FUNCTION__ . "에서 {$this->getTitle()} 고객 Detail Page 오류:" . $e->getMessage());
        }
    }

    //비고사항 변경
    public function history(int $uid): RedirectResponse|string
    {
        try {
            $history = $this->request->getPost('history');
            if (!$history) {
                throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: 비고가 정의되지 않았습니다.");
            }
            $entity = $this->service->history($uid, $history);
            $this->addViewDatas('entity', $entity);
            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());
        }
    }
}
