<?php

namespace KupShop\ElninoBundle\EventListener;

use KupShop\KupShopBundle\Email\OrderNotPaidEmail;

class OrderingCronListener extends \KupShop\OrderingBundle\EventListener\CronListener
{
    public function handleNotifyNotPaid()
    {
        $config = findModule(\Modules::ORDERS, \Modules::SUB_NOTIFY_NOT_PAID);
        foreach ((array) ($config ?? []) as $notifySettings) {
            if ($notifySettings['afterHours'] ?? false) {
                arsort($notifySettings['afterHours']);
                foreach ((array) ($notifySettings['afterHours'] ?? []) as $index => $hours) {
                    $orderResults = sqlQueryBuilder()->select('o.id')
                        ->from('orders', 'o')
                        ->where('o.status_payed = 0 AND o.status_storno = 0 AND o.date_handle IS NULL')
                        ->andWhere(\Query\Order::byPaymentMethods($notifySettings['forPaymentMethods']))
                        ->andWhere('DATE_ADD(o.date_created, INTERVAL :hours HOUR) <= CURRENT_TIMESTAMP()')
                        ->setParameter('hours', $hours)
                        ->groupBy('o.id')
                        ->orderBy('o.date_accept', 'ASC')->execute();
                    foreach ($orderResults as $orderResult) {
                        $order = new \Order();
                        $order->createFromDB($orderResult['id']);

                        // skip vraceny balik
                        if (isset($order->getFlags()['IR'])) {
                            continue;
                        }

                        $level = $index + 1;
                        // Send notification only if this level message not sent
                        if ($order->getData('not_paid_notified') < $level) {
                            $order->sendEmail(
                                null,
                                null,
                                false,
                                OrderNotPaidEmail::getType()
                            );
                            $order->setData('not_paid_notified', $level);
                        }
                    }
                }
            }
            if (($notifySettings['cancelHours'] ?? 0) > 0) {
                $this->cancelOrders($notifySettings['forPaymentMethods'], $notifySettings['cancelHours'], $notifySettings);
            }
        }
    }
}
