<?php
    global $path;
    $status = 200;
    if (isset($_POST["data"]) && isset($_POST["key"])){
        $data = $_POST["data"];
        $key = $_POST["key"];
        if (json_decode($data) === null){
            error_log("ERROR: API v1 log-profile: Invalid JSON");
            $status = 400;
        }
        else{
            $json = json_decode($data);
            $winfo = $json->{"wizard_info"};
            $uname = $winfo->{"wizard_name"};
            $uid = $winfo->{"wizard_id"};
            $dtime = (new DateTime())->format('Y-m-dTH:i:s');
            $fname = ($_SERVER["DOCUMENT_ROOT"] . "/../application/data/profile_" . $uid . "_" . $uname . "_" . $dtime . ".json");
            file_put_contents($fname, $data);
            $cmd = $_SERVER["DOCUMENT_ROOT"] . "/../application/bin/log-profile.py " . $key . " " . $fname;
            $out = [];
            $ret = 0;
            exec($cmd, $out, $ret);
            if ($ret != 0){
                error_log("ERROR: API v1 log-profile exited with status: " . $ret);
                error_log("====================");
                error_log("|| SCRIPT OUTPUT: ||");
                error_log("===============================================================================");
                foreach($out as $line){
                    error_log("|| " . $line);
                }
                error_log("===============================================================================");
                $status = 400;
            }
        }
    }
    else{
        error_log("ERROR: API v1 log-profile: Invalid JSON");
        $status = 400;
    }
    http_response_code($status);
    return $status;
?>
