<?php

declare(strict_types=1);

include_once __DIR__ . '/../login.php';

/** @var PDO $pdo */
$pdo = require __DIR__ . '/../../connection_pdo.php';

header('Content-Type: application/json; charset=UTF-8');
header('X-Content-Type-Options: nosniff');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');

$lastId = (int) ($_GET['id'] ?? 0);

try {
    $sql  = 'SELECT id, click_id, country, payout, currency_symbol, network, traffic, conversion_date FROM leadreport WHERE id > :last_id';
    $stmt = $pdo->prepare($sql);
    $stmt->execute(['last_id' => $lastId]);
} catch (Throwable $e) {
    echo json_encode([]);
    exit;
}

$rows = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $country = strtoupper((string) ($row['country'] ?? ''));
    if ($country === 'INVALID IP ADDRESS.') {
        $country = '';
    }

    $rawClickId = (string) ($row['click_id'] ?? '');
    if (!mb_check_encoding($rawClickId, 'UTF-8')) {
        $rawClickId = mb_convert_encoding($rawClickId, 'UTF-8', 'ISO-8859-1');
    }
    $clickId = strtoupper($rawClickId);

    $rows[] = [
        'id'              => (int) $row['id'],
        'click_id'        => $clickId,
        'audio'           => statUrl('/realtime/asd.mp3'),
        'img'             => statAssetUrl('/dist/notify.svg'),
        'country'         => $country,
        'payout'          => ((string) ($row['currency_symbol'] ?? '$')) . number_format((float) ($row['payout'] ?? 0), 2),
        'network'         => strtoupper((string) ($row['network'] ?? '')),
        'traffic'         => strtoupper((string) ($row['traffic'] ?? '')),
        'conversion_date' => (string) ($row['conversion_date'] ?? ''),
    ];
}

echo json_encode($rows, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
