<?php
// src/AdMobAPI.php - AdMob API Handler

class AdMobAPI {
    private $access_token;
    private $api_endpoint = 'https://admobapi.googleapis.com/v1';
    private $publisher_id;

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

    /**
     * Set Publisher ID
     */
    public function setPublisherId($publisher_id) {
        $this->publisher_id = $publisher_id;
    }

    /**
     * Make API request to AdMob
     */
    private function makeRequest($method, $endpoint, $data = null) {
        $url = $this->api_endpoint . $endpoint;

        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $this->access_token,
                'Content-Type: application/json',
                'Accept: application/json'
            ]
        ]);

        if ($data && ($method === 'POST' || $method === 'PUT')) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }

        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($response === false) {
            return ['error' => 'cURL Error', 'http_code' => 0];
        }

        return [
            'data' => json_decode($response, true),
            'http_code' => $http_code
        ];
    }

    /**
     * Get account information
     */
    public function getAccountInfo() {
        $response = $this->makeRequest('GET', '/accounts');
        return $response;
    }

    /**
     * Get specific publisher account details
     */
    public function getPublisherAccount($account_id) {
        $response = $this->makeRequest('GET', '/accounts/' . $account_id);
        return $response;
    }

    /**
     * List all apps in account
     */
    public function listApps($account_id) {
        $response = $this->makeRequest('GET', '/accounts/' . $account_id . '/apps');
        return $response;
    }

    /**
     * Get specific app details
     */
    public function getAppDetails($account_id, $app_id) {
        $response = $this->makeRequest('GET', '/accounts/' . $account_id . '/apps/' . $app_id);
        return $response;
    }

    /**
     * List all ad units
     */
    public function listAdUnits($account_id, $app_id = null) {
        if ($app_id) {
            $endpoint = '/accounts/' . $account_id . '/adUnits?filter=app.appId=' . $app_id;
        } else {
            $endpoint = '/accounts/' . $account_id . '/adUnits';
        }

        $response = $this->makeRequest('GET', $endpoint);
        return $response;
    }

    /**
     * Get specific ad unit details
     */
    public function getAdUnitDetails($account_id, $ad_unit_id) {
        $response = $this->makeRequest('GET', '/accounts/' . $account_id . '/adUnits/' . $ad_unit_id);
        return $response;
    }

    /**
     * Generate network report
     */
    public function generateNetworkReport($account_id, $start_date, $end_date, $dimensions = [], $metrics = []) {
        $request = [
            'dateRange' => [
                'startDate' => [
                    'year' => (int)substr($start_date, 0, 4),
                    'month' => (int)substr($start_date, 5, 2),
                    'day' => (int)substr($start_date, 8, 2)
                ],
                'endDate' => [
                    'year' => (int)substr($end_date, 0, 4),
                    'month' => (int)substr($end_date, 5, 2),
                    'day' => (int)substr($end_date, 8, 2)
                ]
            ],
            'dimensions' => $dimensions ?: ['DATE'],
            'metrics' => $metrics ?: ['IMPRESSIONS', 'CLICKS', 'ESTIMATED_EARNINGS']
        ];

        $response = $this->makeRequest('POST', '/accounts/' . $account_id . '/networkReports:generate', $request);
        return $response;
    }

    /**
     * Generate mediation report
     */
    public function generateMediationReport($account_id, $start_date, $end_date, $dimensions = [], $metrics = []) {
        $request = [
            'dateRange' => [
                'startDate' => [
                    'year' => (int)substr($start_date, 0, 4),
                    'month' => (int)substr($start_date, 5, 2),
                    'day' => (int)substr($start_date, 8, 2)
                ],
                'endDate' => [
                    'year' => (int)substr($end_date, 0, 4),
                    'month' => (int)substr($end_date, 5, 2),
                    'day' => (int)substr($end_date, 8, 2)
                ]
            ],
            'dimensions' => $dimensions ?: ['DATE', 'AD_SOURCE'],
            'metrics' => $metrics ?: ['IMPRESSIONS', 'CLICKS', 'ESTIMATED_EARNINGS']
        ];

        $response = $this->makeRequest('POST', '/accounts/' . $account_id . '/mediationReports:generate', $request);
        return $response;
    }

    /**
     * Generate campaign report
     */
    public function generateCampaignReport($account_id, $start_date, $end_date, $campaign_id = null) {
        $request = [
            'dateRange' => [
                'startDate' => [
                    'year' => (int)substr($start_date, 0, 4),
                    'month' => (int)substr($start_date, 5, 2),
                    'day' => (int)substr($start_date, 8, 2)
                ],
                'endDate' => [
                    'year' => (int)substr($end_date, 0, 4),
                    'month' => (int)substr($end_date, 5, 2),
                    'day' => (int)substr($end_date, 8, 2)
                ]
            ],
            'dimensions' => ['DATE', 'APP', 'AD_UNIT'],
            'metrics' => ['IMPRESSIONS', 'CLICKS', 'ESTIMATED_EARNINGS', 'MATCH_RATE']
        ];

        if ($campaign_id) {
            $request['filter'] = 'campaign.id=' . $campaign_id;
        }

        $response = $this->makeRequest('POST', '/accounts/' . $account_id . '/campaignReports:generate', $request);
        return $response;
    }

    /**
     * Get AdSense linked sites (publishers)
     */
    public function getAdSensePublishers() {
        $response = $this->makeRequest('GET', '/accounts');
        return $response;
    }
}

?>