<?php
error_reporting(0);
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require '../vendor/autoload.php';

$app = new \Slim\App;

$container = $app->getContainer();


$container['db'] = function ($c) {
    $db = $c['settings']['db'];
    $pdo = new PDO('sqlite:db.sqlite3');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    $pdo-> exec("CREATE TABLE IF NOT EXISTS `simulations` (
	`id`	INTEGER PRIMARY KEY AUTOINCREMENT,
	`timestamp`	INTEGER,
	`status`	VARCHAR NOT NULL DEFAULT 'scheduled',
	`token`	VARCHAR NOT NULL,
	`username`	VARCHAR NOT NULL,
	`topo_xml`	TEXT NOT NULL DEFAULT '',
	`sessionname`	VARCHAR,
	`repeat_interval`	INTEGER,
	`repeat_count`	INTEGER NOT NULL DEFAULT 0
);");    
    return $pdo;
};

$container['errorHandler'] = function ($container) {
    return function ($request, $response, $exception) use ($container) {
       
        return $container['response']->withStatus(500)
                             ->withHeader('Content-Type', 'text/html')
                             ->withJson(["statusText"=>$exception->getMessage()]);
    };
};




$app->get('/plannedsims/{id}', function (Request $request, Response $response) {
    $id = $request->getAttribute('id');
    $query = $this->db->prepare('SELECT * FROM simulations WHERE id = ? LIMIT 1;');
 
    $array = array($id);
    $query->execute($array);
    $result = $query->fetch();
    if ($result)
        return $response->withJson();
    
});

$app->delete('/plannedsims/{id}', function (Request $request, Response $response) {
    $id = $request->getAttribute('id');
    $query = $this->db->prepare('DELETE FROM simulations WHERE id = ?;');
 
    $array = array($id);
    $query->execute($array);

    return $response->withJson(array("statusText"=>"Successfully deleted simulation with id ".$id."."));
});


$app->get('/plannedsims', function (Request $request, Response $response ) {
    $data=$this->db->query("SELECT * FROM simulations;")->fetchAll();
    
    $newResponse = $response->withJson($data);
    return $newResponse;
});


$app->post('/plannedsims/new', function (Request $request, Response $response) {
        $params = $request->getQueryParams();
        $sessionName = $params["session"];
        $timestamp = $params["timestamp"];
        $token = $params["token"];
        $username = $params["username"];
        $repeat = $params["repeat"];
        
        switch ($repeat){
            case "daily":
                $repeat = strtotime('+1 day',0);
                break;
            case "weekly":
                $repeat = strtotime('1 week',0);
                break;
            default:
                $repeat = 0;
                break;
        }
        if (!is_numeric($repeat) && $repeat <=0)
                $repeat = null;
    
        $XML = $request->getBody()->getContents();
        if ($repeat != 0)
            $sth = $this->db->prepare('INSERT INTO simulations (timestamp, topo_xml,sessionname,token,username,repeat_interval,repeat_count,status) VALUES (?, ?, ?,?,?,?,0,"repeating");');
        else
            $sth = $this->db->prepare('INSERT INTO simulations (timestamp, topo_xml,sessionname,token,username,repeat_interval,repeat_count) VALUES (?, ?, ?,?,?,?,0);');
        $sth->execute([intval($timestamp),$XML,$sessionName,$token,$username,$repeat]);    
        
        return $response->withJson(array("statusText"=>"Successfully added simulation startup."));
});
$app->run();