#include <infodrom.style>
#include <phptools.inc>

<future>
<?
  function convert_date($date)
  {
    if (!preg_match ("/[0-9]+-[0-9]+-[0-9]+/", $date)) {
      $date = explode (".", $date);
      if ($date[2] < 2000)
	$date[2] += 2000;
      $date = sprintf ("%d-%d-%d", $date[2], $date[1], $date[0]);
    }
    return $date;
  }

  $dbh = pg_pconnect ("<dbhost>", "<dbport>", "<dbname>")
	 or die("Unable to connect to SQL server");

  if (isset($_POST['clone']) &&
      isset($_POST['date']) && !empty($_POST['clone']) &&
      isset($_POST['id']) && !empty($_POST['id'])) {

    $date = convert_date($_POST['date']);
    $query = 'INSERT INTO events (start,delta,name,city,country,conference,exhibition,url,inserted) '.
      "SELECT '%s',delta,name,city,country,conference,exhibition,url,now()".
      'FROM events WHERE oid = %d';
    $query = sprintf($query, $date, $_POST['id']);
    $sth = pg_exec ($dbh, $query) or die("Datenbank-Abfrage!");

    $oid = pg_last_oid($sth);
    if ($oid === false)
      die("INSERT failed");

    header('Location: edit.php?id=' . $oid);
    exit(0);
  }
?>

<page func="Infodrom Oldenburg" title="Events">

<sql_prepare>
<?
  function bomb_if_empty ($foo, $name)
  {
    if (strlen ($foo) == 0) {
      printf ("<p><strong><em>%s</em> must not be empty!</strong>", $name);
      exit ();
    }
  }

  bomb_if_empty ($_POST['name'], "Name");
  bomb_if_empty ($_POST['country'], "City");
  bomb_if_empty ($_POST['country'], "Country");
  bomb_if_empty ($_POST['date'], "Date");

  $days = (int)$_POST['days'];
  if ($days < 0) {
    $days = 0;
  } elseif ($days > 0) {
    $days = $days -1;
  }
  if ($days != 1) {
    $days = "$days days";
  } else {
    $days = "$days day";
  }

  $date = convert_date($_POST['date']);

  $orig_name = $_POST['name'];

  $oid = 0;

  if ($_POST['id'] > 0 && isset($_POST['delete'])) {
      $query = sprintf ("DELETE FROM events WHERE oid = %d", $_POST['id']);
      $sth = pg_exec ($dbh, $query) or die("Datenbank-Abfrage!");
  } else {
      $item = ['start' => $date,
	       'delta' => $days,
	       'name' => $_POST['name'],
	       'city' => $_POST['city'],
	       'country' => $_POST['country'],
	       'conference' => isset($_POST['conference'])?1:0,
	       'exhibition' => isset($_POST['exhibition'])?1:0,
	       'cancelled' => isset($_POST['cancelled'])?1:0,
	       'url' => $_POST['url'],
	       'deburl' => $_POST['deburl'],
	       'localurl' => $_POST['localurl'],
	       'comment' => $_POST['comment'],
	       ];

      if ($_POST['id'] > 0) {
	  $db->update('events', $item, 'oid = ' . intval($_POST['id']));
      } else {
	  $item['inserted'] = 'now()';
	  $db->insertInto('events', $item);
      }
  }

  if ($_POST['id'] > 0) {
    if ($_POST['delete'])
      echo "<p>deleted.</p>";
    else
      echo "<p>updated.</p>";
  } else
    echo "<p>inserted.</p>";
?>

</page>

# Local variables:
# mode: text
# mode: auto-fill
# end:
