<?php

# Structure on the server (http://rickardlab.ucsd.edu/):
#
#  This file:
#   rickardlab.ucsd.edu/studies/save.php
#  Data gets saved in:
#    rickardlab.ucsd.edu/study/data/{experimenter}/{experimentName}
#  Each subject gets saved using their id:
#	 rickardlab.ucsd.edu/study/data/{experimenter}/{experimentName}/{id}.txt
#
# Warning:
# Note that this means that anybody can POST to this file directly and
# create files on your server. E.g., if somebody sends data to the URL
# rickardlab.ucsd.edu/study/save.py?id=hello&experimentName=tim&curData=you+da+bomb,
# that will create a file on the server in the directory "data". So it isn't the
# safest thing in the world. It won't work if they load this directly in their
# browser because it needs to be POSTed and browsers use GET, but otherwise
# could be problematic.

# How to make this file work:
# Make sure php is enabled on your server. That's it.
# You might have to make your "data" folder writeable to the world:
# in terminal:
# sudo chmod -R 777 data 
# or via connecting to your server in some scpy client (like Transmit for app)
#

# You *should not* create the experimenter or experiment folders in advance.
# If you do, it might fail because the web server script won't have write
# access to those directories unless you set their permissions to 777.


// ------------------
// CORS HEADERS
// ------------------
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// ------------------
// HANDLE POST DATA
// ------------------

$experimenter = $_POST['experimenter'] ?? 'unknown_experimenter';
$experimentName = $_POST['experimentName'] ?? 'unknown_experiment';
$id = $_POST['id'] ?? uniqid("anon_");
$curData = $_POST['curData'] ?? '';

// Optional basic sanitization
$experimenter = preg_replace("/[^a-zA-Z0-9_\-]/", "", $experimenter);
$experimentName = preg_replace("/[^a-zA-Z0-9_\-]/", "", $experimentName);
$id = preg_replace("/[^a-zA-Z0-9_\-]/", "", $id);

// Create folder path
$dir = "data/$experimenter/$experimentName";
if (!file_exists($dir)) {
    mkdir($dir, 0777, true);  // Creates nested directories
}

// Save data to file
$filename = "$dir/$id.txt";
file_put_contents($filename, $curData);

// Send JSON response
header("Content-Type: application/json");
echo json_encode([
    "status" => "success",
    "file" => $filename
]);
?>


