<?php
// ! Support file only, run AjaxTable.html instead !
// This file is used as both Data_Url and Upload_Url
// Generates data for TreeGrid when no data received or saves received changes to database
// Single file, without using TreeGridFramework.php

// --- Database switching ---
require_once("IncDbTxt.php");                 // Routines to connect to database via text file database
$db = new Database("Database");               // Database in folder "Database"

header("Content-Type: text/xml; charset=utf-8"); 

// --------------------------------------------------------------------------
// --- Saves changes ---
$XML = array_key_exists("TGData",$_REQUEST) ? $_REQUEST["TGData"] : "";
if ($XML) { 
   if(get_magic_quotes_gpc()) $XML = stripslashes($XML);
      
   // --- simple xml or php xml --- 
   $SXML = is_callable(simplexml_load_string);
   if(!$SXML) require_once("Xml.php");
   if($SXML){ 
      $Xml = simplexml_load_string(html_entity_decode($XML));
      $Xml = $Xml->Changes->I;
      }
   else { 
      $Xml = CreateXmlFromString(html_entity_decode($XML));
      $Xml = $Xml->getElementsByTagName("I");
      }
   foreach($Xml as $I){
      $A = $SXML ? $I->attributes() : $I->attributes;
      // --- end of simple xml or php xml --- 
         
      if($A["Deleted"]){
         $db->Exec("DELETE FROM TableData WHERE ID='".$A["id"]."'");
         }
      else if($A["Added"]){
         $db->Exec("INSERT INTO TableData(ID,Project,Resource,Week,Hours) VALUES("
               . $A["id"] . "," 
               . "'" . str_replace("'","''",$A["Project"]) . "',"
               . "'" . str_replace("'","''",$A["Resource"]) . "',"
               . $A["Week"] . ","
               . $A["Hours"] .")");
         }
      else if($A["Changed"]){
         $S = "UPDATE TableData SET ";
         foreach($A as $name => $value){
            if($name=="Project" || $name=="Resource") $S .= "$name = '" . str_replace("'","''",$value) . "',";
            else if($name=="Week" || $name=="Hours") $S .= "$name = " . $value . ",";
            }
         $S = substr($S,0,strlen($S)-1);
         $S .= " WHERE ID='".$A["id"]."'";
         $db->Exec($S);
         }
      }
   echo "<Grid><IO Result='0'/></Grid>";
   }

// --- Generating data for body ---
else {   
   $rs = $db->Query("SELECT COUNT(*),MAX(ID) FROM TableData");
   $cnt = $rs->Get(0);
   echo "<Grid><Cfg LastId='" . $rs->Get(1) . "' RootCount='" . $cnt . "'/><Body>";
   $cnt = floor(($cnt+19) / 20);
   for($i=0;$i<$cnt;$i++) echo("<B/>");
   echo "</Body></Grid>";
   }
// --------------------------------------------------------------------------
?>