<?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');
header('Pragma: no-cache');

if (!isset($_GET['date'])) {
    echo json_encode([]);
    exit;
}

$dateParam = $_GET['date'] === '2' ? 'yesterday' : 'today';
$conversionDate = date('Y-m-d', strtotime($dateParam));

$topClickId = '';

try {
    $stmt = $pdo->prepare(
        'SELECT click_id FROM leadreport WHERE conversion_date = :date
         GROUP BY click_id ORDER BY SUM(CAST(payout AS DECIMAL(18,2))) DESC LIMIT 1',
    );
    $stmt->execute(['date' => $conversionDate]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if (is_array($row)) {
        $topClickId = (string) ($row['click_id'] ?? '');
    }
} catch (Throwable $e) {
    echo json_encode([]);
    exit;
}

if ($topClickId === '') {
    echo json_encode([]);
    exit;
}

$escaped = htmlspecialchars(strtoupper($topClickId), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
$html = '<strong><img style="width:20px;height:20px;vertical-align:middle;" src="' . statH(statAssetUrl('/dist/fox.svg')) . '">'
    . $escaped . '</strong>';

echo json_encode([['click_id' => $html]], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
