<?php

namespace Win7\Ads\Repository;

use Win7\Ads\Entity\CustomerFilter;
use Win7\Ads\Report\ReportRequest;

/**
 * Repositório responsável por consultar e executar modificações em grupos de anúncios.
 *
 * @author Thiago Daher
 */
class AdGroupRepository extends AdsRepository
{

    /**
     * Consulta a lista de grupos de anúncios, juntamente com as métricas.
     *
     * @param \Win7\Ads\Entity\CustomerFilter $filter
     * @return array
     */
    public function getListWithMetrics(CustomerFilter $filter): array
    {
        $request = new ReportRequest();
        $request->setCustomerId($filter->getCustomerId());

        $qb = $request->getQueryBuilder();
        $qb->andSelect('ad_group.name');
        $qb->andSelect('ad_group.id');
        $qb->andSelect('campaign.id');
        $qb->andSelect('metrics.conversions_from_interactions_rate');
        $qb->andSelect('metrics.clicks');
        $qb->andSelect('metrics.impressions');
        $qb->andSelect('metrics.conversions');
        $qb->andSelect('metrics.ctr');
        $qb->andSelect('metrics.absolute_top_impression_percentage');
        $qb->andSelect('metrics.top_impression_percentage');
        $qb->andSelect('metrics.average_cpc');
        $qb->andSelect('metrics.cost_micros');
        $qb->from('ad_group');
        $this->applyCampaignFilter($qb, $filter);
        $this->applyDateFilter($qb, $filter);
        $qb->andWhere('metrics.impressions > 0');
        $qb->andWhere('metrics.clicks > 0');

        return $this->getReportResult($request);
    }

    /**
     * Consulta a lista de grupos de anúncios.
     *
     * @param \Win7\Ads\Entity\CustomerFilter $filter
     * @return array
     */
    public function getList(CustomerFilter $filter): array
    {
        $request = new ReportRequest();
        $request->setCustomerId($filter->getCustomerId());

        $qb = $request->getQueryBuilder();
        $qb->andSelect('ad_group.name');
        $qb->andSelect('ad_group.id');
        $qb->andSelect('campaign.id');
        $qb->andSelect('campaign.name');
        $qb->from('ad_group');
        $this->applyCampaignFilter($qb, $filter, false);
        $qb->andWhere("campaign.status = 'ENABLED'");
        $qb->andWhere("ad_group.status = 'ENABLED'");
        $qb->andWhere("campaign.serving_status = 'SERVING'");

        return $this->getReportResult($request);
    }
}