<?php

namespace App\Controllers\CLI;

use App\Controllers\BaseController;
use App\Entities\Customer\ServiceEntity;
use App\Services\Customer\ServiceService;
use App\Services\PaymentService;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

class Payment extends BaseController
{
    private ?PaymentService $_paymentService = null;
    private ?ServiceService $_service = null;
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
    }
    public function getService(): ServiceService
    {
        if (!$this->_service) {
            $this->_service = new ServiceService();
        }
        return $this->_service;
    }
    public function getPaymentService(): PaymentService
    {
        if (!$this->_paymentService) {
            $this->_paymentService = new PaymentService();
        }
        return $this->_paymentService;
    }
    public function billing(): void
    {
        //Transaction Start
        $db = \Config\Database::connect();
        $db->transStart();
        try {
            log_message("notice", "Billing 작업을 시작.");
            //결제일이 오늘보다 크고, 상태가 사용중인 서비스정보를 이용해서 결제정보에 신규 추가하기
            foreach ($this->getService()->getEntities(['billing_at' => date("Y-m-d"), 'status' => STATUS['AVAILABLE']]) as $entity) {
                // echo $serviceEntity->getPK() . ":" . $serviceEntity->getBillingAt() . "\n";
                $entity = $this->getPaymentService()->setService('create', $entity, []);
                $entity = $this->getService()->modify(
                    $entity,
                    [
                        'billing_at' => $this->getService()->getNextMonthDate($entity),
                        'paymentifo_uid' => $entity->getPaymentUID(),
                        'serverinfo_uid' => $entity->getServerInfoUID()
                    ]
                );
                log_message("notice", sprintf("%s/%s원 결제추가\n", $entity->getCustomTitle(), $entity->getAmount()));
            }
            // echo $this->getService()->getModel()->getLastQuery() . "\n";
            log_message("notice", "Billing 작업을 완료.");
            $db->transCommit();
        } catch (\Exception $e) {
            //Transaction Rollback
            $db->transRollback();
            log_message(
                "error",
                "Billing 작업을 실패하였습니다.\n--------------\n" .
                    $e->getMessage() .
                    "\n--------------\n"
            );
        }
    }
}
