<?php

use \Slim\Http\Request as Request;
use \Slim\Http\Response as Response;
use App\Model\Cliente;
$app->get('/clientes[/{id}]', function (Request $request,  Response $response, $args) {

    if (isset($args['id'])){
        $result = Cliente::find($args['id']);
        $response->getBody()->write(Cliente::toJSON($result));
        return $response;
    }else{
        $uptate = $request->getHeader("update-cli")[0];
        if($uptate=="none")
            $objects = Cliente::all();
        else
            $objects = Cliente::all(array("conditions" => "cli_update > '".$uptate."'"));
        $response->getBody()->write(Cliente::toJSON($objects));
        return $response->withAddedHeader('update-cli', date('Y-m-d '.'00:00:00'));
    }
});

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

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

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