<?php
/**
 * Generic Insurance Bridge - proxy.php (Sadece Canlı Ortamlar)
 */

header('Content-Type: application/json; charset=utf-8');
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(204); exit; }

function out($status, $data) {
    http_response_code($status);
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

// Sadece Canlı (Production) Sunucu Adresleri
$allowedHosts = [
    'ws.ankarasigorta.com.tr',        // Ankara Sigorta Canlı 
    'adaauth.dogasigorta.com',       // Doğa Sigorta Token Sunucusu
    'saglik.dogasigorta.com',        // Doğa Sigorta Sağlık Servisleri
    'api.aksigorta.com.tr',          // Aksigorta Canlı
    'saglik.turknippon.com',            // Turk Nippon Canlı
    'wsgateway.mapfre.com.tr',       // Mapfre Canlı Gateway [cite: 2669, 3464, 3475]
    'uretimbkm.mapfre.com.tr',       // Mapfre Canlı Üretim [cite: 2669]
    'api.unicosigorta.com.tr',       // Unico Sigorta Canlı
    'api.allianz.com.tr'            //Allianz Canlı
];

$targetUrl = $_GET['url'] ?? '';
$debug     = isset($_GET['debug']) && $_GET['debug'] == '1';

if (!$targetUrl) {
    out(400, [
        'error' => 'url parametresi zorunludur',
        'usage' => 'proxy.php?url=https://<host>/<path>',
        'allowed_hosts' => $allowedHosts,
    ]);

}

$parsed = parse_url($targetUrl);
if (!$parsed || empty($parsed['host']) || empty($parsed['scheme'])) {
    out(400, ['error' => 'Gecersiz url', 'url' => $targetUrl]);
}

// Güvenlik: Sadece listedeki CANLI host'lara izin ver
if (!in_array($parsed['host'], $allowedHosts, true)) {
    out(403, [
        'error' => 'Güvenlik Engeli: Host whitelist disinda', 
        'host' => $parsed['host'], 
        'mesaj' => 'Test ortami adreslerini kullaniyor olabilirsiniz.'
    ]);
}

if ($parsed['scheme'] !== 'https' && $parsed['scheme'] !== 'http') {
    out(400, ['error' => 'Sadece http/https destekleniyor']);
}

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

$incomingHeaders = function_exists('getallheaders') ? getallheaders() : [];
$forward = [];
$blocked = ['host', 'content-length', 'connection', 'accept-encoding', 'x-forwarded-for', 'x-real-ip', 'cf-connecting-ip', 'cf-ray', 'cf-visitor'];
foreach ($incomingHeaders as $name => $value) {
    $lower = strtolower($name);
    if (in_array($lower, $blocked, true)) continue;
    $forward[] = $name . ': ' . $value;
}

if (!preg_grep('/^content-type:/i', $forward) && $body !== '') {
    $forward[] = 'Content-Type: application/json';
}
// Make.com'dan gelen X- ile baslayan ozel basliklari (X-ApiKey vb.) forward sepetine ekle
foreach (getallheaders() as $name => $value) {
    if (stripos($name, 'X-') === 0) {
        $forward[] = "$name: $value";
    }
}
$ch = curl_init($targetUrl);
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST  => $method,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HEADER         => false,
    CURLOPT_TIMEOUT        => 60,
    CURLOPT_HTTPHEADER     => $forward,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_SSL_VERIFYPEER => true,
    CURLOPT_SSL_VERIFYHOST => 2,
]);

if ($method !== 'GET' && $method !== 'HEAD') {
    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
}

$resp = curl_exec($ch);
$info = curl_getinfo($ch);
// PDF Kontrolü Başlangıcı
$contentType = isset($info['content_type']) ? $info['content_type'] : '';
if (strpos($contentType, 'application/pdf') !== false || strpos($contentType, 'octet-stream') !== false) {
    out(200, [
        "basarili" => true,
        "dosyaTipi" => "pdf",
        "pdfBase64" => base64_encode($resp)
    ]);
    exit;
}
// PDF Kontrolü Bitişi

$err  = curl_error($ch);
curl_close($ch);

if ($resp === false) {
    out(502, ['basarili' => false, 'mesaj' => 'cURL hatasi', 'detail' => $err]);
}

$upstreamStatus = (int)$info['http_code'];
$parsedJson     = json_decode($resp, true);

// Debug modu aktifse detaylari don
if ($debug) {
    out(200, [
        'debug' => true,
        'request' => ['url' => $targetUrl, 'method' => $method, 'headers' => $forward],
        'response' => ['status' => $upstreamStatus, 'body' => $parsedJson ?: $resp]
    ]);
}

// JSON degilse sar ve gonder (Make.com hatasini onler)
if (!is_array($parsedJson)) {
    out($upstreamStatus ?: 502, [
        'basarili' => false,
        'mesaj' => 'Sunucu JSON dondurmedi',
        'raw_response' => substr($resp, 0, 10000)
    ]);
}

// Temiz JSON cevap
http_response_code($upstreamStatus);
echo $resp;
