<?php
namespace Google\Ads\GoogleAds\Examples\BasicOperations;

error_reporting(E_ALL);
require __DIR__ . '/google-ads-php/vendor/autoload.php';

use GetOpt\GetOpt;
use Google\ApiCore\ApiException;
use Google\Ads\GoogleAds\Lib\V21\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V21\GoogleAdsException;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser;
use Google\Ads\GoogleAds\Lib\V21\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\V21\Services\SearchGoogleAdsStreamRequest;

class GetCampaigns
{
    private const DEFAULT_CUSTOMER_ID = '4860398606';

    public static function main()
    {
        // Use the correct path for your secrets file
        $secretsPath = '/home/greatnew/public_html/lib/google-ads-api/google_ads_secrets.php';

        // Read secrets from the config file
        if (!is_readable($secretsPath)) {
            throw new \RuntimeException("Secrets file not readable: $secretsPath");
        }
        $cfg = require $secretsPath;
        if (!is_array($cfg)) {
            throw new \RuntimeException("Secrets file did not return an array: $secretsPath");
        }

        // Validate required keys
        foreach (['clientId', 'clientSecret', 'refreshToken', 'developerToken'] as $k) {
            if (!isset($cfg[$k]) || trim((string)$cfg[$k]) === '') {
                throw new \UnexpectedValueException("Missing or empty '$k' in $secretsPath");
            }
        }

        // Build OAuth2 credentials
        $oauth2 = (new OAuth2TokenBuilder())
            ->withClientId(trim($cfg['clientId']))
            ->withClientSecret(trim($cfg['clientSecret']))
            ->withRefreshToken(trim($cfg['refreshToken']))
            ->build();

        // Build Google Ads client using the credentials and settings
        $googleAdsClient = (new GoogleAdsClientBuilder())
            ->withDeveloperToken(trim($cfg['developerToken']))
            ->withOAuth2Credential($oauth2)
            ->withLoginCustomerId(trim($cfg['loginCustomerId'] ?? self::DEFAULT_CUSTOMER_ID))
            ->build();

        // Handle CLI or GET arg for customer ID
        $options = (new ArgumentParser())->parseCommandArguments([
            ArgumentNames::CUSTOMER_ID => GetOpt::REQUIRED_ARGUMENT
        ]);
        $customerId = $options[ArgumentNames::CUSTOMER_ID] ?: $googleAdsClient->getLoginCustomerId();

        // Execute the example
        self::getData($googleAdsClient, $customerId);
    }

    public static function getData(GoogleAdsClient $googleAdsClient, $customerId)
    {
        if (!isset($_REQUEST['campaign_id']) || !ctype_digit((string)$_REQUEST['campaign_id'])) {
            http_response_code(400);
            header('Content-Type: application/json');
            echo json_encode(['error' => 'campaign_id is required (numeric)']);
            return;
        }

        $campaignId = (string)$_REQUEST['campaign_id'];
        $svc = $googleAdsClient->getGoogleAdsServiceClient();

        $query = '
SELECT
  campaign.id,
  campaign.name,
  bidding_strategy.id,
  bidding_strategy.name,
  segments.device,
  campaign.end_date,
  campaign.start_date,
  segments.date,
  metrics.impressions,
  metrics.clicks,
  metrics.active_view_impressions,
  metrics.cost_micros
FROM campaign
WHERE campaign.id = ' . $campaignId . ' AND segments.date DURING LAST_30_DAYS';

        $stream = $svc->searchStream(
            SearchGoogleAdsStreamRequest::build($customerId, $query)
        );

        $results = [];
        foreach ($stream->iterateAllElements() as $row) {
            $device = (string)$row->getSegments()->getDevice()->getValue();
            $results[] = [
                'campaign_id'   => $row->getCampaign()->getId(),
                'date'          => $row->getSegments()->getDate(),
                'impressions'   => $row->getMetrics()->getImpressions(),
                'viewable_impr' => $row->getMetrics()->getActiveViewImpressions(),
                'clicks'        => $row->getMetrics()->getClicks(),
                'device'        => $device,
                'cost'          => number_format($row->getMetrics()->getCostMicros() / 1_000_000, 2),
            ];
        }

        header('Content-Type: application/json');
        echo json_encode($results);
    }
}

GetCampaigns::main();
