<?php
/* $Id: workplacemanager.php,v 1.2 2006/04/27 11:57:00 k-fish Exp $ */

$myEnv["module"] = "admin";
$myEnv["output"] = "html";
$myEnv['stdsmenu'] = false;

include("../../config.inc.php");
include(INCLUDEPATH . "container.inc.php");

// adding file revision into global array
revisionInit("\$Revision: 1.2 $", __FILE__);

// =================================================
//	              create entry
// =================================================
if (isset($_POST["op"]) && $_POST["op"] == "create"){
    
    $_POST["worklocname"] = trim($_POST["worklocname"]);

    // Worklocationname mustn't be ""
    if ($_POST["worklocname"] != "") {

      $gname = $conn->QMagic($_POST["worklocname"]);

      $sql = "SELECT name FROM mgw_workplace WHERE name = ". $gname;
      if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

   	  if($res->RecordCount() == 0) {
      
          // Create Worklocation
    $id = $conn->GenID('mgw__seq_workloc', 60005);
    $gname = $conn->QMagic($_POST["worklocname"]);
    $gdesc = $conn->QMagic($_POST["description"]);
    $gsort = (int)$_POST["sort_order"];

    // find max sort order
    $sql="select max(sort_order) from mgw_workplace";
    $max_sort = $conn->GetOne($sql);
    if ($max_sort === FALSE) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    if ($gsort < 1 || $gsort > $max_sort) $gsort = $max_sort + 1;
    else {
        $sql = "UPDATE mgw_workplace SET sort_order=sort_order+1 WHERE sort_order >= $gsort";
        if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    }
    $sql="INSERT INTO mgw_workplace (id, name, description, sort_order, lu_user, lu_date) VALUES ($id, $gname, $gdesc, $gsort, ".$_SESSION["MGW"]->userid.", ".$conn->DBTimeStamp(time()).")";

    if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
      } else {
          // Worklocation name already exists, display form again with description
          $smarty->assign("suname","create");
          $smarty->assign("suclass","submit");
          $smarty->assign("mode","new");
          $smarty->assign("td", array("description"=>$_POST["description"]));
          $smarty->assign("exception",Lang::getLanguageString("err_duplicateworkloc"));
            
          $smarty->display('workplacemanager_edit.tpl');
          exit;
      }

    } else {
      // worklocname is "", display form again with description
      $smarty->assign("suname","create");
      $smarty->assign("suclass","submit");
      $smarty->assign("mode","new");
      $smarty->assign("td", array("description"=>$_POST["description"]));
      $smarty->assign("exception",Lang::getLanguageString("err_noworklocname"));
            
      $smarty->display('workplacemanager_edit.tpl');
      exit;
    }
}

// =================================================
//	              edit entry
// =================================================

if (isset($_POST["op"]) && $_POST["op"] == "edit"){
    $id = (int) $_POST["id"];
    $gname = $conn->QMagic($_POST["worklocname"]);
    $gdesc = $conn->QMagic($_POST["description"]);
	$gsort = (int)$_POST["sort_order"];
    // adjust sort orders
    // find original sort order and highest sort order
    $sql="select sort_order from mgw_workplace where id=$id";
    $orig_sort = $conn->GetOne($sql);
    if ($orig_sort === FALSE) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    $sql="select max(sort_order) from mgw_workplace";
    $max_sort = $conn->GetOne($sql);
    if ($max_sort === FALSE) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    // if max_sort is null, establish sort order
    if ($max_sort < 1 || $orig_sort < 1) {
        $max_sort = 0;
        $sql = "SELECT id FROM mgw_workplace";
        if(!$workplace_ids = $conn->GetCol($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
        foreach ($workplace_ids as $workplace_id) {
            $max_sort++;
            $sql = "UPDATE mgw_workplace SET sort_order=$max_sort WHERE id=$workplace_id";
            if (!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
            // prevent resorting
            if ($workplace_id == $id) $gsort = $orig_sort = $max_sort;
        }
    }
    // if new > highest, new = highest
    if ($gsort > $max_sort) $gsort = $max_sort;
    if ($gsort < 1) $gsort = $orig_sort;
    // if original == new, do nothing
    if ($gsort > $orig_sort) {
        // if new > original, adjust -1 original to new
        $sql = "update mgw_workplace set sort_order=sort_order-1 where sort_order <= $gsort and sort_order > $orig_sort";
        if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    } elseif ($gsort < $orig_sort) {
        // if new < original, adjust +1 new to original
        $sql = "update mgw_workplace set sort_order=sort_order+1 where sort_order >= $gsort and sort_order < $orig_sort";
        if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    }
    $sql="update mgw_workplace set name=$gname, description=$gdesc, sort_order=$gsort, lu_user=".$_SESSION["MGW"]->userid.", lu_date=". $conn->DBTimeStamp(time()). " WHERE id=$id";
    if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
}

// =================================================
//	              delete worklocation
// =================================================
if (isset($_GET["view"]) && $_GET["view"] == "delete"){
    $id = (int) $_GET["id"];
    // get sort order
    $sql = "SELECT sort_order FROM mgw_workplace WHERE id=$id";
    $sort_order = $conn->GetOne($sql);
    if ($sort_order === FALSE) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    // delete entry
    $sql = "DELETE FROM mgw_workplace WHERE id=$id";
    if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    // realign sort order
    $sql = "UPDATE mgw_workplace SET sort_order=sort_order-1 WHERE sort_order>$sort_order";
    if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
}

// =================================================
//	              New Item Formular
// =================================================
if (isset($_GET["view"]) && $_GET["view"] == "newform") {
    $smarty->assign("suname","create");
    $smarty->assign("suclass","submit");
    $smarty->assign("mode","new");

    $smarty->display('workplacemanager_edit.tpl');
    exit;
}

// ================================================
//			Edit worklocation form
// ================================================
if (isset($_GET["view"]) && $_GET["view"] == "editform") {
    $id = (int) $_GET["id"];

    $sql = "SELECT * FROM mgw_workplace WHERE id = $id";
    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    $row = $res->FetchRow();
	
    $smarty->assign("suname","edit");
    $smarty->assign("suclass","submit");
    $smarty->assign("mode","edit");
    $smarty->assign("td", $row);
    $smarty->assign("editworkloc", Lang::getParmLang(Lang::getLanguageString("editworkloc"), array($row["name"])));
	
    $smarty->display('workplacemanager_edit.tpl');
    exit();
}


// =================================================
//	              List View
// =================================================
$icons = getIconStrings();

$sql = "SELECT a.id, a.name, a.description, a.sort_order, a.lu_date, b.username AS lu_user from mgw_workplace a LEFT JOIN mgw_users b ON a.lu_user = b.id ORDER BY a.sort_order";
if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
while($row = $res->FetchRow()){
    // create Action URLs
    $editlink = "<a href=\"workplacemanager.php?mod=admin&amp;obj=workloc&amp;view=editform&amp;id=". $row["id"] ."&amp;".SID."\" class=\"edit\">". $icons["edit"] . "</a>";
    $dellink = "<a href=\"workplacemanager.php?mod=admin&amp;obj=workloc&amp;view=delete&amp;id=". $row["id"] ."&amp;".SID."\" onclick=\"return confirm('".Lang::getLanguageString('reallydelworkplace')."')\" class=\"delete\">". $icons["delete"] . "</a>";

    $row['lu_date'] = $conn->UnixTimestamp($row['lu_date']);
    $row['action'] = $editlink . $icons["space"] . $dellink;
    $smarty->append("td",$row);
}	
		
$smarty->display("workplacemanager_list.tpl");
?>
