<?php

namespace App\Controllers\CLI;

use App\Controllers\BaseController;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

class Invoice extends BaseController
{
    private $service = null;
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        if ($this->service === null) {
            $this->service = service('customer_serviceservice');
        }
    }
    public function execute(): void
    {
        try {
            log_message('info', "청구서 발행 시작");
            $success = 0;
            $error   = 0;
            $total   = 0;
            foreach ($this->service->getEntities(['billing_at' => date("Y-m-d"), 'status' => STATUS['AVAILABLE']]) as $entity) {
                try {
                    service('paymentservice')->createByService($entity);
                    $entity = $this->service->modify($entity, ['billing_at' => $this->service->getNextMonthDate($entity)]);
                    log_message('info', "{$entity->getServerTitle()} 청구서 발행 완료: 다음달 청구일:{$entity->getBillingAt()} 입니다.");
                } catch (\Throwable $e) {
                    $error++;
                    log_message('error', "{$entity->getServerTitle()} 청구서 발행 실패:{$e->getMessage()}");
                }
                $total++;
            }
            log_message('info', sprintf("성공:%s , 실패:%s , 총:%s 청구서 발행 작업완료", $success, $error, $total));
        } catch (\Throwable $e) {
            log_message('error', "청구서 발행 작업오류:{$e->getMessage()}");
        }
    }
}
