<?php
    /**
     * Profile uploader script.
     *
     * Exposes an API to save a run to the database.
     * Reads post data and calls the log-profile.py script.
     * It also saves the data to a JSON file in the da directory.
     * Mandatory POST parameters are:
     *  - data: Received JSON file after a run.
     *  - key: User API key.
     *
     * @category API
     */

    namespace swdb;

    $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"] . "/../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;
?>

