#!/usr/bin/php-cgi -dcgi.force_redirect=0
<?php
# encoding: utf-8
# api: cgi
# type: store
# category: database
# title: Survey submit
# description: Store arbitrary POST form data into a survey_* table
# version: 0.2
# state: alpha
# config: -
# access: public
#
# Requires a form like:
#
#    <action target="/ext/survey/SAMPLE" method=POST>
#        <input type=checkbox name=q1 value=1>
#        <input type=radio name=q2 value=1>
#        <input type=text name=q3>
#        <input type=submit>
#    <a href="/ext/survey_sum/SAMPLE">see results…</a>
#
# And will then populate a `survey_SAMPLE` table with JSON entries (no
# field expansion or anything). Does allow for array and text storage.
# Whereas `survey_sum` will only show countable entries. More detailed
# analysis has to be done manually.
#

include("./fossil_common.php");
define("RX_TBL", "/^(\w+|table2|name)$/");   // allowed survey_$tbl names



#-- insert
function store($tbl) {
    $json = json_encode($_POST);
    db("CREATE TABLE IF NOT EXISTS `survey_$tbl` (submitted TEXT, remote_addr TEXT, fields TEXT)");
    db("INSERT INTO `survey_$tbl` (submitted, remote_addr, fields) VALUES (DATETIME('now'), ?, ?)", [$_SERVER["REMOTE_ADDR"], $json]);
    header("Location: /ext/survey_sum/$tbl#thanks");
}

#-- run
if (!preg_match(RX_TBL, $tbl = basename($_SERVER["PATH_INFO"]))) {
    die("No table name given /survey/NAME");
}
elseif (count($_POST)) {
    #error_reporting(E_ALL);ini_set("display_errors", 1);
    store($tbl);
}
else {
    die("Empty form");
}

