<?php
// === DEBUG MODU AÇIK ===
error_reporting(E_ALL);
ini_set('display_errors', '0');
ini_set('log_errors', '1');
ini_set('error_log', '/tmp/proxy-debug.log');

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: *');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

$ALLOWED_HOSTS = [
    'tss.ankarasigorta.com.tr',
    'webservice.ankarasigorta.com.tr',
    'ws.ankarasigorta.com.tr',
    'adaauth.dogasigorta.com',
    'portal.dogasigorta.com',
    'saglik.dogasigorta.com',
    'api.aksigorta.com.tr',
    'testapi.aksigorta.com.tr',
    'api.unicosigorta.com.tr',
    'saglik.turknippon.com',
    'wsgateway.mapfre.com.tr',
    'uretimbkm.mapfre.com.tr',
    'api.allianz.com.tr',
];

$target = $_GET['url'] ?? '';
error_log("REQUEST target=$target");

if ($target === '') {
    http_response_code(400);
    header('Content-Type: application/json');
    echo json_encode(['error' => 'url parametresi zorunludur', 'allowed_hosts' => $ALLOWED_HOSTS]);
    exit;
}

$parsed = parse_url($target);
if (!$parsed || empty($parsed['host'])) {
    http_response_code(400);
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Gecersiz URL', 'url' => $target]);
    exit;
}

$host = strtolower($parsed['host']);
if (!in_array($host, $ALLOWED_HOSTS, true)) {
    http_response_code(403);
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Host whitelist disi', 'host' => $host, 'allowed_hosts' => $ALLOWED_HOSTS]);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$body   = file_get_contents('php://input');

$forward_headers = [];
$skip = ['host', 'content-length', 'x-forwarded-for', 'x-real-ip', 'connection', 'accept-encoding'];
$incoming = function_exists('getallheaders') ? getallheaders() : [];
foreach ($incoming as $name => $value) {
    if (in_array(strtolower($name), $skip, true)) continue;
    $forward_headers[] = $name . ': ' . $value;
}

$ch = curl_init($target);
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST  => $method,
    CURLOPT_POSTFIELDS     => ($method !== 'GET' ? $body : null),
    CURLOPT_HTTPHEADER     => $forward_headers,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HEADER         => true,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_FOLLOWLOCATION => false,
    CURLOPT_TIMEOUT        => 90,
]);

$response     = curl_exec($ch);
$http_code    = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$header_size  = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
$err          = curl_error($ch);
$errno        = curl_errno($ch);
curl_close($ch);

error_log("RESPONSE http_code=$http_code errno=$errno err=$err ct=$content_type");

if ($response === false) {
    http_response_code(502);
    header('Content-Type: application/json');
    echo json_encode(['error' => 'curl_error', 'errno' => $errno, 'detail' => $err, 'target' => $target]);
    exit;
}

$response_body = substr($response, $header_size);
error_log("BODY_LEN=" . strlen($response_body) . " FIRST_500=" . substr($response_body, 0, 500));

if ($content_type && (strpos($content_type, 'application/pdf') !== false || strpos($content_type, 'octet-stream') !== false)) {
    http_response_code(200);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['basarili' => true, 'dosyaTipi' => 'pdf', 'pdfBase64' => base64_encode($response_body)]);
    exit;
}

http_response_code($http_code);
if ($content_type) {
    header('Content-Type: ' . $content_type);
}
echo $response_body;
