<?php



require_once '../class/Document.php';
require_once '../class/Security.php';

$app->get('/documents', function ($request, $response,$args) {
    $db = Db::getInstance();
    $conn = $db->getConn();
    $userToken = $request->getHeader("Authorization")[0];
    $se = new Security();
    $userId = $se->decode($userToken);

    $document = new Document($conn, $userId);
    $res = $document->getDocuments($request->getParams());
    
     //return response
     $response->withHeader('Content-Type', 'application/json');
     $response->write(json_encode($res));
     return $response;

    //disconnect connection
    $conn->close();
});


$app->post('/documents', function ($request, $response,$args) {
    $db = Db::getInstance();
    $conn = $db->getConn();
    $userToken = $request->getHeader("Authorization")[0];
    $se = new Security();
    $userId = $se->decode($userToken);

    $document = new Document($conn, $userId);
    $res = $document->saveDocument($request->getParsedBody());
    
     //return response
     $response->withHeader('Content-Type', 'application/json');
     $response->write(json_encode($res));
     return $response;

    //disconnect connection
    $conn->close();
});

$app->delete('/documents', function ($request, $response,$args) {
    $db = Db::getInstance();
    $conn = $db->getConn();
    $userToken = $request->getHeader("Authorization")[0];
    $se = new Security();
    $userId = $se->decode($userToken);

    $document = new Document($conn, $userId);
    $res = $document->deleteDocument($request->getParams());
    
     //return response
     $response->withHeader('Content-Type', 'application/json');
     $response->write(json_encode($res));
     return $response;

    //disconnect connection
    $conn->close();
});