<?php

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

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

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

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

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