<?php

# Turn off switch
$state = json_decode(file_get_contents("state.json"), true);
$state["switch"] = 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");
    
// Replace level worker
copy("01_sub.php", $sub."/"."01.php");

# Patch paths of the copied level
$data = file_get_contents("$sub"."/01.json");
$data = str_replace("..\/..", "..\/..\/..", $data);
file_put_contents("$sub"."/01.json", $data);

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

# Load current level and patch exits to target the copy
$data = file_get_contents("01.json");
$data = str_replace("01.php#", "$sub"."/"."01.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;
    
    
?>