<?php

declare(strict_types=1);

namespace External\PompoBundle\Util;

use External\PompoBundle\Email\PompoPartnerCouponsEmail;
use Query\Operator;

class PompoNotifier
{
    private const NOTIFY_LOW_PARTNER_COUPONS_COUNT = 5;

    private PompoPartnerCouponsEmail $partnerCouponsEmail;

    public function __construct(PompoPartnerCouponsEmail $partnerCouponsEmail)
    {
        $this->partnerCouponsEmail = $partnerCouponsEmail;
    }

    /**
     * Upozornění v případě, že budou docházet partnerské kódy.
     */
    public function notifyLowPartnerCoupons(): void
    {
        if (!($notifyEmail = $this->getNotifyEmail())) {
            return;
        }

        $qb = sqlQueryBuilder()
            ->select('bpe.id, bpe.name, COUNT(dc.id) as count, MIN(dc.date_to) as min_date')
            ->from('bonus_points_exchange', 'bpe')
            ->leftJoin('bpe', 'discounts_coupons', 'dc', 'dc.id_discount = bpe.id_discount AND dc.used = \'N\' AND dc.id_user IS NULL AND (dc.date_to >= NOW() OR dc.date_to IS NULL)')
            ->where(Operator::equals(['bpe.partner' => 'Y']))
            ->groupBy('bpe.id');

        $lowPartnerCoupons = [];
        foreach ($qb->execute() as $item) {
            if ($item['count'] <= self::NOTIFY_LOW_PARTNER_COUPONS_COUNT) {
                $lowPartnerCoupons[] = $item;
            }
        }

        if (!empty($lowPartnerCoupons)) {
            $this->partnerCouponsEmail->setCoupons($lowPartnerCoupons);
            $email = $this->partnerCouponsEmail->getEmail();
            $email['to'] = $notifyEmail;

            $this->partnerCouponsEmail->sendEmail($email);
        }
    }

    private function getNotifyEmail(): ?string
    {
        $dbcfg = \Settings::getDefault();

        $email = $dbcfg->loadValue('pompoSettings')['notify_email'] ?? null;
        if (empty($email)) {
            return null;
        }

        return $email;
    }
}
