// /submitform/:id controller
// Submit form controller
// A form gets submitted and you get redirected where the form says
// TODO: Validate different field types
$app->post('/submitform/:id', function ($id) use($app) {
    $c = array();
    $parameters = array();
    $post_vars = $app->request()->post();
    // We grab the form
    $form = models\Form::find($id);
    // We grab its fields
    $fields = $form->fields;
    // We grab its contacts
    $contacts = $form->contacts;
    // We add a response
    $response = new models\ModelBuilder();
    $response::fromTable('responses_' . $id);
    $response->form_id = $id;
    // This is the array containing the form fields and their values
    // that will be passed to the twig template for them to be sent by e-mail
    $parameters['fields'] = array();
    // We have to iterate through the form fields
    foreach ($post_vars as $key => $var) {
        // We skip everything that is not a field
        // as field lengths for example
        if (substr($key, 0, 6) != 'field_') {
            continue;
        }
        $id_field = end(explode('_', $key));
        // We check that it's in the required format
        if ((int) $id_field != $id_field) {
    // We grab its fields (will be referenced by their ids on the responses)
    $fields = $form->fields;
    // We grab its responses
    $responses = models\ModelBuilder::fromTable('responses_' . $id_form)->all();
    $c['responses'] = $responses;
    $c['fields'] = $fields;
    $app->response()->header('Content-Type', 'text/csv');
    $app->response()->header('Content-Disposition', 'attachment;filename=form' . $id_form . '_export.csv');
    $app->render('pages/csv.html', $c);
})->name('getFormResponsesDownload');
// /form/responses/:id_form/delete/:id_response controller
// Delete responses associated to a form
$app->get('/form/responses/:id_form/delete/:id_response', function ($id_form, $id_response) use($app) {
    $c = array();
    // We grab its responses
    $response = models\ModelBuilder::fromTable('responses_' . $id_form)->find($id_response);
    $response->delete();
    $app->redirect($app->urlFor('getFormResponses', array('id' => $id_form)));
})->name('getFormResponseDelete');
/*
* POST CONTROLLERS 
*/
// /form/new/ controller
// Create new form
// TODO: Use Schema::create
$app->post('/form/new', function () use($app) {
    $c = array();
    $post_vars = $app->request()->post();
    if (count($post_vars) == 0) {
        $error = 'When creating a form, you must add at least 1 field';
        $app->redirect($app->urlFor('error') . '?error=' . $error);