<?php
// api.recordsmaniashop.com -> Node proxy
$NODE_BASE = 'http://127.0.0.1:4000';

// /?path=/api/... veya .htaccess ile gelen path
$path = isset($_GET['path']) ? $_GET['path'] : '/';

$query = $_GET;
unset($query['path']);
$queryString = http_build_query($query);

$url = $NODE_BASE . $path . ($queryString ? ('?' . $queryString) : '');

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $_SERVER['REQUEST_METHOD']);

// ---------------------
// HEADER'LAR
// ---------------------
$headers = [];
if (function_exists('getallheaders')) {
    foreach (getallheaders() as $name => $value) {
        $lname = strtolower($name);

        // Host & Content-Length'i biz ayarlayacağız
        if ($lname === 'host') continue;
        if ($lname === 'content-length') continue;

        // multipart için Content-Type'ı da curl'e bırakacağız
        if (
            $lname === 'content-type' &&
            isset($_SERVER['CONTENT_TYPE']) &&
            stripos($_SERVER['CONTENT_TYPE'], 'multipart/form-data') === 0
        ) {
            continue;
        }

        $headers[] = $name . ': ' . $value;
    }
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

// ---------------------
// BODY / POSTFIELDS
// ---------------------
$method      = $_SERVER['REQUEST_METHOD'];
$contentType = isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '';

if (in_array($method, ['POST', 'PUT', 'PATCH'])) {

    // 1) multipart/form-data (file upload)
    if (stripos($contentType, 'multipart/form-data') === 0) {
        $postFields = [];

        // normal form alanları
        foreach ($_POST as $k => $v) {
            $postFields[$k] = $v;
        }

        // dosya alanları
        foreach ($_FILES as $fieldName => $fileInfo) {
            // tek dosya
            if (!is_array($fileInfo['name'])) {
                if ($fileInfo['error'] === UPLOAD_ERR_OK) {
                    $postFields[$fieldName] = new CURLFile(
                        $fileInfo['tmp_name'],
                        $fileInfo['type'] ?: 'application/octet-stream',
                        $fileInfo['name']
                    );
                }
            } else {
                // çoklu dosya (şimdilik gerekmez ama tam olsun)
                $count = count($fileInfo['name']);
                for ($i = 0; $i < $count; $i++) {
                    if ($fileInfo['error'][$i] === UPLOAD_ERR_OK) {
                        $postFields[$fieldName . "[$i]"] = new CURLFile(
                            $fileInfo['tmp_name'][$i],
                            $fileInfo['type'][$i] ?: 'application/octet-stream',
                            $fileInfo['name'][$i]
                        );
                    }
                }
            }
        }

        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
    }
    // 2) multipart değilse (JSON, x-www-form-urlencoded vs.)
    else {
        $input = file_get_contents('php://input');
        if ($input !== false && $input !== '') {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $input);
        }
    }
}

// ---------------------
// CEVABI NODE'DAN AL
// ---------------------
$response = curl_exec($ch);
if ($response === false) {
    $err = curl_error($ch);
    curl_close($ch);
    http_response_code(502);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['error' => 'Proxy error', 'detail' => $err]);
    exit;
}

$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$httpCode   = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$headerStr  = substr($response, 0, $headerSize);
$body       = substr($response, $headerSize);

curl_close($ch);

// ---------------------
// HEADER + BODY'Yİ CLIENT'A YOLLA
// ---------------------
http_response_code($httpCode);

foreach (explode("\r\n", $headerStr) as $headerLine) {
    if (stripos($headerLine, 'Content-Length:') === 0) continue;
    if (stripos($headerLine, 'Transfer-Encoding:') === 0) continue;
    if (stripos($headerLine, 'Connection:') === 0) continue;
    if ($headerLine === '') continue;
    header($headerLine, false);
}

echo $body;
