<?php

namespace Market\ZodacoBundle\Console\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;

class SendMailCommand extends ContainerAwareCommand {

    protected function configure() {
        $this
                ->setName('SendMail')
                ->addArgument(
                        'id', InputArgument::OPTIONAL, 'Who do you want to send mail?'
                )
                ->setDescription('Runs Cron Tasks if needed')
                ->addOption(
                        'yell', null, InputOption::VALUE_NONE, 'If set, the task will yell in uppercase letters'
        );
    }

    protected function execute(InputInterface $input, OutputInterface $output) {
        $container = $this->getContainer();
        $em = $container->get('doctrine.orm.entity_manager');

        $output->writeln('<comment>Start</comment>');

        $check = $em->getRepository('MarketZodacoBundle:Notifications')->getTop();

        if ($check) {
            foreach ($check as $value) {
                $message = \Swift_Message::newInstance()
                        ->setSubject($value->getTitle())
                        ->setFrom("contact@chomanguon.vn", "Chợ Mã Nguồn")
                        ->setBody($value->getContent(), 'text/html');
                if ($value->getEmail() == $value->getReplyEmail()) {
                    $message->setTo("chomanguon.vn@gmail.com")->addReplyTo($value->getReplyEmail());
                } else {
                    $message->setTo($value->getEmail());
                    if($value->getReplyEmail() != ""){
                        $message->addReplyTo($value->getReplyEmail());
                    }
                }
                $container->get('mailer')->send($message);

                $em->remove($value);
            }
            $em->flush();
        }

        $output->writeln('<comment>Done</comment>');
    }

}
