<?php

declare(strict_types=1);

namespace External\PompoBundle\EventSubscriber\Ordering;

use KupShop\OrderingBundle\EventListener\CronListener;
use Query\Operator;
use Query\Order;

class OrderingCronSubscriber extends CronListener
{
    protected function notifyNotPaidOrder(\Order $order, int $level, array $notifySettings): void
    {
        // Pokud existuje nejaka duplicitni objednavka, ktera je z toho dne zaplacena, tak neodesilam notifikaci
        $orderCheck = sqlQueryBuilder()
            ->select('o.id')
            ->from('orders', 'o')
            // Duplicitni objednavka bud musi byt s platbou online a zaplacena, nebo nemit platbu online
            ->andWhere(
                Operator::orX(
                    Operator::andX(
                        Operator::equals(['o.status_payed' => 1]),
                        Order::byPaymentMethods([\Payment::METHOD_ONLINE])
                    ),
                    Operator::not(
                        Order::byPaymentMethods([\Payment::METHOD_ONLINE])
                    )
                )
            )
            // objednavka na stejny email
            ->andWhere(
                Operator::equals(
                    [
                        'o.invoice_email' => $order->invoice_email,
                    ]
                )
            )
            ->andWhere(Operator::not(Operator::equals(['o.id' => $order->id])))
            // musi to byt duplicitni objednavka
            ->andWhere(Operator::findInSet(['D'], 'o.flags'))
            ->execute()->fetchOne();

        $now = new \DateTime();
        // Kvuli pozdnimu nasazeni, aby to neodeslalo notifikaci na objednavky X mesicu starych
        $diff = $now->diff($order->date_created);

        // Oznacim, ze to bylo odeslane, ale nic neposilam
        // Protoze existuje duplicitni objednavka, ktera uz zaplacena je, nebo ma jiny typ platby
        if ($orderCheck || $diff->days > 6) {
            $order->setData('not_paid_notified', $level);

            return;
        }

        parent::notifyNotPaidOrder($order, $level, $notifySettings);
    }
}
