<?php
/**
 * PayPal IPN Router (S6 / MU)
 * custom = userid|SITE|REALM|PACKID|IP|SIGNATURE
 */

function nexora_router_log_value($value) {
    $value = preg_replace('/[\x00-\x1F\x7F]+/', ' ', (string)$value);
    return substr($value, 0, 160);
}

$routerLog = dirname(__DIR__) . '/includes/logs/ipn_router.log';
@file_put_contents($routerLog,
    '['.date('c').'] HIT ip=' . nexora_router_log_value(isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '') .
    ' status=' . nexora_router_log_value(isset($_POST['payment_status']) ? $_POST['payment_status'] : '') .
    ' txn_id=' . nexora_router_log_value(isset($_POST['txn_id']) ? $_POST['txn_id'] : '') . PHP_EOL,
    FILE_APPEND
);

$targets = [
    'S6' => 'https://s6.nexoravenetworks.com/api/paypal.php',
    'MU' => 'https://munexorave.com/api/paypal.php',
];

$custom = isset($_POST['custom']) ? (string)$_POST['custom'] : '';
$parts  = explode('|', $custom);

$site = '';
if (count($parts) >= 2) {
    $site = strtoupper(trim($parts[1]));
}

if (!isset($targets[$site])) {
    @file_put_contents($routerLog,
        '['.date('c').'] ERROR unknown SITE.' . PHP_EOL,
        FILE_APPEND
    );
    header('HTTP/1.1 200 OK');
    echo 'OK';
    exit;
}

$data = http_build_query($_POST);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $targets[$site]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
curl_exec($ch);
curl_close($ch);

header('HTTP/1.1 200 OK');
echo 'OK';
