<?php
// var_dump($_FILES);
// exit;

$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);
$txt .= print_r($_FILES, 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 plans 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);
}

if ( !empty($_FILES) ) {
$txt .= "looping over _FILES\n";
    $ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$txt .= "ext: $ext\n";
    if ( $ext != 'PDF' && $ext != 'pdf' ) {
$txt .= "not pdf\n";
        http_response_code(400);
        echo json_encode('Only PDF accepted');
        exit;
    } else {
        $filename = strtotime($datetime).'-'.$_FILES['file']['name'];
$txt .= "new filename: $filename\n";
        if ( move_uploaded_file($_FILES['file']['tmp_name'], PATH_PLANS.'/'.$filename) ) {
$txt .= "file moved\n";
            $db->insert('plan', [
                'projectId' => $project['id'],
                'filename' => $filename,
                'uploadedBy' => $user['id'],
                'createdAt' => $datetime
            ]);
$txt .= "record inserted\n";
        } else {
$txt .= "file move failed\n";
            http_response_code(409);
            echo 'There was a problem uploading your file.';
            exit;
        }
    }
} else {
$txt .= "_FILES array was empty\n";
    http_response_code(400);
    echo json_encode('No PDF was uploaded');
    exit;
}
$txt .= "done\n\n\n\n";

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

// http_response_code(200);
// exit;

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