<?php
namespace App\Command;

use Cake\Console\Arguments;
use Cake\Command\Command;
use Cake\Console\ConsoleIo;
use Cake\ORM\TableRegistry;
use Cake\Mailer\Mailer;

class NotifyDailyUsersCommand extends Command
{
    public function execute(Arguments $args, ConsoleIo $io)
    {
        $modelResults = TableRegistry::getTableLocator()->get('ProyectosPalabrasClavesLicitaciones');
        $today = date('Y-m-d');
        $status = -1;
        $opportunities = $modelResults->getOpportunities($status);
        $dataEmails = $opportunities['data_email'];
        if(count($opportunities) == 0)
        {
            $io->out('No hay oportunidades de negocio disponibles.');
            die;
        }
        // Enviar correos
        $subject = __('Nuevas oportunidades de negocio');
        $message = '';
        foreach($dataEmails as $to => $data)
        {
            try {
                $mailer = new Mailer('default');
                $mailer
                    ->setEmailFormat('html')
                    ->setTo($to)
                    ->setSubject($subject)
                    ->viewBuilder()
                        ->setTemplate('notification') // En templates/email/html/notificacion.php
                        ->setLayout('default');
                $mailer->setViewVars([
                    'data' => $data,
                ]);
                $mailer->deliver();

            } catch (\Exception $e) {

                $io->out('No se pudo enviar el correo a:' . $to . $e->getMessage());
            }
        }
    }
}
