<?php
// api.php
date_default_timezone_set('Asia/Jakarta');

// Simpan multi API key dan client ID di sini
$apiCredentials = [
    ['clientId' => 2222, 'apiKey' => '22222'],
    ['clientId' => 11111, 'apiKey' => '1111111'],
    ['clientId' => 243870, 'apiKey' => '4a6c1eb51367eb3784f21855006eb74011452a430e5194eaf16f93610dff55a7'],
];

// Ambil token dari iMonetizeIt berdasarkan index API key
function getAuthToken($index = 0) {
    global $apiCredentials;
    if (!isset($apiCredentials[$index])) return null;

    $url = 'https://api.imonetizeit.com/v1/auth/session';
    $apiKey   = $apiCredentials[$index]['apiKey'];
    $clientId = $apiCredentials[$index]['clientId'];

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode(['client_id'=>$clientId,'api_key'=>$apiKey]),
        CURLOPT_HTTPHEADER     => ['Content-Type: application/json','Accept: application/json'],
        CURLOPT_RETURNTRANSFER => true,
    ]);
    $resp = curl_exec($ch);
    curl_close($ch);

    $data = json_decode($resp, true);
    if (!isset($data['access_token'])) {
        return null;
    }
    return $data['access_token'];
}

// Fungsi ambil statistik per API key dengan parameter index API
function getStatisticsSingle($startDate, $endDate, $apiIndex = 0) {
    $token = getAuthToken($apiIndex);
    if (!$token) return ['data' => []];

    $url = 'https://api.imonetizeit.com/v1/statistics/sm'
         . '?start_date=' . $startDate
         . '&end_date=' . $endDate
         . '&segments[]=smartlink'
         . '&timezone=%2B00%3A00'
         . '&include_archived=1'
         . '&limit=1000';

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_HTTPHEADER     => ['Authorization: Bearer ' . $token],
        CURLOPT_RETURNTRANSFER => true,
    ]);
    $resp = curl_exec($ch);
    curl_close($ch);

    $data = json_decode($resp, true)['data'] ?? [];

    foreach ($data as &$row) {
        $row['unique'] = isset($row['unique']) ? (int)$row['unique'] :
                         (isset($row['unigue']) ? (int)$row['unigue'] :
                         (isset($row['uniques']) ? (int)$row['uniques'] : 0));
        $row['clicks']  = isset($row['clicks']) ? (int)$row['clicks'] : 0;
        $row['payouts'] = isset($row['payouts']) ? (float)$row['payouts'] : 0.0;
        $row['leads']   = isset($row['leads']) ? (int)$row['leads'] : 0;
        $row['visits']  = isset($row['visits']) ? (int)$row['visits'] : 0;
    }
    unset($row);

    return ['data' => $data];
}

// Fungsi utama: ambil statistik dari semua API key dan gabung hasilnya
function getStatistics($startDate, $endDate) {
    global $apiCredentials;
    $allData = [];

    foreach ($apiCredentials as $index => $cred) {
        $result = getStatisticsSingle($startDate, $endDate, $index);
        if (!empty($result['data'])) {
            $allData = array_merge($allData, $result['data']);
        }
    }

    // Agregasi data agar data yang sama (smartlink + country) digabung
    $aggregated = [];

    foreach ($allData as $row) {
        $key = ($row['smartlink'] ?? '-') . '||' . ($row['country'] ?? '-');
        if (!isset($aggregated[$key])) {
            $aggregated[$key] = [
                'smartlink' => $row['smartlink'] ?? '-',
                'country'   => $row['country'] ?? '-',
                'visits'    => 0,
                'unique'    => 0,
                'clicks'    => 0,
                'leads'     => 0,
                'payouts'   => 0.0,
            ];
        }
        $aggregated[$key]['visits']  += $row['visits'];
        $aggregated[$key]['unique']  += $row['unique'];
        $aggregated[$key]['clicks']  += $row['clicks'];
        $aggregated[$key]['leads']   += $row['leads'];
        $aggregated[$key]['payouts'] += $row['payouts'];
    }

    return ['data' => array_values($aggregated)];
}

