<?php
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405); 
    echo json_encode(['error' => 'Method not allowed. Only POST requests are accepted by this proxy.']);
    exit;
}

if (!isset($_POST['player_tag'])) {
    http_response_code(400); 
    echo json_encode(['error' => 'Player tag is required.']);
    exit;
}
$playerTag = $_POST['player_tag'];

$cleanedPlayerTag = ltrim($playerTag, '#');
$encodedPlayerTag = urlencode($cleanedPlayerTag);

$externalApiUrl = "https://clashapi.colinschmale.dev/v1/players/%23{$encodedPlayerTag}";
$externalApiKey = 'vAggXnhfhGdDoZDmvb2UBZTm';

$curlHeaders = [
    'Accept: */*',
    'Accept-Language: en-US,en;q=0.9',
    'Connection: keep-alive',
    'Origin: https://www.warreport.app',
    "apikey: {$externalApiKey}",
    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36',
    'Sec-Fetch-Dest: empty',
    'Sec-Fetch-Mode: cors',
    'Sec-Fetch-Site: cross-site',
    'sec-ch-ua: "Google Chrome";v="125", "Chromium";v="125", "Not.A/Brand";v="24"',
    'sec-ch-ua-mobile: ?0',
    'sec-ch-ua-platform: "Windows"'
];


$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $externalApiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_HTTPHEADER, $curlHeaders);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if (curl_errno($ch)) {
    http_response_code(500);
    echo json_encode([
        'error' => 'Proxy Error', 
        'reason' => 'Failed to connect to the target API: ' . curl_error($ch)
    ]);
    curl_close($ch);
    exit;
}

curl_close($ch);

http_response_code($httpCode);
echo $response;

?>
