<?php

namespace Customize\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

use Doctrine\ORM\EntityManagerInterface;
use Plugin\RemisePayment4\Entity\RemiseACMember;

class ChargeDateCheckCommand extends Command
{
    /**
     * @var EntityManagerInterface
     */
    private $entityManager;
        
    protected static $defaultName = 'eccube:customize:chargedate_check';
    
    public function __construct(
        EntityManagerInterface $entityManager
    ) {
        $this->entityManager = $entityManager;
        parent::__construct();
    }

    protected function configure() {
      $this->setDescription('Charge Date Check');
    }
    
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $info = "[Apteq_custom][定期購買次回課金日チェック開始]";
        log_info($info); 
        
        $qb = $this->entityManager->createQueryBuilder();
        $RemiseACMemberRows = $qb->select("rm")
            ->from("\Plugin\RemisePayment4\Entity\RemiseACMember", "rm")
            ->where("rm.status = 1")
            ->getQuery()
            ->getResult();
        
        $today = new \DateTime();
        
        foreach($RemiseACMemberRows as $RemiseACMember) {         
        
            if($RemiseACMember->getNextDate() < $today) {
                // 次回課金日が過去の日付だったら未来の日付に変更
                $interval = $RemiseACMember->getIntervalValue();

                $beforeMonth = $RemiseACMember->getNextDate()->format("n");
                // 加算する
                $after       = (clone $RemiseACMember->getNextDate())->add(new \DateInterval("P" . $interval . "M"));
                $afterMonth  = $after->format("n");

                // 加算結果が期待値と異なる場合は、前月の最終日に修正する
                $tmpAfterMonth = $beforeMonth + $interval;
                $expectAfterMonth = $tmpAfterMonth > 12 ? $tmpAfterMonth - 12 : $tmpAfterMonth;

                if ($expectAfterMonth != $afterMonth) {
                    $after = (clone $after)->modify("last day of last month");
                }

                $RemiseACMember->setNextDate($after);
                $RemiseACMember->setUpdateDate($today);

                // DB書き込み
                $this->entityManager->persist($RemiseACMember);
                $this->entityManager->flush();

                $info = "[Apteq_custom]:".$RemiseACMember->getId().":".$RemiseACMember->getNextDate()->format("Ymd")."[次回課金日更新]";
                log_info($info);            
            }
        }        
        
        $info = "[Apteq_custom][定期購買次回課金日チェック終了]";
        log_info($info);         
    }
}