// Fungsi lain juga disesuaikan supaya pakai getStatistics baru (gabungan semua API key)
function getSmartlinkSummary($startDate, $endDate) {
    $stats = getStatistics($startDate, $endDate)['data'];
    $summary = [];

    foreach ($stats as $row) {
        $key = $row['smartlink'];
        if (!isset($summary[$key])) {
            $summary[$key] = [
                'smartlink' => $row['smartlink'],
                'visits'    => 0,
                'unique'    => 0,
                'clicks'    => 0,
                'leads'     => 0,
                'payouts'   => 0.0,
            ];
        }
        $summary[$key]['visits']  += $row['visits'];
        $summary[$key]['unique']  += $row['unique'];
        $summary[$key]['clicks']  += $row['clicks'];
        $summary[$key]['leads']   += $row['leads'];
        $summary[$key]['payouts'] += $row['payouts'];
    }

    return ['data' => array_values($summary)];
}

function getStatisticsByCountry($startDate, $endDate) {
    $stats = getStatistics($startDate, $endDate)['data'];
    $result = [];

    foreach ($stats as $row) {
        $result[] = [
            'smartlink' => $row['smartlink'],
            'country'   => $row['country'],
            'leads'     => $row['leads'],
            'payouts'   => $row['payouts'],
        ];
    }

    return ['data' => $result];
}

function getStatisticsGroupedBySmartlink($startDate, $endDate) {
    $stats = getStatistics($startDate, $endDate)['data'];
    $grouped = [];

    foreach ($stats as $row) {
        $smartlink = $row['smartlink'];
        $country = $row['country'] ?? '-';

        if (!isset($grouped[$smartlink])) {
            $grouped[$smartlink] = [
                'smartlink' => $smartlink,
                'visits'    => 0,
                'unique'    => 0,
                'clicks'    => 0,
                'leads'     => 0,
                'payouts'   => 0,
                'countries' => [],
            ];
        }

        $grouped[$smartlink]['visits']  += $row['visits'];
        $grouped[$smartlink]['unique']  += $row['unique'];
        $grouped[$smartlink]['clicks']  += $row['clicks'];
        $grouped[$smartlink]['leads']   += $row['leads'];
        $grouped[$smartlink]['payouts'] += $row['payouts'];

        if (!isset($grouped[$smartlink]['countries'][$country])) {
            $grouped[$smartlink]['countries'][$country] = [
                'country'  => $country,
                'visits'   => 0,
                'unique'   => 0,
                'clicks'   => 0,
                'leads'    => 0,
                'payouts'  => 0,
            ];
        }
        $grouped[$smartlink]['countries'][$country]['visits']  += $row['visits'];
        $grouped[$smartlink]['countries'][$country]['unique']  += $row['unique'];
        $grouped[$smartlink]['countries'][$country]['clicks']  += $row['clicks'];
        $grouped[$smartlink]['countries'][$country]['leads']   += $row['leads'];
        $grouped[$smartlink]['countries'][$country]['payouts'] += $row['payouts'];
    }

    foreach ($grouped as &$g) {
        $g['countries'] = array_values($g['countries']);
    }
    unset($g);

    return ['data' => array_values($grouped)];
}

function getLiveClicks() {
    $now = date('Y-m-d');
    $stats = getStatistics($now, $now)['data'];
    $clicks = 0;
    foreach ($stats as $row) {
        $clicks += $row['clicks'];
    }
    return $clicks;
}

function getLeadsByCountryAggregated($startDate, $endDate) {
    $stats = getStatistics($startDate, $endDate)['data'];
    $aggregated = [];

    foreach ($stats as $row) {
        $country = $row['country'] ?? '-';
        if ($row['leads'] > 0) {
            if (!isset($aggregated[$country])) {
                $aggregated[$country] = [
                    'country' => $country,
                    'leads'   => 0,
                    'payouts' => 0,
                ];
            }
            $aggregated[$country]['leads'] += $row['leads'];
            $aggregated[$country]['payouts'] += $row['payouts'];
        }
    }

    return array_values($aggregated);
}

function getMostClicksByCountry($startDate, $endDate) {
    $stats = getStatistics($startDate, $endDate)['data'];
    $clicksByCountry = [];

    foreach ($stats as $row) {
        $country = $row['country'] ?? 'N/A';
        $clicks = $row['clicks'] ?? 0;

        if (!isset($clicksByCountry[$country])) {
            $clicksByCountry[$country] = 0;
        }
        $clicksByCountry[$country] += $clicks;
    }

    arsort($clicksByCountry);
    $topCountry = key($clicksByCountry);
    $topClicks = current($clicksByCountry);

    return ['country' => $topCountry, 'clicks' => $topClicks];
}
