<?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 termos de pesquisa.
 *
 * @author Thiago Daher
 */
class SearchTermViewRepository extends AdsRepository
{

    /**
     * Retorna a lista de termos de pesquisa, juntamente com as métricas.
     *
     * @param \Win7\Ads\Entity\CustomerFilter $filter
     * @param string|null $adGroup
     * @return array
     */
    public function getListWithMetrics(CustomerFilter $filter, ?string $adGroup): array
    {
        $request = new ReportRequest();
        $request->setCustomerId($filter->getCustomerId());

        $qb = $request->getQueryBuilder();
        $qb->andSelect('search_term_view.search_term');
        $qb->andSelect('metrics.absolute_top_impression_percentage');
        $qb->andSelect('metrics.top_impression_percentage');
        $qb->andSelect('metrics.average_cpc');
        $qb->andSelect('metrics.cost_micros');
        $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('ad_group.id');
        $qb->andSelect('ad_group.name');
        $qb->andSelect('campaign.name');
        $this->applyCampaignFilter($qb, $filter);
        $this->applyDateFilter($qb, $filter);

        if ($adGroup) {
            $qb->andWhere("ad_group.id = '$adGroup'");
        }

        $qb->from('search_term_view');

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