<?php

/**
 * 
 * VERSION HANDLER API
 * 
 * Syntax des Aufrufs (als GET Schreibweise; ein POST soll (später) auch gehen):
 * http://dev.ci.iml.unibe.ch:8002/versions/?action=update&project=ci&phase=preview&host=ci.preview.iml.unibe.ch&variable=version&value=007
 * 
 * Parameter:
 * 
 *      action=update (get-Funktionen muss ich später noch bauen)
 *      project=[Projekt-ID (=Name des Package, das installiert wird)]
 *      phase=(preview|stage|live)
 *      host=[FQDN]
 *      variable=version (andere noch nicht unterstützt/ vorgesehen)
 *      value=[Versionsdaten]
 * 
 * 2017-04-07  hahn  first lines
 */


// ----------------------------------------------------------------------
// functions
// ----------------------------------------------------------------------

/**
 * show an error message and quit with http status code 400 (Bad request)
 * @param string  $sMessage  message to show
 * @return boolean
 */
function quit($sMessage) {
    $sProtocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
    header("$sProtocol 400: Bad request");
    die("<h1>Bad request</h1>" . $sMessage);
    return false;
}

/**
 * get a request param from GET and POST scope (POST has priority) and
 * verify it with execution of a cleanup array
 * @param string  $sKey            key to search for in GET or POST
 * @param string  $sRegex4Cleanup  regex for filtering
 * @return type
 */
function getParam($sKey, $sRegex4Cleanup = false) {
    $sValue=false;
    if (array_key_exists($sKey, $_GET)) {
        $sValue=$_GET[$sKey];
    }
    if (array_key_exists($sKey, $_POST)) {
        $sValue=$_POST[$sKey];
    }
    if(!$sValue){
        return false;
    }
    $sReturn = $sRegex4Cleanup ? preg_replace($sRegex4Cleanup, '', $sValue) : $sValue;

    if ($sReturn !== $sValue) {
        quit("ERROR: the parameter value in [$sKey = ...] has a wrong format.");
    }
    return $sReturn;
}

// ----------------------------------------------------------------------
// check required params
// ----------------------------------------------------------------------
/*
if (!$_GET || !count($_GET)) {
    quit("no parameter was found.");
}

foreach (array("action", "project") as $sKey) {
    if (!array_key_exists($sKey, $_GET)) {
        quit("value required: $sKey=");
    }
}
 */


// ----------------------------------------------------------------------
// get vars
// ----------------------------------------------------------------------


$sAction = getParam('action', '/[^a-z]/');

$sProject = getParam('project', '/[^a-z\-0-9]/');
$sPhase = getParam('phase', '/[^a-z]/');
$sPlace = getParam('place', '/[^a-z]/');
$sHost = getParam('host', '/[^a-z\.\-0-9]/');

if ($sHost && !$sPlace) {
    $sPlace = 'installed';
}

$sVarname = getParam('variable', '/[^a-z]/');
$sValue = getParam('value', '');


// ----------------------------------------------------------------------
// init class
// ----------------------------------------------------------------------

$sOut='';
$sHeader='';
$sOut.='<h1>data browser</h1>';
require './classes/valuestore.class.php';

$oVersion = new valuestore();

$aData=$oVersion->dumpdb();
$sTable='';
$sTableHead='';
if(is_array($aData) && count($aData)){
    // echo '<pre>' . print_r($aData, 1);
    foreach ($aData as $aRow){
        $sItemUrl='index.php?project='.$aRow['project'].'&package='.$aRow['package'].'&phase='.$aRow['phase'].'&host='.$aRow['host'].'&variable='.$aRow['variable'].'';
        $sTable.='<tr onclick="location.href=\''.$sItemUrl.'\'">';
        // $sTable.='<tr>';
        foreach ($aRow as $sKey=>$sValue){
            // $sTable.='<td class="'.$sKey.'"><a href="'.$sUrl.'">'.$sValue.'</a></td>';
            $sTable.='<td class="'.$sKey.'">'.htmlentities($sValue).'</td>';
        }
        $sTable.='<td>'
                // . '<button onclick="location.href=\''.$sItemUrl.'&action=get\'">View</button>'
                . '<form method="POST" action="'.$sItemUrl.'">'
                    . '<input type="hidden" name="action" value="delete">'
                    . '<button>Delete</button>'
                . '</form>'
                . '</td>'
                . '</tr>';
        
    }
    foreach (array_keys($aRow) as $sKey){
        $sTableHead.='<th class="'.$sKey.'">'.$sKey.'</th>';
    }
    $sOut.=''
            . '<form method="POST" action="index.php">'
                . '<input type="hidden" name="action" value="cleanup">'
                . '<button>Cleanup</button>'
            . '</form>'
            
            . '<table id="tbldata"><thead>'
            . '<tr>'.$sTableHead. '</tr>'
            . '</thead>'
            . '<tbody>'.$sTable.'</tbody></table>';
    
} else {
    $sOut.='no data yet.';
}
// $sOut.='<script>addFilterToTable("tbldata"); filterTable();</script>';

require_once("../deployment/classes/page.class.php");
$oPage = new Page();
$oPage->addResponseHeader("Pragma: no-cache");
$oPage->setOutputtype('html');
$oPage->setHeader($sHeader);
$oPage->addJsOnReady('addFilterToTable(); filterTable();');

$oPage->setContent($sOut);
echo $oPage->render();
