<?php

namespace App\Controllers\CLI;

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

class Payment extends BaseController
{
    private $_db;
    private ?ServiceService $_serviceService = null;
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->_db = \Config\Database::connect();
    }
    public function getServiceService(): ServiceService
    {
        if (!$this->_serviceService) {
            $this->_serviceService = new ServiceService();
        }
        return $this->_serviceService;
    }
    public function billing(): void
    {
        //Transaction Start
        $this->_db->transStart();
        try {
            //서비스중 결제일이 오늘이고, 상태가 사용중이 경우만 서비스 모두 연장처리
            $this->getServiceService()->extendBillingAt(date('Y-m-d'), PaymentEntity::STATUS_UNPAID);
            //결제일이 오늘보다 크고, 상태가 사용중인 서비스정보를 이용해서 결제정보에 신규 추가하기
            foreach ($this->getServiceService()->getEntities(['billing_at' => date("Y-m-d"), 'status' => ServiceEntity::STATUS_NORMAL]) as $serviceEntity) {
                // echo $serviceEntity->getPK() . ":" . $serviceEntity->getBillingAt() . "\n";
                foreach ($this->getServiceItemService()->getEntities(['serviceinfo_uid' => $serviceEntity->getPK()]) as $itemEntity) {
                    //결제정보 ServicePaymentService에 월별 결제만 신규등록
                    if ($itemEntity->getBillingCycle() == "month") {
                        //결제정보 ServicePaymentService에 등록
                        $paymentFormDatas = ['status' => PaymentEntity::STATUS_UNPAID];
                        $this->getServicePaymentService()->createByServiceItemService($paymentFormDatas, $itemEntity);
                    }
                }
            }
            // echo $this->getServiceService()->getModel()->getLastQuery() . "\n";
            log_message("notice", "Billing 작업을 완료하였습니다.");
            $this->_db->transCommit();
        } catch (\Exception $e) {
            //Transaction Rollback
            $this->_db->transRollback();
            log_message(
                "error",
                "Billing 작업을 실패하였습니다.\n--------------\n" .
                    $e->getMessage() .
                    "\n--------------\n"
            );
        }
    }
}
