<?php

# Turn off switch
$state = json_decode(file_get_contents("state.json"), true);
$state["switch_open"] = 0;
file_put_contents("state.json", json_encode($state));

# Create unique copy of the complete level
$sub = uniqid();
mkdir($sub);
foreach (glob("*.*") as $f)
    copy($f, $sub."/".$f);
copy(".htaccess", $sub."/.htaccess");
    
# Patch paths of the copied maps
$data = file_get_contents("$sub"."/room_open.json");
$data = str_replace("..\/..", "..\/..\/..", $data);
file_put_contents("$sub"."/room_open.json", $data);

$data = file_get_contents("$sub"."/room_closed.json");
$data = str_replace("..\/..", "..\/..\/..", $data);
file_put_contents("$sub"."/room_closed.json", $data);

# Load current level and patch exits to target the copy
$data = file_get_contents("room_open.json");
$data = str_replace("room.php#", "$sub"."/"."room.php#", $data);

// Patch php filenames with timestamps to defeat cache
//   destination.php --> destination.number.php
$tstamp = round(microtime(true)*100);  # 0.01 sec resolution
$data = str_replace(".php", ".".$tstamp.".php", $data);

header('Content-type: application/json');
echo($data);
exit;
    
    
?>