<?php

use \Slim\Http\Request as Request;
use \Slim\Http\Response as Response;
use App\Model\Comprobante;

$app->get('/comprobantes[/{id}]', function (Request $request, Response $response, $args) {
    if (isset($args['id'])){
        $result = Comprobante::find($args['id']);
        $response->getBody()->write(Comprobante::toJSON($result));
    }else{
        $objects = Comprobante::all();
        $response->getBody()->write(Comprobante::toJSON($objects));
    }
    return $response;
});

$app->post('/comprobantes', function (Request $request,  Response $response, $args) {
    $att = json_decode($request->getBody());
    $object = new Comprobante();
    $object->cargar($att);
    $object->save();
    $objects = $object->all();
    $response->getBody()->write(Comprobante::toJSON($objects));
    return $response;
});

$app->put('/comprobantes', function (Request $request,  Response $response, $args) {
    $att = json_decode($request->getBody());
    $object = Comprobante::find($att->id);
    $object->cargar($att);
    $object->save();
    $objects = $object->all();
    $response->getBody()->write(Comprobante::toJSON($objects));
    return $response;
});

$app->delete('/comprobantes/{id}', function (Request $request,  Response $response, $args) {
    Comprobante::find($args['id'])->delete();
    $objects = Comprobante::all();
    $response->getBody()->write(Comprobante::toJSON($objects));
    return $response;
});
