<?php

namespace KupShop\OrderingBundle\Tests;

use KupShop\DevelopmentBundle\MailArchive;
use KupShop\KupShopBundle\Config;
use KupShop\OrderingBundle\EventListener\CronListener;

class NotificationsTests extends \DatabaseTestCase
{
    /** @var MailArchive */
    protected $mailArchive;

    /** @var CronListener */
    private $listener;

    protected function setUp(): void
    {
        parent::setUp();

        $cfg = &Config::get();
        $cfg['Modules']['orders'] = [
            'notifyNotPaid' => [
                'afterDays' => [2, 5],
            ],
        ];

        $this->listener = new CronListener();
        $this->mailArchive = $this->get(MailArchive::class);
        $this->mailArchive->clearArchive();
    }

    public function changeOrderCreateDay($ageDays)
    {
        // Prepare order with ThePay created 1 days ago
        sqlQueryBuilder()->update('orders')
            ->set('date_created', 'NOW() - INTERVAL :days DAY')
            ->set('id_delivery', '8')
            ->setParameter('days', $ageDays)
            ->execute();
    }

    public function testNotPaidNotification()
    {
        // 1 day old - no email
        $this->changeOrderCreateDay(1);
        $this->listener->handleNotifyNotPaid();
        $this->assertFalse($this->mailArchive->getLast());

        // 3 days Old - send email
        $this->changeOrderCreateDay(3);
        $this->listener->handleNotifyNotPaid();
        $email = $this->mailArchive->getLast();
        $this->assertNotFalse($email);
        $this->assertContains('nebyla uhrazena', $email['body']);
        $this->mailArchive->clearArchive();

        $order = new \Order();
        $order->createFromDB(1);
        $history = $order->getHistory(true);
        $this->assertContains('upomínka platby', end($history)['comment']);

        // No email this time - already sent
        $this->changeOrderCreateDay(3);
        $this->listener->handleNotifyNotPaid();
        $this->assertFalse($this->mailArchive->getLast());
        $this->mailArchive->clearArchive();

        // 6 days old - send email
        $this->changeOrderCreateDay(6);
        $this->listener->handleNotifyNotPaid();
        $this->assertNotFalse($this->mailArchive->getLast());
        $this->mailArchive->clearArchive();

        // No email this time - already sent
        $this->changeOrderCreateDay(6);
        $this->listener->handleNotifyNotPaid();
        $this->assertFalse($this->mailArchive->getLast());
        $this->mailArchive->clearArchive();
    }
}
