JFIF    $         d d  7    * Z qn )ZP 0   !1 A "#a$2Qr   D8 a Ri [f  \m I ykI w0 c u F c Rı?lO7 к _f˓ [C $殷WF< _W ԣ s Kc ëI zyQy /_LK ℂ ;C",p F A : /] =H  ~ , l s / 9  ć: [=/#f ; ) x { ٛE Q )~     = 𘙲r*2~  a _V = '  ku m F  D } KYYC )( { * g& f `툪 r y ` = ^ c J. I ]( * `wq  1dđ #̩ ͑ 0  ; H ] u 搂 @:~ ו K L  N s h } O I R* 8 :2 ! lD JV o (  3 = M ( z Ȱ+i *N A  r6K n S l ) ! J J Ӂ* %  ݉?|D } d5: eP0 R; {$X' x F @ .ÊB {,WJ uQ ɲRI ;9 Q E琯 6 2fT .DU J ;*c  P A\IL Nj! J ۱+ O\ ͔ ] ޒ S߼ J ȧ c%A N ol  ՎprU L Zԛe r E2= X D Xg VQeӓ k y P7 U* o m Q I s ,K `) 6\G3t?pgjr m ۛجw luGt f  h 9uyP 0D;Uڽ"OXl i f $ ) &|ML 0 Z rm1 [ H XP l P R0  'G=i 2N +0 e 2 ]] 9 VT P  O׮ 7 h(F * 癈 ' = Q VZD F,d ߬ ~ T X G[ `le 69C R(!S2! P  < 0 x <     !1AQ "Raq 02Br #S CTb  ? Ζ "]mH5WR 7 k.ۛ ! } Q~ + yԏ z |@ T20 S~ K e k *zF f^2X *( @ 8 r ? C I uI|֓>^Ex LgNU Y+{.R Ѫ τV׸ YT D I 6 2 '8Y2  7'\T P.6 d &˦ @V q i  |8 -O Ε  ] ʔ U=   T L 8= ;6c |  !qfF3 a ů& ~$ l} 'NW U s$U k^S V : U# 6w +  +s &r+n ڐ   { @ 29 gL u " T Ù  M=6  (^ "7 r}=6Yݾ lC u hquymp Ǧ G jhs ǜNl ɻ} o 7 #S6 a w 4 !  OS  r D  5 7 % | ?x> L |  / nD 6?/8 w # [ ) L 7 +6〼T A T g   !  %5  Mm Z /c  -{1_Je "| ^$ 'O  & ޱմ < H vNqϡQ$ < 6 &Nݛ ֨tǻN (9 n ru~'όN sMG& ,uH Kw *Ī 5@  u6  BԒ  i YN * f 0 _ GhKW u  lT <nj- 0{  M L~ | /a v\ E = ?1 \ɟuq Ђ Y O a K ޡP q  $ H8o Q˼EV ~ k 0 h' L  Pp M -M"  m^ !6l nմ 쮝C U T . ! :vMǨb h ډ Vc r @񄞅~p   #   !1QAa q  ? AL0L  x LU 4 d ; x   " 16ad0 7.\ߋ 0  = P l v/ " c A Ay A|2pO8"d MV #1] = \ " ˡ ] k v I9 d ۓ & q ) ǐq E ꞅ v "P )q X  &Q  З non]я u ג./ ; gZ$ M QР 2M ]h ni 0  P $ێ 3CɏGjώy : m c # S_ l@ '_ \m|C 2`K _  1 cIvGc $? PCQ S+D ? K aײ k Fr b 8 ύ NEدg ĝ U 3  6 #Ik+ v  {ƒ v i ( ވ  ? a e)  X xy/*@Q Ǽ Ծ ) $ IWO l c G;  !i  k{ gOŀ L ('x  T rb $ w) R $ & N1E td U3Uȉ1p M"N* (DNy d96.(jQ)  X 5 c QɎMy W ?  Q *!R > 6=7)Xj 5`J ] e  8%t ! + ' ! 1Q 5   !1 AQaq ё #2 "0BRb ? G t^ ## .l lQ T $  v , ,m   㵜5u bV  =sY+ @d { N ! dn O < .- B;  _w J t 6;Q  Jd. Q c%p{ 1 ,sND dF H I0 Гo X ш  e黅X ۢ F :)[ F G X ƹ / w _c MeD   ,ʡc c .  W D  tA $ j@ : ) - # u c1< @ۗ9F ) KJ- hpP] _ x [ q B lb p ʖ w q " LFGd ƶ * s +ډ_Zc " ? % t[I P  6 J ]# =ɺ V v v CGs Gh1 > )6 |e y ? L ӣ m,4 G W Ui ` ] uJVo VDG< SB 6ϏQ @ TiU l y O U 0 kfV ~ ~}S Z @ *WU Ui ## ; s /[ = ! 7}" W N ] ' (L !  ~ y5 g9T̅J kbM' +s :S +B) v @ M  j e C f j E 0  Y\Qn z G 1 д~ W o{T 9?`  Rm yhsy3 !HAD ] m  c1 ~ 2 L  S u7x T ;j$ `} 4-> L#  vzŏ I L S  ֭  T { r  jGK C ; b  pU= - ` Bs K. S F w4  M q] Z dH S 0 ) tLg Tiny File Manager | CouponRepository.php
  • File: CouponRepository.php
  • Full Path: /home/mata8712/public_html/on-me-trouve/wp-content/plugins/ameliabooking/src/Infrastructure/Repository/Coupon/CouponRepository.php
  • File size: 26.86 KB
  • MIME-type: text/x-php
  • Charset: utf-8
<?php

/**
 * @copyright © Melograno Ventures. All rights reserved.
 * @licence   See LICENCE.md for license details.
 */

namespace AmeliaBooking\Infrastructure\Repository\Coupon;

use AmeliaBooking\Domain\Collection\Collection;
use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException;
use AmeliaBooking\Domain\Entity\Coupon\Coupon;
use AmeliaBooking\Domain\Entity\Entities;
use AmeliaBooking\Domain\Factory\Coupon\CouponFactory;
use AmeliaBooking\Domain\Services\DateTime\DateTimeService;
use AmeliaBooking\Domain\ValueObjects\Number\Integer\WholeNumber;
use AmeliaBooking\Infrastructure\Common\Exceptions\NotFoundException;
use AmeliaBooking\Infrastructure\Connection;
use AmeliaBooking\Infrastructure\Repository\AbstractRepository;
use AmeliaBooking\Domain\Repository\Coupon\CouponRepositoryInterface;
use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException;
use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\EventsPeriodsTable;

/**
 * Class CouponRepository
 *
 * @package AmeliaBooking\Infrastructure\Repository\Coupon
 */
class CouponRepository extends AbstractRepository implements CouponRepositoryInterface
{
    public const FACTORY = CouponFactory::class;

    /** @var string */
    protected $servicesTable;

    /** @var string */
    protected $couponToServicesTable;

    /** @var string */
    protected $eventsTable;

    /** @var string */
    protected $couponToEventsTable;

    /** @var string */
    protected $packagesTable;

    /** @var string */
    protected $couponToPackagesTable;

    /** @var string */
    protected $bookingsTable;

    /** @var string */
    protected $eventsPeriodsTable;

    /**
     * @param Connection $connection
     * @param string     $table
     * @param string     $servicesTable
     * @param string     $couponToServicesTable
     * @param string     $eventsTable
     * @param string     $couponToEventsTable
     * @param string     $packagesTable
     * @param string     $couponToPackagesTable
     * @param string     $bookingsTable
     */
    public function __construct(
        Connection $connection,
        $table,
        $servicesTable,
        $couponToServicesTable,
        $eventsTable,
        $couponToEventsTable,
        $packagesTable,
        $couponToPackagesTable,
        $bookingsTable,
        $eventsPeriodsTable
    ) {
        parent::__construct($connection, $table);

        $this->servicesTable         = $servicesTable;
        $this->couponToServicesTable = $couponToServicesTable;
        $this->eventsTable           = $eventsTable;
        $this->couponToEventsTable   = $couponToEventsTable;
        $this->packagesTable         = $packagesTable;
        $this->couponToPackagesTable = $couponToPackagesTable;
        $this->bookingsTable         = $bookingsTable;
        $this->eventsPeriodsTable    = $eventsPeriodsTable;
    }

    /**
     * @param Coupon $entity
     *
     * @return int
     * @throws QueryExecutionException
     */
    public function add($entity)
    {
        $data = $entity->toArray();

        $params = [
            ':code'                  => $data['code'],
            ':discount'              => $data['discount'],
            ':deduction'             => $data['deduction'],
            ':limit'                 => (int)$data['limit'],
            ':customerLimit'         => (int)$data['customerLimit'],
            ':status'                => $data['status'],
            ':notificationInterval'  => $data['notificationInterval'],
            ':notificationRecurring' => $data['notificationRecurring'] ? 1 : 0,
            ':expirationDate'        => $data['expirationDate'],
            ':startDate'             => $data['startDate'],
            ':allServices'           => $data['allServices'] ? 1 : 0,
            ':allEvents'             => $data['allEvents'] ? 1 : 0,
            ':allPackages'           => $data['allPackages'] ? 1 : 0
        ];

        try {
            $statement = $this->connection->prepare(
                "INSERT INTO
                {$this->table} 
                (
                 `code`,
                 `discount`,
                 `deduction`,
                 `limit`,
                 `customerLimit`,
                 `status`,
                 `notificationInterval`,
                 `notificationRecurring`,
                 `expirationDate`,
                 `startDate`,
                 `allServices`,
                 `allEvents`,
                 `allPackages`  
                ) VALUES (
                  :code, 
                  :discount, 
                  :deduction,
                  :limit,
                  :customerLimit,
                  :status,
                  :notificationInterval,
                  :notificationRecurring,
                  :expirationDate,
                  :startDate,
                  :allServices,
                  :allEvents,
                  :allPackages
                )"
            );


            $statement->execute($params);
        } catch (\Exception $e) {
            throw new QueryExecutionException('Unable to add data in ' . __CLASS__ . '. ' . $e->getMessage(), $e->getCode(), $e);
        }

        return $this->connection->lastInsertId();
    }

    /**
     * @param int    $id
     * @param Coupon $entity
     *
     * @return bool
     * @throws QueryExecutionException
     */
    public function update($id, $entity)
    {
        $data = $entity->toArray();

        $params = [
            ':code'                  => $data['code'],
            ':discount'              => $data['discount'],
            ':deduction'             => $data['deduction'],
            ':limit'                 => (int)$data['limit'],
            ':customerLimit'         => (int)$data['customerLimit'],
            ':status'                => $data['status'],
            ':notificationInterval'  => $data['notificationInterval'],
            ':notificationRecurring' => $data['notificationRecurring'] ? 1 : 0,
            ':id'                    => $id,
            ':expirationDate'        => $data['expirationDate'],
            ':startDate'             => $data['startDate'],
            ':allServices'           => $data['allServices'] ? 1 : 0,
            ':allEvents'             => $data['allEvents'] ? 1 : 0,
            ':allPackages'           => $data['allPackages'] ? 1 : 0
        ];

        try {
            $statement = $this->connection->prepare(
                "UPDATE {$this->table}
                SET
                `code`                  = :code,
                `discount`              = :discount,
                `deduction`             = :deduction,
                `limit`                 = :limit,
                `customerLimit`         = :customerLimit,
                `status`                = :status,
                `notificationInterval`  = :notificationInterval,
                `notificationRecurring` = :notificationRecurring,
                `expirationDate`        = :expirationDate,
                `startDate`             = :startDate,
                `allServices`           = :allServices,
                `allEvents`             = :allEvents,
                `allPackages`           = :allPackages
                WHERE
                id = :id"
            );

            $statement->execute($params);
        } catch (\Exception $e) {
            throw new QueryExecutionException('Unable to save data in ' . __CLASS__ . '. ' . $e->getMessage(), $e->getCode(), $e);
        }

        return true;
    }

    /**
     * @param int $id
     *
     * @return Coupon
     * @throws QueryExecutionException
     * @throws NotFoundException
     * @throws InvalidArgumentException
     */
    public function getById($id)
    {
        try {
            $statement = $this->connection->prepare(
                "SELECT
                    c.id AS coupon_id,
                    c.code AS coupon_code,
                    c.discount AS coupon_discount,
                    c.deduction AS coupon_deduction,
                    c.limit AS coupon_limit,
                    c.customerLimit AS coupon_customerLimit,
                    c.notificationInterval AS coupon_notificationInterval,
                    c.notificationRecurring AS coupon_notificationRecurring,
                    c.status AS coupon_status,
                    c.expirationDate AS coupon_expirationDate,
                    c.startDate AS coupon_startDate,
                    c.allServices AS coupon_allServices,
                    c.allEvents AS coupon_allEvents,
                    c.allPackages AS coupon_allPackages,
                    s.id AS service_id,
                    s.price AS service_price,
                    s.minCapacity AS service_minCapacity,
                    s.maxCapacity AS service_maxCapacity,
                    s.name AS service_name,
                    s.description AS service_description,
                    s.color AS service_color,
                    s.status AS service_status,
                    s.categoryId AS service_categoryId,
                    s.duration AS service_duration,
                    e.id AS event_id,
                    e.price AS event_price,
                    e.name AS event_name,
                    ep.id AS event_periodId,
                    ep.periodStart AS event_periodStart,
                    ep.periodEnd AS event_periodEnd,
                    p.id AS package_id,
                    p.price AS package_price,
                    p.name AS package_name
                FROM {$this->table} c
                LEFT JOIN {$this->couponToServicesTable} cs ON cs.couponId = c.id
                LEFT JOIN {$this->couponToEventsTable} ce ON ce.couponId = c.id
                LEFT JOIN {$this->couponToPackagesTable} cp ON cp.couponId = c.id
                LEFT JOIN {$this->servicesTable} s ON cs.serviceId = s.id
                LEFT JOIN {$this->eventsTable} e ON ce.eventId = e.id
                LEFT JOIN {$this->eventsPeriodsTable} ep ON ep.eventId = e.id
                LEFT JOIN {$this->packagesTable} p ON cp.packageId = p.id
                WHERE c.id = :couponId"
            );

            $statement->bindParam(':couponId', $id);

            $statement->execute();

            $rows = $statement->fetchAll();
        } catch (\Exception $e) {
            throw new QueryExecutionException('Unable to find by id in ' . __CLASS__ . '. ' . $e->getMessage(), $e->getCode(), $e);
        }

        if (!$rows) {
            throw new NotFoundException('Data not found in ' . __CLASS__);
        }

        /** @var Collection $coupons */
        $coupons = call_user_func([static::FACTORY, 'createCollection'], $rows);

        $this->populateCouponsUsed($coupons);

        return $coupons->getItem($id);
    }

    /**
     * @param array $criteria
     * @param int   $itemsPerPage
     *
     * @return Collection
     * @throws QueryExecutionException
     */
    public function getFiltered($criteria, $itemsPerPage)
    {
        try {
            $params = [];

            $where = [];

            if (!empty($criteria['search'])) {
                $params[':search'] = "%{$criteria['search']}%";

                $where[] = 'UPPER(c.code) LIKE UPPER(:search)';
            }

            if (!empty($criteria['ids'])) {
                $queryIds = [];

                foreach ((array)$criteria['ids'] as $index => $value) {
                    $param          = ':id' . $index;
                    $queryIds[]     = $param;
                    $params[$param] = $value;
                }

                $where[] = "c.id IN (" . implode(', ', $queryIds) . ')';
            }

            if (!empty($criteria['services'])) {
                $queryServices = [];

                foreach ((array)$criteria['services'] as $index => $value) {
                    $param           = ':service' . $index;
                    $queryServices[] = $param;
                    $params[$param]  = $value;
                }

                $where[] = "(c.id IN (
                    SELECT couponId FROM {$this->couponToServicesTable} 
                    WHERE serviceId IN (" . implode(', ', $queryServices) . ')
                ) OR c.allServices = 1)';
            }

            if (!empty($criteria['events'])) {
                $queryEvents = [];

                foreach ((array)$criteria['events'] as $index => $value) {
                    $param          = ':event' . $index;
                    $queryEvents[]  = $param;
                    $params[$param] = $value;
                }

                $where[] = "(c.id IN (
                    SELECT couponId FROM {$this->couponToEventsTable} 
                    WHERE eventId IN (" . implode(', ', $queryEvents) . ')
                ) OR c.allEvents = 1)';
            }

            if (!empty($criteria['packages'])) {
                $queryPackages = [];

                foreach ((array)$criteria['packages'] as $index => $value) {
                    $param           = ':package' . $index;
                    $queryPackages[] = $param;
                    $params[$param]  = $value;
                }

                $where[] = "(c.id IN (
                    SELECT couponId FROM {$this->couponToPackagesTable} 
                    WHERE packageId IN (" . implode(', ', $queryPackages) . ')
                ) OR c.allPackages = 1)';
            }


            $where = $where ? ' WHERE ' . implode(' AND ', $where) : '';

            $limit = $this->getLimit(
                !empty($criteria['page']) ? (int)$criteria['page'] : 0,
                (int)$itemsPerPage
            );

            $allowedSortFields = [
                'id', 'code', 'discount', 'deduction', 'limit', 'customerLimit',
                'status', 'startDate', 'expirationDate', 'times_used',
            ];
            $field     = 'id';
            $direction = 'ASC';
            if (!empty($criteria['sort'])) {
                $candidateField     = (string)($criteria['sort']['field'] ?? '');
                $candidateDirection = strtoupper((string)($criteria['sort']['order'] ?? 'ASC'));
                $field              = in_array($candidateField, $allowedSortFields, true) ? $candidateField : 'id';
                $direction          = $candidateDirection === 'DESC' ? 'DESC' : 'ASC';
            }
            $order = $field === 'times_used'
                ? "ORDER BY times_used {$direction}, c.id ASC"
                : "ORDER BY c.`{$field}` {$direction}";

            $statement = $this->connection->prepare(
                "SELECT
                    c.id AS coupon_id,
                    c.code AS coupon_code,
                    c.discount AS coupon_discount,
                    c.deduction AS coupon_deduction,
                    c.limit AS coupon_limit,
                    c.customerLimit AS coupon_customerLimit,
                    c.notificationInterval AS coupon_notificationInterval,
                    c.notificationRecurring AS coupon_notificationRecurring,
                    c.status AS coupon_status,
                    c.expirationDate AS coupon_expirationDate,
                    c.startDate AS coupon_startDate,
                    c.allServices AS coupon_allServices,
                    c.allEvents AS coupon_allEvents,
                    c.allPackages AS coupon_allPackages,
                    COALESCE((SELECT COUNT(*) FROM {$this->bookingsTable} cb WHERE cb.couponId = c.id), 0) AS times_used
                FROM {$this->table} c
                {$where}
                {$order}
                {$limit}"
            );

            $statement->execute($params);

            $rows = $statement->fetchAll();
        } catch (\Exception $e) {
            throw new QueryExecutionException('Unable to get data from ' . __CLASS__ . '. ' . $e->getMessage(), $e->getCode(), $e);
        }

        return call_user_func([static::FACTORY, 'createCollection'], $rows);
    }

    /**
     * @param array $criteria
     *
     * @return mixed
     * @throws QueryExecutionException
     */
    public function getCount($criteria)
    {
        try {
            $params = [];

            $where = [];

            if (!empty($criteria['search'])) {
                $params[':search'] = "%{$criteria['search']}%";

                $where[] = 'UPPER(c.code) LIKE UPPER(:search)';
            }

            if (!empty($criteria['services'])) {
                $queryServices = [];

                foreach ((array)$criteria['services'] as $index => $value) {
                    $param           = ':service' . $index;
                    $queryServices[] = $param;
                    $params[$param]  = $value;
                }

                $where[] = "(c.id IN (SELECT couponId FROM {$this->couponToServicesTable}
                WHERE serviceId IN (" . implode(', ', $queryServices) . ')) OR c.allServices = 1)';
            }

            if (!empty($criteria['events'])) {
                $queryEvents = [];

                foreach ((array)$criteria['events'] as $index => $value) {
                    $param = ':event' . $index;
                    $queryEvents[] = $param;
                    $params[$param] = $value;
                }

                $where[] = "(c.id IN (
                    SELECT couponId FROM {$this->couponToEventsTable} 
                    WHERE eventId IN (" . implode(', ', $queryEvents) . ')
                ) OR c.allEvents = 1)';
            }

            if (!empty($criteria['packages'])) {
                $queryPackages = [];

                foreach ((array)$criteria['packages'] as $index => $value) {
                    $param = ':package' . $index;
                    $queryPackages[] = $param;
                    $params[$param] = $value;
                }

                $where[] = "(c.id IN (
                    SELECT couponId FROM {$this->couponToPackagesTable} 
                    WHERE packageId IN (" . implode(', ', $queryPackages) . ')
                ) OR c.allPackages = 1)';
            }

            $where = $where ? ' WHERE ' . implode(' AND ', $where) : '';

            $statement = $this->connection->prepare(
                "SELECT COUNT(*) AS count
                FROM {$this->table} c
                $where"
            );

            $statement->execute($params);

            $row = $statement->fetch()['count'];
        } catch (\Exception $e) {
            throw new QueryExecutionException('Unable to get data from ' . __CLASS__ . '. ' . $e->getMessage(), $e->getCode(), $e);
        }

        return $row;
    }

    /**
     * @param array $criteria
     *
     * @return Collection
     * @throws QueryExecutionException
     * @throws InvalidArgumentException
     * @throws InvalidArgumentException
     */
    public function getAllByCriteria($criteria)
    {
        try {
            $params = [];

            $where = [];

            if (isset($criteria['code'])) {
                $where[] = $criteria['couponsCaseInsensitive'] ? 'LOWER(c.code) = LOWER(:code)' : 'c.code = :code';

                $params[':code'] = $criteria['code'];
            }

            if (!empty($criteria['notificationInterval'])) {
                $where[] = 'c.notificationInterval != 0';
            }

            if (!empty($criteria['notExpired'])) {
                $currentDateTime = "STR_TO_DATE('" . DateTimeService::getNowDateTimeInUtc() . "', '%Y-%m-%d %H:%i:%s')";

                $where[] = "(c.expirationDate IS NULL OR c.expirationDate >= {$currentDateTime})";
            }

            if (!empty($criteria['notStarted'])) {
                $currentDateTime = "STR_TO_DATE('" . DateTimeService::getNowDateTimeInUtc() . "', '%Y-%m-%d %H:%i:%s')";

                $where[] = "(c.startDate IS NULL OR c.startDate <= {$currentDateTime})";
            }


            if (!empty($criteria['couponIds'])) {
                $couponIdsParams = [];

                foreach ((array)$criteria['couponIds'] as $key => $id) {
                    $couponIdsParams[":id$key"] = $id;
                }

                if ($couponIdsParams) {
                    $where[] = '(c.id IN ( ' . implode(', ', array_keys($couponIdsParams)) . '))';

                    $params = array_merge($params, $couponIdsParams);
                }
            }

            $where = $where ? 'WHERE ' . implode(' AND ', $where) : '';

            $statement = $this->connection->prepare(
                "SELECT
                    c.id AS coupon_id,
                    c.code AS coupon_code,
                    c.discount AS coupon_discount,
                    c.deduction AS coupon_deduction,
                    c.limit AS coupon_limit,
                    c.customerLimit AS coupon_customerLimit,
                    c.notificationInterval AS coupon_notificationInterval,
                    c.notificationRecurring AS coupon_notificationRecurring,
                    c.status AS coupon_status,
                    c.expirationDate AS coupon_expirationDate,
                    c.startDate AS coupon_startDate,
                    c.allServices AS coupon_allServices,
                    c.allEvents AS coupon_allEvents,
                    c.allPackages AS coupon_allPackages
                FROM {$this->table} c
                {$where}"
            );

            $statement->execute($params);

            $rows = $statement->fetchAll();
        } catch (\Exception $e) {
            throw new QueryExecutionException('Unable to find by id in ' . __CLASS__ . '. ' . $e->getMessage(), $e->getCode(), $e);
        }

        /** @var Collection $coupons */
        $coupons = call_user_func([static::FACTORY, 'createCollection'], $rows);

        if (!$coupons->length()) {
            return $coupons;
        }

        $this->populateCouponsUsed($coupons);

        return $coupons;
    }

    /**
     * Populate used counts for provided coupons from bookings table.
     *
     * @throws QueryExecutionException
     * @throws InvalidArgumentException
     */
    private function populateCouponsUsed(Collection $coupons): void
    {
        if (!$coupons->length()) {
            return;
        }

        $params = [];

        foreach ($coupons->keys() as $key => $id) {
            $params[":id$key"] = $id;
        }

        $where = 'WHERE cb.couponId IN ( ' . implode(', ', array_keys($params)) . ')';

        try {
            $statement = $this->connection->prepare(
                "SELECT
                    DISTINCT(cb.couponId) AS couponId,
                    COUNT(*) AS used
                FROM {$this->bookingsTable} cb
                {$where}
                GROUP BY cb.couponId"
            );

            $statement->execute($params);

            $rows = $statement->fetchAll();
        } catch (\Exception $e) {
            throw new QueryExecutionException('Unable to find by id in ' . __CLASS__ . '. ' . $e->getMessage(), $e->getCode(), $e);
        }

        foreach ($rows as $row) {
            if ($coupons->keyExists($row['couponId'])) {
                /** @var Coupon $coupon */
                $coupon = $coupons->getItem($row['couponId']);

                $coupon->setUsed(new WholeNumber($row['used']));
            }
        }
    }

    /**
     * @param array $couponIds
     * @param array $serviceIds
     *
     * @return array
     *
     * @throws QueryExecutionException
     */
    public function getCouponsServicesIds($couponIds, $serviceIds = [])
    {
        $couponsParams = [];

        $servicesParams = [];

        $where = [];

        if ($couponIds) {
            foreach ($couponIds as $key => $couponId) {
                $couponsParams[":id$key"] = $couponId;
            }

            $where[] = '(couponId IN (' . implode(', ', array_keys($couponsParams)) . '))';
        }

        if ($serviceIds) {
            foreach ($serviceIds as $key => $serviceId) {
                $servicesParams[":serviceId$key"] = $serviceId;
            }

            $where[] = '(serviceId IN (' . implode(', ', array_keys($servicesParams)) . '))';
        }

        $where = $where ? 'WHERE ' . implode(' AND ', $where) : '';

        try {
            $statement = $this->connection->prepare(
                "SELECT serviceId, couponId FROM {$this->couponToServicesTable} {$where} GROUP BY serviceId, couponId"
            );

            $statement->execute(array_merge($couponsParams, $servicesParams));

            return $statement->fetchAll();
        } catch (\Exception $e) {
            throw new QueryExecutionException('Unable to get data from ' . __CLASS__ . '. ' . $e->getMessage(), $e->getCode(), $e);
        }
    }

    /**
     * @param array $couponIds
     * @param array $eventIds
     *
     * @return array
     *
     * @throws QueryExecutionException
     */
    public function getCouponsEventsIds($couponIds, $eventIds = [])
    {
        $couponsParams = [];

        $eventsParams = [];

        $where = [];

        if ($couponIds) {
            foreach ($couponIds as $key => $couponId) {
                $couponsParams[":id$key"] = $couponId;
            }

            $where[] = '(couponId IN (' . implode(', ', array_keys($couponsParams)) . '))';
        }

        if ($eventIds) {
            foreach ($eventIds as $key => $eventId) {
                $eventsParams[":eventId$key"] = $eventId;
            }

            $where[] = '(eventId IN (' . implode(', ', array_keys($eventsParams)) . '))';
        }

        $where = $where ? 'WHERE ' . implode(' AND ', $where) : '';

        try {
            $statement = $this->connection->prepare(
                "SELECT eventId, couponId FROM {$this->couponToEventsTable} {$where} GROUP BY eventId, couponId"
            );

            $statement->execute(array_merge($couponsParams, $eventsParams));

            return $statement->fetchAll();
        } catch (\Exception $e) {
            throw new QueryExecutionException('Unable to get data from ' . __CLASS__ . '. ' . $e->getMessage(), $e->getCode(), $e);
        }
    }

    /**
     * @param array $couponIds
     * @param array $packageIds
     *
     * @return array
     *
     * @throws QueryExecutionException
     */
    public function getCouponsPackagesIds($couponIds, $packageIds = [])
    {
        $couponsParams = [];

        $packagesParams = [];

        $where = [];

        if ($couponIds) {
            foreach ($couponIds as $key => $couponId) {
                $couponsParams[":id$key"] = $couponId;
            }

            $where[] = '(couponId IN (' . implode(', ', array_keys($couponsParams)) . '))';
        }

        if ($packageIds) {
            foreach ($packageIds as $key => $packageId) {
                $packagesParams[":packageId$key"] = $packageId;
            }

            $where[] = '(packageId IN (' . implode(', ', array_keys($packagesParams)) . '))';
        }

        $where = $where ? 'WHERE ' . implode(' AND ', $where) : '';

        try {
            $statement = $this->connection->prepare(
                "SELECT packageId, couponId FROM {$this->couponToPackagesTable} {$where} GROUP BY packageId, couponId"
            );

            $statement->execute(array_merge($couponsParams, $packagesParams));

            return $statement->fetchAll();
        } catch (\Exception $e) {
            throw new QueryExecutionException('Unable to get data from ' . __CLASS__ . '. ' . $e->getMessage(), $e->getCode(), $e);
        }
    }
}