<?php
$datetime = date("Y-m-d H:i:s");
$txt  = "\n$datetime - ".$_SERVER['PHP_SELF']."\n";
$txt .= print_r($user, true);
$txt .= print_r($_POST, true);

//make sure user is superAdmin
if ( !$user['superAdmin'] ) {
$txt .= "403 not superAdmin\n";

    http_response_code(403);
    echo json_encode('You do not have permission to upload models to this project');
    exit;
}

//validate project id
if ( !$project = $db->row("SELECT * FROM project WHERE id = ?", $_POST['projectId']) ) {
$txt .= "400 invalid project\n";

    http_response_code(400);
    echo json_encode('Invalid project ID');
    exit;
} else {
$txt .= print_r($project, true);
}
//hack to make sure $userProject in template/models.php is populated with the project data
$userProject = $project;

if ( !$modelId = $_POST['modelId'] ) {
    $txt .= "400 no model id\n";

    http_response_code(400);
    echo json_encode('Invalid model ID');
    exit;
}

$db->insert('model', [
    'projectId' => $project['id'],
    'sketchfabId' => $modelId,
    'uploadedBy' => $user['id'],
    'createdAt' => $datetime
]);
$txt .= "record inserted\n";
$txt .= "done\n\n\n\n";

$file = fopen(PATH_LOGS.'/btb.add-model.log', "a");
fwrite($file, $txt);
fclose($file);

// http_response_code(200);
// exit;

$models = $db->run("SELECT * FROM model WHERE projectId = ? ORDER BY createdAt DESC", $project['id']);
include '../template/models.php';