<?php
declare(strict_types=1);
$allow = ['trackingapi.trendemon.com','data.adxcel-ec2.com','bat.bing.com','insight.adsrvr.org','i.ytimg.com','www.googletagmanager.com','www.google.com'];
$u = (string)($_GET['u'] ?? '');
$p = parse_url($u);
if (!$p || empty($p['host']) || !in_array($p['host'], $allow, true)) { http_response_code(404); exit; }
$dir = '/var/www/_extcache';
if (!is_dir($dir)) { @mkdir($dir, 0775, true); }
$key = $dir . '/' . sha1($u);
$mimeKey = $key . '.type';
if (is_file($key) && filemtime($key) > time() - 86400) {
    header('Content-Type: ' . (is_file($mimeKey) ? trim((string)file_get_contents($mimeKey)) : 'application/octet-stream'));
    header('Cache-Control: public, max-age=3600');
    readfile($key); exit;
}
$ch = curl_init($u);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_TIMEOUT => 15,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_USERAGENT => $_SERVER['HTTP_USER_AGENT'] ?? 'Mozilla/5.0',
    CURLOPT_REFERER => 'https://monday.com/',
]);
$body = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE) ?: 'application/octet-stream';
curl_close($ch);
if ($code !== 200 || $body === false || $body === '') { http_response_code(204); exit; }
@file_put_contents($key, $body);
@file_put_contents($mimeKey, $type);
header('Content-Type: ' . $type);
header('Cache-Control: public, max-age=3600');
echo $body;
