<?php

use \Slim\Http\Request as Request;
use \Slim\Http\Response as Response;
use App\Model\Config;
use App\Model\Canal;

$app->get('/canales', function (Request $request, Response $response, $args) {
    $result = Config::find('all', array('select' => 'cfg_canal1 as canal1, cfg_canal2 as canal2, cfg_canal3 as canal3'));
    $canales = [];
    if(sizeof($result)>0 && $result[0]->canal1!=null && trim($result[0]->canal1)!="") {
        if(trim($result[0]->canal1)!="") $canales[] = Canal::toArray(Canal::find($result[0]->canal1),1);
        if(trim($result[0]->canal2)!="") $canales[] = Canal::toArray(Canal::find($result[0]->canal2),2);
        if(trim($result[0]->canal3)!="") $canales[] = Canal::toArray(Canal::find($result[0]->canal3),3);
    }else{
        $canales = Canal::toArray(Canal::all());
    }
    $response->getBody()->write(json_encode($canales));
    return $response;
});

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

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

$app->delete('/canales', function (Request $request,  Response $response, $args) {
    Canal::connection()->query("TRUNCATE TABLE mensatic");
    return $response;
});
