<?php

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

date_default_timezone_set("Europe/London");

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

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

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

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

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

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

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

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

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

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

    $client = new Client($conn, $userId);
    $res = $client->updateClient($args['id'], $request->getParsedBody());
    
     //return response
     $response->withHeader('Content-Type', 'application/json');
     $response->write(json_encode($res));
     return $response;

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

?>