<?php
/*=======================================================================
 *
 * inc_SRVC.inc.php
 *
 * Autor: Marc Vollmann
 *
 =======================================================================*/



// *****************
// * TIME TRACKING *
// *****************

function setTimetrackingEvent ($moId, $usrId, $ttEvent, $ttTimestamp, $gpsLong, $gpsLat, $description, $csc_id = "0") {
	global $dbname, $dblogin, $dbpassword;

  // Get operational IP and port from $moId
  if ($moId != "" && $usrId != "" && $ttEvent != "") :

     // Get operational database instance via metaobject
     $moValue = getOperationalDatabase($moId);

     if ($moValue != "") :
        if ($ttTimestamp == "") : $ttTimestamp = getDateTime("0"); endif;

        // Set operational database and insert event
        $db_op_conn = getDbConnectionSpecial($moValue, $dbname, $dblogin, $dbpassword);

        $sqlStmt = "INSERT INTO phoenix_group.timetracking (tt_datetime,tt_id,usr_id,tt_gps_long,tt_gps_lat,tt_description,csc_id)" .
                          " VALUES ('" . $ttTimestamp . "','" . $ttEvent . "','" . $usrId . "','" . $gpsLong . "','" . $gpsLat . "','" . $description . "','" . $csc_id . "')";

        $res = $db_op_conn->query($sqlStmt);
        if (DB::isError($res)) : die ("$PHP_SELF: " . $res->getMessage()); endif;
        
        $retArray = array("0");
     else:
        $retArray = array("802","<err_no>802</err_no>\n","<err_desc>" . getLngt("Operational database cannot be connected!") . "</err_desc>\n");
     endif;
  else:
     $retArray = array("801","<err_no>801</err_no>\n","<err_desc>" . getLngt("Request has emty items!") . "</err_desc>\n");
  endif;
  return $retArray;
}

// For compatibility only
function setTimekeepingEvent ($moId, $usrId, $ttEvent, $ttTimestamp, $gpsLong, $gpsLat, $description, $csc_id) {
  return setTimetrackingEvent ($moId, $usrId, $ttEvent, $ttTimestamp, $gpsLong, $gpsLat, $description, $csc_id);
}

function getLastTimetrackingEvent ($moId, $usrId) {
	global $dbname, $dblogin, $dbpassword;

  // Get operational IP and port from $moId
  if ($moId != "" && $usrId != "") :

     // Get operational database instance via metaobject
     $moValue = getOperationalDatabase($moId);

     if ($moValue != "") :

        // Set operational database and insert event
        $db_op_conn = getDbConnectionSpecial($moValue, $dbname, $dblogin, $dbpassword);

        $tmpSqlQuery = "SELECT tt_datetime, tt_id, tt_gps_long, tt_gps_lat, tt_description, csc_id FROM phoenix_group.timetracking WHERE usr_id = '" . $usrId . "' ORDER BY tt_datetime DESC LIMIT 0,1";
        $result = $db_op_conn->query($tmpSqlQuery);
        while ($row = $result->fetch_assoc()):
              $retArray = array("0", $row["tt_datetime"], $row["tt_id"], $row["tt_gps_long"], $row["tt_gps_lat"], $row["tt_description"], $row["csc_id"]);
        endwhile;
        $result->free();
     else:
        $retArray = array("802","<err_no>802</err_no>\n","<err_desc>" . getLngt("Operational database cannot be connected!") . "</err_desc>\n");
     endif;
  else:
     $retArray = array("801","<err_no>801</err_no>\n","<err_desc>" . getLngt("Request has emty items!") . "</err_desc>\n");
  endif;
  return $retArray;
}

// ----------------------------------------------------------------------------------------------------------------------------------------


// *************
// * GROUPWARE *
// *************

// <IS_IMPLEMENTED>

// Gets the last calendar week (number) of a specified year
// function calLastWeekNumofYear($selYear) {};

// Gets the first calendar week (number) of a specified month and year (calendar week of the 01.01.YYYY)
// function calFirstWeekNumofMonth($selMonth, $selYear) {};

// Gets the first day (number) of a specified month and year
// function calFirstDayNumOfMonth($selMonth, $selYear) {};

// Gets the first day (number) of the first calendar week of a specified year, it has to be a "Monday"
// function calFirstDayNumOfFirstCalendarWeekOfYear($selYear) {};

// Gets the first day (number) of a specified calendar week and year
// function calFirstDayNumOfWeek($selWeek, $selYear) {};

// Gets an array with days of a specified month (and year), where there is at least one appointment per day
// function getDaysWithAppointments($selYear, $selMonth) {}

// Modifies array according to the appointments starting and ending on different days
// $apArray = Array with appointments of the time interval (week, month, ...)
// $lowerRangeDate = Date of the beginning of the interval (week, month, ...)
// $upperRangeDate = Date of the end of the interval (week, month, ...)
// function modifyIntervalAppointments2SingleDayAppointments($apArray, $lowerRangeDate, $upperRangeDate) {}

// Gets the appointments of one day
// function getAppointmentsOfOneDay($selYear, $selMonth, $selDay, $csId = "") {}

// Gets the appointments of one week
// function getAppointmentsOfOneWeek($selWeek, $selYear, $selMonth, $selDay, $csId = "") {}

// Gets the appointments of one month
// function getAppointmentsOfOneMonth($selYear, $selMonth, $csId = "") {}

// Gets the appointments of one year
// function getAppointmentsOfOneYear($selYear, $csId = "") {}

// Gets a customer list according to a special search string
// function getCustomerList ($search)             => defined in "inc_customer.inc.php"

// Gets special data from a single customer
// function getCustomerSpecial ($csId)            => defined in "inc_customer.inc.php"

// Gets ALL data from a special customer
// function getCustomer ($cmpId)                  => defined in "inc_customer.inc.php"

// Inserts a new customer
// function insertCustomer ($csArray = array())   => defined in "inc_customer.inc.php"

// Gets a costcenter list according to a special search string or a a special customer
// function getCostcenterList ($csId = "", $search = "", $limit = "100")  => defined in "inc_customer.inc.php"

// Gets costcenter addresses of a special costcenter
// function getCostcenterAddressList ($cscId)     => defined in "inc_customer.inc.php"

// </IS_IMPLEMENTED>


// Dummy function because of checking existence. It is implemented in "serviceXML.php".
function getApEnvironment() {

}

// Gets the headline with the current day
function getAppointmentHeader($viewMode, $selYear, $selMonth, $selDay, $selWeek) {
  global $calWeekDays,$calCurrentDayNumOfTheWeek, $calMonthNames, $calMonthDays;
  global $calCurrentWeekNum, $calCurrentWeekName, $calCurrentDayNumOfTheYear;

  $out = "";
  // Daily output
  if ($viewMode == "1") :
     // Name of the week day (E.g.: "Donnerstag") --- Day, Name of the month and year  (E.g.: "29 Juni 2006") --- calendar week (E.g.: "KW 26")
     $out .= $calWeekDays[$calCurrentDayNumOfTheWeek - 1] . ", " . $selDay . ". " . $calMonthNames[$selMonth - 1] . " " . $selYear . "     " . $calCurrentWeekName . " " . $calCurrentWeekNum . "     " . $calCurrentDayNumOfTheYear . getLngt(". Tag des Jahres");
  endif;
  // Weekly output
  if ($viewMode == "2") :
     // Get the first day ("Monday") of the specified week and compute date interval of the week
     $firstDayOfWeek = calFirstDayNumOfWeek($selWeek, $selYear);
     $tmpDatetime = mktime(0, 0, 0, $firstDayOfWeek[1], $firstDayOfWeek[0] + 6, $firstDayOfWeek[2]);
     // calendar week                    (E.g.: "KW 26")
     $out .= $calCurrentWeekName . " " . $selWeek . "     " . "[" . $selYear . "]" . "     " . $firstDayOfWeek[0] . "." . $firstDayOfWeek[1] . "." . ($firstDayOfWeek[2] != date("Y", $tmpDatetime) ? $firstDayOfWeek[2] : "") . " - " . date("d", $tmpDatetime) . "." . date("m", $tmpDatetime) . "." . ($firstDayOfWeek[2] != date("Y", $tmpDatetime) ? date("Y", $tmpDatetime) : "") . "&nbsp;";
  endif;
  // Monthly output
  if ($viewMode == "3") :
     // Name of the month and year  (E.g.: "Juni 2006")
     $out .= $calMonthNames[$selMonth - 1] . " " . $selYear . "     " . "01." . $selMonth . ". - " . $calMonthDays[$selMonth - 1] . "." . $selMonth . ".";
  endif;
  // Yearly output
  if ($viewMode == "4") :
     // Name of the year  (E.g.: "2006")
     $out .= $selYear . "     " . "01.01. - 31.12.";
  endif;
  return $out;
}

// Gets the title of the output table
function getAppointmentTitle($viewMode) {
  $appointmentTitleArray = array();
  // Daily output
  if ($viewMode == "1") :
     $appointmentTitleArray = array(getLngt("Beginn"), getLngt("Ende"), getLngt("Ersteller, Teilnehmer"), getLngt("Kunde"), getLngt("Aktion"));
  endif;
  // Weekly output
  if ($viewMode == "2") :
     $appointmentTitleArray = array(getLngt("Tag"), getLngt("Zeit"), getLngt("Ersteller, Teilnehmer"), getLngt("Beschreibung"), getLngt("Kunde"));
  endif;  
  return $appointmentTitleArray;
}

// DB actions for an appointment
function actionAppointment ($actionMode, $apId, $apText, $execDatetime, $endDatetime, $hqId, $usrId, $csId, $usrIdsParticipants, $apCat1, $apCat2, $apCat3, $apCat4) {
	global $db, $PHP_SELF;
	$opCode = "0";
	$currentTime = getDateTime("0");
	$sendPerMail = false;
	$apText = trim($apText);
  // $execDatetime = getDateTime("format",array($f_hour,$f_minute,0,$f_month,$f_day,$f_year),"Y-m-d H:i:s");
  // $endDatetime = getDateTime("format",array($f_hour_to,$f_minute_to,0,$f_month_to,$f_day_to,$f_year_to),"Y-m-d H:i:s");
/*
echo "actionMode: " . $actionMode . "<br>";
echo "apId: " . $apId . "<br>";
echo "apText: " . $apText . "<br>";
echo "execDatetime: " . $execDatetime . "<br>";
echo "endDatetime: " . $endDatetime . "<br>";
echo "hqId: " . $hqId . "<br>";
echo "usrId: " . $usrId . "<br>";
echo "csId: " . $csId . "<br>";
echo "usrIdsParticipants: " . $usrIdsParticipants . "<br>";
echo "apCat1: " . $apCat1 . "<br>";
echo "apCat2: " . $apCat2 . "<br>";
echo "apCat3: " . $apCat3 . "<br>";
echo "apCat4: " . $apCat4 . "<br>";
*/
  if (($actionMode == "insert" && $apText != "") || ($actionMode == "update" && $apId != "")) :
     // Check for headquarters
     if ($hqId == "" && $csId != "" && is_numeric($csId)) :
        $hqId = getFieldValueFromId("phoenix.customer","cs_id",$csId,"hq_id");
     endif;
     if ($hqId != "" && $usrId != "") :
	      if ($execDatetime != "" && $endDatetime != "" && $execDatetime <= $endDatetime) :
	         $usrIdsParticipants = trim($usrIdsParticipants);
	         if ($usrIdsParticipants != "") :
	            if (substr($usrIdsParticipants,0,1) != ",") : $usrIdsParticipants = "," . $usrIdsParticipants; endif;
	            if (substr($usrIdsParticipants,-1,1) != ",") : $usrIdsParticipants .= ","; endif;
	         endif;
           if ($actionMode == "insert") :
              // Insert values
              insertStmt("phoenix_group.appointment", array("usr_id", $usrId, "hq_id", $hqId, "ap_category_1", $apCat1, "ap_category_2", $apCat2,
                                                            "ap_category_3", $apCat3, "ap_category_4", $apCat4,
                                                            "ap_participants", $usrIdsParticipants, "ap_text", $apText, 
                                                            "ap_execdate", $execDatetime, "ap_enddate", $endDatetime, 
                                                            "ap_modifytime", $currentTime, "cs_id", $csId));
              $opCode = getLastInsertID();
           elseif ($actionMode == "update") :
              // Update values
              updateStmt("phoenix_group.appointment", "ap_id", $apId, array("ap_category_1", $apCat1, "ap_category_2", $apCat2, "ap_category_3", $apCat3,"ap_category_4", $apCat4,
                                                                            "ap_participants", $usrIdsParticipants, "ap_text", $apText, "ap_execdate", $execDatetime, "ap_enddate", $endDatetime, 
                                                                            "ap_modifytime", $currentTime, "cs_id", $csId));
              $opCode = $apId;
           endif;
           $sendPerMail = true;
	      endif;
	   endif;

	elseif ($actionMode == "delete") :
	   if ($apId != "") :
	      deleteStmt("phoenix_group.appointment","ap_id = ".$apId);
	      $opCode = $apId;
	      $sendPerMail = true;
	   endif;
	
	elseif ($actionMode == "confirm") :
     if ($apId != "" && $usrId != "") :
        // Get confirmation string from appointment
        $tmpApConfirmed = getFieldValueFromId("phoenix_group.appointment", "ap_id", $apId, "ap_confirmed");
        $tmpApConfirmed = substr($tmpApConfirmed,1,-1);   // Remove commata from db-field
        $tmpApConfirmed = spliti(",", $tmpApConfirmed);   // It has to be an array
        $j = array_search($usrId, $tmpApConfirmed);
        if ($j === FALSE) :
           if (count($tmpApConfirmed) == 1 && trim($tmpApConfirmed[0] == "")) :
              $tmpApConfirmed = array($usrId);
           else :         
              array_push($tmpApConfirmed, $usrId);
           endif;
           updateStmt("phoenix_group.appointment", "ap_id", $apId, array("ap_confirmed", "," . implode(",", $tmpApConfirmed) . ","));
           $opCode = $apId;
        endif;
     endif;

	elseif ($actionMode == "finish") :
     if ($apId != "") :
        updateStmt("phoenix_group.appointment", "ap_id", $apId, array("ap_category_4", "2"));
        $opCode = $apId;
     endif;
  endif;

	if (false && $sendPerMail) :
     $mailAddresses = array();
     // Get email address of the creator of the appointment
     $fromEmailAddress = getFieldValueFromId("user", "usr_id", $usrId, "usr_email");
     if (checkEmailFormat($fromEmailAddress)) : 
        array_push($mailAddresses, $fromEmailAddress);
     endif;
     // Get data of the appointment
     if ($actionMode == "insert" || $actionMode == "update") :
        $tmpParticipants = $usrIdsParticipants;
        $tmpText = $apText;
     elseif ($actionMode == "delete") :
        $tmpExecDatetime = getFieldValueFromId("phoenix_group.appointment", "ap_id", $apId, "ap_execdate");
        $tmpText = getFieldValueFromId("phoenix_group.appointment", "ap_id", $apId, "ap_text");
        $tmpParticipants = getFieldValueFromId("phoenix_group.appointment", "ap_id", $apId, "ap_participants");
          $tmpParticipants = substr($tmpParticipants,1,-1);   // Remove commata from db-field
          $tmpParticipants = spliti(",", $tmpParticipants);   // It has to be an array
     endif;
     $lenTmp = count($tmpParticipants);
     for ($i = 0; $i < $lenTmp; $i++) :
         $toEmailAddress = getFieldValueFromId("user", "usr_id", $tmpParticipants[$i], "usr_email");
         if (checkEmailFormat($toEmailAddress)) :
            array_push($mailAddresses, $toEmailAddress);
         endif;
     endfor;      
	   $mailAddressesString = implode(",", $mailAddresses);
	   $mailObj = new htmlMimeMail();

     // Format mailtext
     $mailtext  = "<html><head><meta text/html>";
     $mailtext .= "<style type=\"text/css\">";
     $mailtext .= ".f8np1 { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; font-weight: normal; padding: 1px}";
     $mailtext .= ".f8bp1 { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; font-weight: bold; padding: 1px}";
     $mailtext .= ".f8np1_red { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; font-weight: normal; padding: 1px; color: #FF0000;}";
     $mailtext .= "</style>";
     $mailtext .= "</head><body><h4>";
     
     $mailtext .= "<div class=\"f8bp1\">" . getLngt("Sehr geehrte Damen und Herren,") . "</div><br>";
     $tmpText = str_replace("\r", '<br>', $tmpText);
     $mailtext .= "<div class=\"f8bp1\">" . $tmpText . "</div><br>";
     $mailtext .= "<div class=\"f8bp1\">" . getLngt("Mit freundlichem Gruß!") . "</div><br>";

     // Logo
     $logoName = getParameterValue("0", "IMG_LOGO_NAME", $hqId);
     $logoHeight = getParameterValue("0", "IMG_LOGO_HEIGHT", $hqId);
     $logoWidth = getParameterValue("0", "IMG_LOGO_WIDTH", $hqId);
     if ($logoName != "" && $logoHeight != "" && $logoWidth != "") :
        $mailtext .= "<br><div><img src=\"../images/external/" . $logoName . "\" border=\"0\" height=\"" . $logoHeight . "\" width=\"" . $logoWidth . "\"></div><br><br>";
     endif;
     $mailtext .= "</body></html>";
     
     $mailObj->setHtml($mailtext, null, "./");

     $mailObj->setFrom($fromEmailAddress);
     // $mailObj->setCc($mailCcAddress);
     // $mailObj->setBcc($mailBccAddress);
     $mailObj->setSubject(getLngt("Termin abgesagt: ") . $tmpExecDatetime);
     $mailResult = $mailObj->send(array($mailAddressesString), 'smtp');
     if (!$mailResult) :
        $statusMessage .= getLngt("Die Nachricht konnte nicht gesendet werden!") . " ";
     endif;
     $mailObj = NULL;
	endif;
	return $opCode;
}

// Gets a report list according to a special object type (customer, courier, etc.)
function getReportList ($fromDateRange, $toDateRange, $rpObjType = "cs", $rpObjId = "", $rpType = "") {
	global $db, $PHP_SELF;
	global $f_hq_id;
	$retArray = array();

	if (false) :
	   // $retArray = array("301","<err_no>301</err_no>\n","<err_desc>" . getLngt("Ein Suchbegriff wurde nicht eingegeben!") . "</err_desc>\n");
	else :
     // Get status of the customer according to being meta customer
     $isMeta = "0";
     $csParentIdArray = array();
     if ($rpObjId != "" && is_numeric($rpObjId)) :
        if ($rpObjType == "cs") :
           $csHqId = getFieldValueFromId("customer","cs_id",$rpObjId,"hq_id");
           if (!in_array($csHqId, $f_hq_id)) :
              array_push($f_hq_id, $csHqId);
           endif;
           // Check being meta customer
           if (existsEntry("customer",array("cs_id_parent",$rpObjId))) :
              $isMeta = "1";
              $csParentIdArray = getColVectorFromDB2Array("customer","cs_id_parent",$rpObjId,"cs_id","");
              array_push($csParentIdArray, $rpObjId);    // meta customer inclusive
           endif;
        endif;
        if ($rpObjType == "cr") :
           $crHqId = getFieldValueFromId("courier","cr_id",$rpObjId,"hq_id");
           if (!in_array($crHqId, $f_hq_id)) :
              array_push($f_hq_id, $crHqId);
           endif;
        endif;
     endif;

     $sqlquery = getReportListStatement($fromDateRange, $toDateRange, $rpObjType, $rpObjId, $rpType, $isMeta, $csParentIdArray);
     $result = $db->query($sqlquery);
     if (DB::isError($result)):
        $retArray = array("202","<err_no>202</err_no>\n","<err_desc>" . getLngt("Datenbankfehler") . "</err_desc>\n");
     else:
        while ($row = $result->fetch_assoc()):
              $retArray[] = array($row["rp_id"], $row["rp_reporttype"], $row["rp_text"], $row["rp_confidential"], $row["rp_createtime"], $row["usr_id"], $row["usr_name"], $row["usr_firstname"], $row["usr_phone"], $row["eid"], $row["cmp_comp"], $row["cmp_comp2"], $row["hq_id"], $row["hq_name"]);
        endwhile;
        $result->free();
     endif;
	endif;

	return $retArray;
}

// Gets a single report according to a special object type (customer, courier, etc.)
function getReport ($rpId, $rpObjType = "cs") {
	global $db, $PHP_SELF;
	global $f_hq_id;
	$retArray = array();

	if (false) :
	   // $retArray = array("301","<err_no>301</err_no>\n","<err_desc>" . getLngt("Ein Suchbegriff wurde nicht eingegeben!") . "</err_desc>\n");
	else :
     $sqlquery = getReportStatement($rpId, $rpObjType);

     $result = $db->query($sqlquery);
     if (DB::isError($result)):
        $retArray = array("202","<err_no>202</err_no>\n","<err_desc>" . getLngt("Datenbankfehler") . "</err_desc>\n");
     else:
        while ($row = $result->fetch_assoc()):
              $retArray[] = array($row["rp_id"], $row["rp_reporttype"], $row["rp_text"], $row["rp_confidential"], $row["rp_createtime"], $row["usr_id"], $row["usr_name"], $row["usr_firstname"], $row["usr_phone"], $row["eid"], $row["cmp_comp"], $row["cmp_comp2"], $row["hq_id"], $row["hq_name"]);
        endwhile;
        $result->free();
     endif;
	endif;

	return $retArray;
}

// DB actions for an report
function actionReport ($actionMode, $rpId, $rpType, $rpObjType = "cs", $rpObjId, $rpText, $rpConfidential = "0", $hqId, $usrId) {
	global $db, $PHP_SELF;
	$opCode = "0";
	$currentTime = getDateTime("0");
	$sendPerMail = false;
	$rpText = trim($rpText);
/*
echo "actionMode: " . $actionMode . "<br>";
echo "rpId: " . $rpId . "<br>";
echo "rpType: " . $rpType . "<br>";
echo "rpObjType: " . $rpObjType . "<br>";
echo "rpObjId: " . $rpObjId . "<br>";
echo "rpText: " . $rpText . "<br>";
echo "rpConfidential: " . $rpConfidential . "<br>";
echo "hqId: " . $hqId . "<br>";
echo "usrId: " . $usrId . "<br>";

writeToFile("../log/mobile.log", "-----------------------------");
writeToFile("../log/mobile.log", "actionMode: " . $actionMode);
writeToFile("../log/mobile.log", "rpId: " . $rpId);
writeToFile("../log/mobile.log", "rpType: " . $rpType);
writeToFile("../log/mobile.log", "rpObjType: " . $rpObjType);
writeToFile("../log/mobile.log", "rpObjId: " . $rpObjId);
writeToFile("../log/mobile.log", "rpText: " . $rpText);
writeToFile("../log/mobile.log", "rpConfidential: " . $rpConfidential);
writeToFile("../log/mobile.log", "hqId: " . $hqId);
writeToFile("../log/mobile.log", "usrId: " . $usrId);
*/
  $retArray = array("101","<err_no>101</err_no>\n","<err_desc>" . getLngt("Die Eingaben für die angeforderte Aktion sind nicht vollständig!") . "</err_desc>\n");
  if ($usrId != "" && (($actionMode == "insert" && $rpText != "") || ($actionMode == "update" && $rpId != "" && $rpText != "") || ($actionMode == "delete" && $rpId != ""))) :
     // Check for headquarters
     if ($hqId == "") :
        if ($rpObjId != "" && is_numeric($rpObjId)) :
           if ($rpObjType == "cs") :
              $hqId = getFieldValueFromId("phoenix.customer","cs_id",$rpObjId,"hq_id");
           elseif ($rpObjType == "cr") :
              $hqId = getFieldValueFromId("phoenix.courier","cr_id",$rpObjId,"hq_id");
           endif;
        else :
           $hqId = getFieldValueFromId("phoenix.user","usr_id",$usrId,"hq_id");
        endif;
     endif;
     if ($hqId != "" && $usrId != "") :
        if ($actionMode == "insert") :
           if ($rpObjId != "" && $rpObjType != "") :
              if ($rpText != "") :
                 // Insert values                 
                 insertStmt("phoenix_group.report_process", array("usr_id", $usrId, "hq_id", $hqId, "rp_reporttype", $rpType, "rp_text", $rpText,
                                                                  "rp_createtime", $currentTime, "rp_objId", $rpObjId, "rp_objtype", $rpObjType, "rp_confidential", $rpConfidential));
                 $rpIdNew = getLastInsertID();
                 $retArray = array("0",$rpIdNew);
              else :
                 $retArray = array("103","<err_no>103</err_no>\n","<err_desc>" . getLngt("Der Berichttext ist leer!") . "</err_desc>\n");
              endif;
           else :
              $retArray = array("102","<err_no>102</err_no>\n","<err_desc>" . getLngt("Bezugs-ID oder Bezugstyp ist nicht existent!") . "</err_desc>\n");
           endif;
        elseif ($actionMode == "update") :
           // Update values
           if ($rpId != "" && $rpText != "") :
              updateStmt("phoenix_group.report_process", "rp_id", $rpId, array("rp_reporttype", $rpType, "rp_text", $rpText, "rp_confidential", $rpConfidential), "usr_id = '" . $usrId . "'");
              $retArray = array("0",$rpId);
           else :
              $retArray = array("104","<err_no>104</err_no>\n","<err_desc>" . getLngt("Die Berichts-ID für die Aktualisierung fehlt!") . "</err_desc>\n");
           endif;
	      elseif ($actionMode == "delete") :
	         // Remove report
           deleteStmt("phoenix_group.report_process","rp_id = " . $rpId . " AND usr_id = '" . $usrId . "'");
           $retArray = array("0",$rpId);
        endif;        
	   endif;
	endif;
	return $retArray;
}


// Gets all objects (of a specified category) regarding the search value
// The first element of the returned array is an array with the header names
function getMetafieldData ($search, $category, $prefix = "%", $objType = "", $objId = "", $objAssocDataOnly = "") {
	global $db, $PHP_SELF, $f_hq_id;

	$retArray = array();
  if ($category == "") :
     $retArray = array("101","<err_no>101</err_no>\n","<err_desc>" . getLngt("Die Kategorie wurde nicht spezifiziert.") . "</err_desc>\n");
	elseif ($search == "" && $objAssocDataOnly == "") :
     $retArray = array("102","<err_no>102</err_no>\n","<err_desc>" . getLngt("Ein Suchbegriff ist nicht existent.") . "</err_desc>\n");
	elseif ($objAssocDataOnly == "1" && ($objType == "" || $objId == "")) :
     $retArray = array("103","<err_no>103</err_no>\n","<err_desc>" . getLngt("Bezugs-ID nicht angegeben.") . "</err_desc>\n");
  else :
     // Init
     if ($objAssocDataOnly == "1") : $search = "%%"; endif;
     $fromClause = "";
     $whereClause = "";

     $gHqId = true;
     $constFormSingleHQ = getParameterValue("0", "SYSTEM_FORM_SINGLE_HQ_" . $category, "0");
     if ($constFormSingleHQ != "" && $constFormSingleHQ != "0") :
        $gHqId = false;
     else :
        $constFormSingleHQ = getParameterValue("0", "SYSTEM_FORM_SINGLE_HQ", "0");
        if ($constFormSingleHQ != "" && $constFormSingleHQ != "0") :
           $gHqId = false;
        endif;
     endif;

     // Special handling regarding categories
     if ($category == "1") :
        // Contacts
        if ($objType == "" || $objType == "usr") : 
           $objType = "cs";    // If category is "contacts" init object type to "cs" if empty
           $objId = "";
        endif;
        if ($objType == "cs") :
           // Customer contacts
           $fromClause = ", customer AS cs, company AS cmp";
        elseif ($objType == "cr") :
           // Courier contacts
           $fromClause = ", courier AS cr, company AS cmp";
        endif;
     endif;

     // In the first step get the involved object IDs
     $sqlquery = "SELECT DISTINCT mtfv.mtfv_id"
                  . " FROM metafieldvalue AS mtfv, metafieldcategorykey AS mtfck, metafieldkey AS mtfk"
                  . " WHERE mtfv.mtfck_id = mtfck.mtfck_id      AND"
                  . "       mtfck.mtfc_id = '" . $category . "' AND"
                  . "       mtfck.mtfk_id = mtfk.mtfk_id        AND"
                  . "       mtfv.mtfv_value LIKE '" . $prefix . $search . "%'";

     // Special search for type co2cs, additional search in customer data
     if ($category == "1") :
        $sqlquery2 = "SELECT DISTINCT mtfv.mtfv_id"
                      . " FROM metafieldvalue AS mtfv, metafieldcategorykey AS mtfck, metafieldkey AS mtfk" . $fromClause
                      . " WHERE mtfv.mtfck_id = mtfck.mtfck_id         AND"
                      . "       mtfck.mtfc_id = '" . $category . "'    AND"
                      . "       mtfk.mtfk_id = mtfck.mtfk_id           AND"
                      . "       mtfk.mtfk_type = 'co2" . $objType . "' AND"
                      . "       " . $objType . "." . $objType . "_id = mtfv.mtfv_value  AND"
                      .         ($objId != "" && is_numeric($objId) && $objId > 0 ? " " . $objType . "." . $objType . "_id = '" . $objId . "' AND " : "")
                      . "       " . $objType . ".cmp_id = cmp.cmp_id   AND"
                      . "       (" . $objType . "." . $objType . "_eid LIKE '" . $prefix . $search . "%' OR"
                      . "        cmp.cmp_comp LIKE '" . $prefix . $search . "%')";

        if ($objAssocDataOnly == "1") :
           $sqlquery = $sqlquery2;
        else :
           $sqlquery = "(" . $sqlquery . ") UNION (" . $sqlquery2 . ")";
        endif;
     endif;

     $result = $db->query($sqlquery);
     if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
     while ($row = $result->fetch_assoc()):
           $objIdArray[] = $row["mtfv_id"];
     endwhile;
     $result->free();

     if (count($objIdArray) > 0) :
        // Next step get all object informations of all involved objects
        $whereClauseHQ = "";
        if (count($f_hq_id) > 0) :
           $whereClauseHQ = " AND mtfck.hq_id IN " . getSQLMandatorArray($f_hq_id) . " ";
           if ($gHqId) : $whereClauseHQ = " AND mtfck.hq_id = '0' "; endif;
        endif;

        $sqlquery = "SELECT mtfv.mtfck_id, mtfv.mtfv_id, mtfv.mtfv_value, mtfk.mtfk_type, mtfk.mtfk_name"
                     . " FROM metafieldvalue AS mtfv, metafieldcategorykey AS mtfck, metafieldkey AS mtfk"
                     . " WHERE mtfv.mtfv_id IN (" . implode($objIdArray, ",") . ") AND"
                     . "       mtfck.mtfc_id = '" . $category . "' AND"
                     . "       mtfk.mtfk_id = mtfck.mtfk_id AND "
                     . "       mtfv.mtfck_id = mtfck.mtfck_id "
                     .         $whereClauseHQ
                     . " ORDER BY mtfv.mtfv_id, mtfck.mtfck_sort";

        $result = $db->query($sqlquery);
        if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());

        $remObjId = "";
        $writeMtfkNameArray = true;
        $retArray[0] = array();
        $rowCount = 1;
        while ($row = $result->fetch_assoc()):

              if ($remObjId == "") :
                 $remObjId = $row["mtfv_id"];
              endif;
              if ($remObjId != $row["mtfv_id"]) :
                 $rowCount++;
                 $remObjId = $row["mtfv_id"];
                 $writeMtfkNameArray = false;
              endif;

              if ($writeMtfkNameArray) :
                 $headerField = $row["mtfk_name"];
                 $headerField = str_replace ("&nbsp;", " ", $headerField);
                 $retArray[0][] = $headerField;
              endif;

              $fieldValue = $row["mtfv_value"];

              if ($row["mtfk_type"] == "co2cs") :
                 $tmpCsId = $fieldValue;
                 $tmpCmpId = getFieldValueFromId("customer", "cs_id", $tmpCsId, "cmp_id");
                 $tmpCmpComp1 = trim(getFieldValueFromId("company", "cmp_id", $tmpCmpId, "cmp_comp"));

                 $fieldValue = getFieldValueFromId("customer", "cs_id", $fieldValue, "cs_eid");
                 if ($fieldValue != "" && $tmpCmpComp1 != "") :
                    $fieldValue .= " [" . trim($tmpCmpComp1) . "]";
                 endif;

              elseif ($row["mtfk_type"] == "co2cr") :
                 $tmpCsId = $fieldValue;
                 $tmpCmpId = getFieldValueFromId("courier", "cr_id", $tmpCsId, "cmp_id");
                 $tmpCmpComp1 = trim(getFieldValueFromId("company", "cmp_id", $tmpCmpId, "cmp_comp"));

                 $fieldValue = getFieldValueFromId("courier", "cr_id", $fieldValue, "cr_eid");
                 if ($fieldValue != "" && $tmpCmpComp1 != "") :
                    $fieldValue .= " [" . trim($tmpCmpComp1) . "]";
                 endif;

              elseif ($row["mtfk_type"] == "checkboxes_hq") :
                 $tmpHqArray = spliti(",", $row["mtfv_value"]);
                 $tmpHqArrayLen = count($tmpHqArray);
                 for ($i = 0; $i < $tmpHqArrayLen; $i++) :
                     $tmpHqArray[$i] = getFieldValueFromId("headquarters","hq_id",$tmpHqArray[$i],"hq_mnemonic");
                 endfor;
                 $fieldValue = implode(",",$tmpHqArray);

              elseif (substr($row["mtfk_type"],0,7) == "select:") :  // SELECT FIELD
                 $subTypeArray = spliti(":",$row["mtfk_type"]);
                 $table = $subTypeArray[1];
                 if ($table == "vht") :
                    $fieldValue = getFieldValueFromClause("metatype","mt_value","mt_type = 'vehicletype' AND mt_sort = '" . $row["mtfv_value"] . "' AND mt_objid = '0'");
                 endif;
                 if ($table == "grp") :
                    $fieldValue = getFieldValueFromId("groups","grp_id",$row["mtfv_value"],"grp_name");
                 endif;
                 if ($table == "br") :
                    $fieldValue = getFieldValueFromId("branch","br_id",$row["mtfv_value"],"br_name");
                 endif;
              endif;

              $fieldValue = str_replace ("&nbsp;", " ", $fieldValue);
              if ($retArray[$rowCount] == "") :
                 $retArray[$rowCount] = array($fieldValue);
              else :
                 $retArray[$rowCount][] = $fieldValue;
              endif;
        endwhile;

     endif;
  endif;
  return $retArray;
}

// Gets all contacts regarding the search value
function getContactList ($search, $category, $prefix = "%", $objType = "", $objId = "") {
	$retArray = getMetafieldData($search, $category, $prefix, $objType, $objId);
  return $retArray;
}

// Gets all contacts of a special object (cs, cr, etc.)
function getContactListOfObject ($search, $category, $prefix = "%", $objType = "", $objId = "") {
	$retArray = getMetafieldData($search, $category, $prefix, $objType, $objId, "1");
  return $retArray;
}

// Gets data of a single table
function getDbTableData($table, $fields, $whereClause = "", $mode = "0", $dbConnection = "") {
	global $db, $PHP_SELF;
  if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;

  $retArray = array();
	if ($table != "") :
	   $fieldsLen = 0;
	   if (is_array($fields)) :
	      $fieldsLen = count($fields);
	   endif;
	   if ($fieldsLen > 0) :
        if ($whereClause != "") : $whereClause = " WHERE " . $whereClause ; endif;
        $sqlStmt = "SELECT " . implode(",", $fields) . " FROM " . $table . " " . $whereClause;
        $result = $dbConnection->query($sqlStmt);
        if (DB::isError($result)) die ("$PHP_SELF: <br>$sqlStmt<br>" . $result->getMessage());

        // Header
        for ($i = 0; $i < $fieldsLen; $i++) :
            if ($mode == "1") :
               $retArray[0][] = $fields[$i];
            else :
               $retArray[0][$fields[$i]] = $fields[$i];
            endif;
        endfor;

        $count = 1;
        while ($row = $result->fetch_assoc()):
              for ($i = 0; $i < $fieldsLen; $i++) :
                  if ($mode == "1") :
                     $retArray[$count][] = $row[$fields[$i]];
                  else :
                     $retArray[$count][$fields[$i]] = $row[$fields[$i]];
                  endif;
              endfor;
              $count++;
        endwhile;     
        $result->free();
     else :
        $retArray = array("102","<err_no>102</err_no>\n","<err_desc>" . getLngt("Es wurde kein Feld spezifiziert.") . "</err_desc>\n");
	   endif;
	else :
	   $retArray = array("101","<err_no>101</err_no>\n","<err_desc>" . getLngt("Der Tabellenname ist nicht spezifiziert.") . "</err_desc>\n");
	endif;
  return $retArray;
}

// Gets all headquarters
function getHeadquartersList () {
	$retArray = getDbTableData("headquarters", array("hq_id", "hq_mnemonic", "hq_name"));
  return $retArray;
}

// Gets costcenters of a special customer
function getCostcenterListOfCustomer ($csId) {
  $retArray = getCostcenterList($csId, "");
  return $retArray;
}

// ----------------------------------------------------------------------------------------------------------------------------------------


// *************************
// * SHOPS AND BONUS CARDS *
// *************************

function getBonusCard ($bcId, $bcCode) {
	$retArray = array();
  if (($bcId != "" && is_numeric($bcId)) || $bcCode != "") :
     if ($bcId != "") :
        $tmpFields = getFieldsValueFromId("phoenix.bonuscard","bc_id",$bcId,array("bc_id","bc_code"));
     endif;
     if ($bcCode != "") :
        $tmpFields = getFieldsValueFromId("phoenix.bonuscard","bc_code",$bcCode,array("bc_id","bc_code"));
     endif;
     $retArray = array("0",$tmpFields[0],$tmpFields[1]);
  else:
     $retArray = array("201","<err_no>201</err_no>\n","<err_desc>" . getLngt("Request has emty items!") . "</err_desc>\n");
  endif;
  return $retArray;
}

function insertBonusCard ($bcCode) {
	$retArray = array();
  if ($bcCode != "") :
     if (!existsEntry("phoenix.bonuscard", array("bc_code",$bcCode))) :
        insertStmt("phoenix.bonuscard", array("bc_code",$bcCode));
        $bcId = getLastInsertId();
        $retArray = array("0",$bcId,$bcCode);
     else :
        $retArray = array("202","<err_no>202</err_no>\n","<err_desc>" . getLngt("Bonus card number does exist!") . "</err_desc>\n");
     endif;
  else:
     $retArray = array("201","<err_no>201</err_no>\n","<err_desc>" . getLngt("Bonus card number is empty!") . "</err_desc>\n");
  endif;
  return $retArray;
}

function updateBonusCard ($bcId, $bcCode) {
  global $db;
	$retArray = array();
	$bcCode = trim($bcCode);
  if (($bcId != "" && is_numeric($bcId)) && $bcCode != "") :
     $bcIdCheck = getFieldValueFromId("phoenix.bonuscard","bc_code",$bcCode,"bc_id");
     if ($bcId == $bcIdCheck) :
        $res = updateStmt("phoenix.bonuscard", "bc_id", $bcId, array("bc_code",$bcCode));
        if ($db->affected_rows > 0) :
           $retArray = array("0",$bcId,$bcCode);
        else :
           $retArray = array("202","<err_no>203</err_no>\n","<err_desc>" . getLngt("Update failed!") . "</err_desc>\n");
        endif;
     else :
        $retArray = array("202","<err_no>202</err_no>\n","<err_desc>" . getLngt("Bonus card number does exist!") . "</err_desc>\n");
     endif;
  else:
     $retArray = array("201","<err_no>201</err_no>\n","<err_desc>" . getLngt("Request has emty items!") . "</err_desc>\n");
  endif;
  return $retArray;
}

function getBonusCardOwner ($bcId, $objType = "", $objId = "", $orderByClause = "") {
	global $db, $PHP_SELF;
	$retArray = array();
  if ($bcId != "" || ($objType != "" && $objId != "" && is_numeric($objId))) :
     if ($orderByClause == "") : $orderByClause = "bc_id"; endif;
     if ($bcId != "" && is_numeric($bcId)) : $whereClause .= " AND bc_id = '" . $bcId . "' "; endif;
     if ($objType != "" && $objId != "" && is_numeric($objId)) : $whereClause .= " AND bco_obj_type = '" . $objType . "' AND bco_obj_id = '" . $objId . "' "; endif;
     $sqlStmt = "SELECT bc_id,bco_obj_type,bco_obj_id,bco_points FROM phoenix.bonuscardowner WHERE " . $whereClause . " ORDER BY " . $orderByClause;
     $retArray = getMatrixFromDbResultByStatement($sqlStmt);
     $retArray = array("0", $retArray);
  else:
     $retArray = array("201","<err_no>201</err_no>\n","<err_desc>" . getLngt("Request has emty items!") . "</err_desc>\n");
  endif;
  return $retArray;
}

function getBonusCardOwnerByClause ($whereClause, $orderByClause = "") {
	global $db, $PHP_SELF;
	$retArray = array();
  if ($whereClause != "") :
     if ($orderByClause == "") : $orderByClause = "bc_id"; endif;
     $sqlStmt = "SELECT bc_id,bco_obj_type,bco_obj_id,bco_points FROM phoenix.bonuscardowner WHERE " . $whereClause . " ORDER BY " . $orderByClause;
     $retArray = getMatrixFromDbResultByStatement($sqlStmt);
     $retArray = array("0", $retArray);
  else:
     $retArray = array("201","<err_no>201</err_no>\n","<err_desc>" . getLngt("Request has emty items!") . "</err_desc>\n");
  endif;
  return $retArray;
}

function setBonusCardOwner ($bcId, $objType, $objId, $bcoPoints) {
  global $db;
	$retArray = array();
  if (($bcId != "" && is_numeric($bcId)) && $objType != "" && ($objId != "" && is_numeric($objId))) :
     if ($bcoPoints == "" || !is_numeric($bcoPoints)) : $bcoPoints = 0; endif;
     if (existsEntry("phoenix.bonuscardowner", array("bcId",$bcId,"bco_obj_type",$objType,"bco_obj_id",$objId))) :
        $res = updateStmt("phoenix.bonuscardowner", "bc_id", $bcId, array("bco_points", $bcoPoints), "bco_obj_type = '" . $objType . "' AND bco_obj_id = '" . $objId . "'");
        if ($db->affected_rows > 0) :
           $retArray = array("0","OK");
        else :
           $retArray = array("203","<err_no>203</err_no>\n","<err_desc>" . getLngt("Row does exist but update failed!") . "</err_desc>\n");
        endif;
     else :
        $res = insertStmt("phoenix.bonuscardowner", array("bc_id", $bcId, "bco_obj_type", $objType, "bco_obj_id", $objId, "bco_points", $bcoPoints));
        if ($db->affected_rows > 0) :
           $retArray = array("0","OK");
        else :
           $retArray = array("204","<err_no>204</err_no>\n","<err_desc>" . getLngt("Row has not been inserted!") . "</err_desc>\n");
        endif;
     endif;
  else:
     $retArray = array("201","<err_no>201</err_no>\n","<err_desc>" . getLngt("Request has emty items!") . "</err_desc>\n");
  endif;
  return $retArray;
}

function addBonusCardOwnerPoints ($bcId, $objType, $objId, $bcoPoints) {
  global $db;
	$retArray = array();
  if (($bcId != "" && is_numeric($bcId)) && $objType != "" && ($objId != "" && is_numeric($objId)) && ($bcoPoints != "" && is_numeric($bcoPoints))) :
     if (existsEntry("phoenix.bonuscardowner", array("bcId",$bcId,"bco_obj_type",$objType,"bco_obj_id",$objId))) :
        $res = updateStmt("phoenix.bonuscardowner", "bc_id", $bcId, array("bco_points", $bcoPoints), "bco_obj_type = '" . $objType . "' AND bco_obj_id = '" . $objId . "'");
        if ($db->affected_rows > 0) :
           $retArray = array("0","OK");
        else :
           $retArray = array("203","<err_no>203</err_no>\n","<err_desc>" . getLngt("Row does exist but update failed!") . "</err_desc>\n");
        endif;
     else :
        $retArray = array("202","<err_no>202</err_no>\n","<err_desc>" . getLngt("Row does not exist!") . "</err_desc>\n");
     endif;
  else:
     $retArray = array("201","<err_no>201</err_no>\n","<err_desc>" . getLngt("Request has emty items!") . "</err_desc>\n");
  endif;
  return $retArray;
}

function getBonusCardSingleTransaction ($bctaId) {
  if ($bctaId != "" && is_numeric($bctaId)) :
     $tmpFields = getFieldsValueFromId("phoenix.bonuscardtransaction","bcta_id",$bctaId,array("bcta_id","bc_id","bcta_obj_type","bcta_obj_id","shp_id","bcta_value","bcta_points","bcta_createtime","bcta_remark"));
     $retArray = array_merge(array("0"), $tmpFields);
  else:
     $retArray = array("201","<err_no>201</err_no>\n","<err_desc>" . getLngt("Request has emty items!") . "</err_desc>\n");
  endif;
  return $retArray;
}

function getBonusCardTransactionList ($dateFrom, $dateTo, $orderByClause = "", $objType = "", $objId = "", $shpId = "") {
	global $db, $PHP_SELF;
	$retArray = array();
  if ($dateFrom != "" && $dateTo != "") :
     if ($orderByClause == "") : $orderByClause = "bcta_id"; endif;
     $whereClause = "bcta_createtime >= '" . $dateFrom . "' AND bcta_createtime <= '" . $dateTo . "'";
     if ($shpId != "" && is_numeric($shpId)) : $whereClause .= " AND shp_id = '" . $shpId . "' "; endif;
     if ($objType != "" && $objId != "" && is_numeric($objId)) : $whereClause .= " AND bcta_obj_type = '" . $objType . "' AND bcta_obj_id = '" . $objId . "' "; endif;
     $sqlStmt = "SELECT bcta_id,bc_id,bcta_obj_type,bcta_obj_id,shp_id,bcta_value,bcta_points,bcta_createtime,bcta_remark"
              . "  FROM phoenix.bonuscardtransaction WHERE " . $whereClause . " ORDER BY " . $orderByClause;
     $retArray = getMatrixFromDbResultByStatement($sqlStmt);
     $retArray = array("0", $retArray);
  else:
     $retArray = array("201","<err_no>201</err_no>\n","<err_desc>" . getLngt("Request has emty items!") . "</err_desc>\n");
  endif;
  return $retArray;
}

function getBonusCardTransactionListByClause ($whereClause, $orderByClause = "") {
	global $db, $PHP_SELF;
	$retArray = array();
  if ($whereClause != "") :
     if ($orderByClause == "") : $orderByClause = "bcta_id"; endif;
     $sqlStmt = "SELECT bcta_id,bc_id,bcta_obj_type,bcta_obj_id,shp_id,bcta_value,bcta_points,bcta_createtime,bcta_remark"
              . "  FROM phoenix.bonuscardtransaction WHERE " . $whereClause . " ORDER BY " . $orderByClause;
     $retArray = getMatrixFromDbResultByStatement($sqlStmt);
     $retArray = array("0", $retArray);
  else:
     $retArray = array("201","<err_no>201</err_no>\n","<err_desc>" . getLngt("Request has emty items!") . "</err_desc>\n");
  endif;
  return $retArray;
}

function setBonusCardSingleTransaction ($bcId, $objType, $objId, $shpId, $bctaValue, $bctaPoints, $bctaRemark) {
	global $db, $PHP_SELF;
	$retArray = array();
  if (($bcId != "" && is_numeric($bcId)) && $objType != "" && ($objId != "" && is_numeric($objId))) :
     if (existsEntry("phoenix.bonuscard", array("bc_id",$bcId))) :
        if (($objType == "usr" && !existsEntry("phoenix.user", array("usr_id",$objId))) || 
            ($objType == "cmp" && !existsEntry("phoenix.company", array("cmp_id",$objId)))) :
           if (existsEntry("phoenix.shop", array("shp_id",$shpId))) :
              if ($bctaValue == "") : $bctaValue = 0; endif;
              if ($bctaPoints == "") : $bctaPoints = 0; endif;
              $bctaValue = str_replace (",", ".", $bctaValue);
              $bctaPoints = str_replace (",", ".", $bctaPoints);
              if (is_numeric($bctaValue) && is_numeric($bctaPoints)) :
                 TA(B);
                 $currentTime = getDateTime("0");
                 $res = insertStmt("phoenix.bonuscardtransaction", array("bc_id", $bcId, "bcta_obj_type", $objType, "bcta_obj_id", $objId, "shp_id", $shpId, "bcta_value", $bctaValue, "bcta_points", $bctaPoints, "bcta_createtime ", $currentTime, "bcta_remark ", $bctaRemark));
                 if ($db->affected_rows > 0) :
                    $bctaId = getLastInsertId();
                    // Add bonuscard points to "bonus card owner"
                    $tmpArr = addBonusCardOwnerPoints($bcId, $objType, $objId, $bcoPoints);
                    if ($tmpArr[0] == "0") :
                       $retArray = array("0",$bctaId);
                       TA(C);
                    else :
                       TA(R);
                    endif;
                 else :
                    $retArray = array("206","<err_no>206</err_no>\n","<err_desc>" . getLngt("Row has not been inserted!") . "</err_desc>\n");
                    TA(R);
                 endif;
                 TA(E);
              else :
                 $retArray = array("205","<err_no>205</err_no>\n","<err_desc>" . getLngt("Value or points is not numeric!") . "</err_desc>\n");
              endif;
           else :
              $retArray = array("204","<err_no>204</err_no>\n","<err_desc>" . getLngt("Shop does not exist!") . "</err_desc>\n");
           endif;
        else :
           $retArray = array("203","<err_no>203</err_no>\n","<err_desc>" . getLngt("User or company does not exist!") . "</err_desc>\n");
        endif;
     else :
        $retArray = array("202","<err_no>202</err_no>\n","<err_desc>" . getLngt("Bonuscard does not exist!") . "</err_desc>\n");
     endif;
  else:
     $retArray = array("201","<err_no>201</err_no>\n","<err_desc>" . getLngt("Request has emty items!") . "</err_desc>\n");
  endif;
  return $retArray;
}

function getShop ($shpId) {
	$retArray = array();
  if ($shpId != "" && is_numeric($shpId)) :
     $tmpFields = getFieldsValueFromId("phoenix.shop","bc_id",$bcId,array("shp_id","hq_id","cmp_id","shp_bc_active","shp_bc_factor","shp_bc_ta_limit"));
     $retArray = array("0",$tmpFields[0],$tmpFields[1],$tmpFields[2],$tmpFields[3],$tmpFields[4],$tmpFields[5]);
  else:
     $retArray = array("201","<err_no>201</err_no>\n","<err_desc>" . getLngt("Request has emty items!") . "</err_desc>\n");
  endif;
  return $retArray;
}

function getShopByClause ($whereClause, $orderByClause = "") {
	global $db, $PHP_SELF;
	$retArray = array();
  if ($whereClause != "") :
     if ($orderByClause == "") : $orderByClause = "bcta_id"; endif;
     $sqlStmt = "SELECT shp_id,hq_id,cmp_id,shp_bc_active,shp_bc_factor,shp_bc_ta_limit FROM phoenix.shop WHERE " . $whereClause . " ORDER BY " . $orderByClause;
     $retArray = getMatrixFromDbResultByStatement($sqlStmt);
     $retArray = array("0", $retArray);
  else:
     $retArray = array("201","<err_no>201</err_no>\n","<err_desc>" . getLngt("Request has emty items!") . "</err_desc>\n");
  endif;
  return $retArray;
}

function insertShop ($shpName, $hqId, $shpBcActive = "1", $shpBcFactor = "1", $shpBcTaLimit = "100") {
	global $db, $PHP_SELF;
	$retArray = array();
	$shpName = trim($shpName);
  if ($shpName != "" && $hqId != "" && is_numeric($hqId)) :
     if (existsEntry("phoenix.headquarters", array("hq_id",$hqId))) :
        $sqlStmt = "SELECT shp.shp_id FROM phoenix.shop AS shp, phoenix.company AS cmp WHERE cmp.cmp_comp = '" . $shpName . "' AND cmp.cmp_id = shp.shp_id AND shp.hq_id = '" . $hqId . "'";
        $shpId = getOneStmt($sqlStmt, "shp_id");
        if ($shpId == "") :
           TA(B);
           $currentTime = getDateTime("0");
           insertStmt("phoenix.company", array("cmp_comp", $shpName, "cmp_comp2", "", "cmp_hsno", "", "cmp_iln", "", "cmp_tax_idno", "", "cmp_stax_idno", "", 
                      "cmp_bank", "", "cmp_bankno", "", "cmp_bankacc", "", "cmp_iban", "", "cmp_swift", "", "cmp_authenticated", "1", "cmp_visible", "1", 
                      "cmp_remark", "", "cmp_remark2", "", "cmp_new_date", $currentTime, "cmp_modify_status", "1"));
           $cmpIdNew = getLastInsertId();
           insertStmt("phoenix.shop", array("hq_id", $hqId, "cmp_id", $cmpIdNew, "shp_bc_active", $shpBcActive, "shp_bc_factor", $shpBcFactor, "shp_bc_ta_limit", $shpBcTaLimit));
           $shpIdNew = getLastInsertId();
           TA(C);
           TA(E);
           if ($shpIdNew != "" && is_numeric($shpIdNew) && $cmpIdNew != "" && is_numeric($cmpIdNew)) :
              $retArray = array("0",$shpIdNew,$cmpIdNew);
           else :
              $retArray = array("204","<err_no>204</err_no>\n","<err_desc>" . getLngt("Shop insertion failed by transaction abort!") . "</err_desc>\n");
           endif;
        else :
           $retArray = array("203","<err_no>203</err_no>\n","<err_desc>" . getLngt("Shop does exist for the center!") . "</err_desc>\n");
        endif;
     else :
        $retArray = array("202","<err_no>202</err_no>\n","<err_desc>" . getLngt("Center does exist!") . "</err_desc>\n");
     endif;
  else:
     $retArray = array("201","<err_no>201</err_no>\n","<err_desc>" . getLngt("Request has emty items!") . "</err_desc>\n");
  endif;
  return $retArray;
}

function updateShop ($shpId, $shpName, $shpBcActive, $shpBcFactor, $shpBcTaLimit) {
  global $db;
	$retArray = array();
  if (($shpId != "" && is_numeric($shpId))) :
     $updArrayShop = array();
     $updArrayCompany = array();
     if ($shpName != ""):
        $updArrayCompany = array_merge($updArrayCompany, array("cmp_comp", $shpName));
     endif;
     if ($shpBcActive != ""):
        $updArrayShop = array_merge($updArrayShop, array("shp_bc_active", $shpBcActive));
     endif;
     if ($shpBcFactor != ""):
        $updArrayShop = array_merge($updArrayShop, array("shp_bc_factor", $shpBcFactor));
     endif;
     if ($shpBcTaLimit != ""):
        $updArrayShop = array_merge($updArrayShop, array("shp_bc_ta_limit", $shpBcTaLimit));
     endif;
     if (count($updArrayShop) > 0) :
        $res = updateStmt("phoenix.shop", "shp_id", $shpId, $updArrayShop);
        $aRows1 = $db->affected_rows;
        $cmpId = getFieldValueFromId("phoenix.shop","shp_id",$shpId,"cmp_id");
        $res2 = updateStmt("phoenix.company", "cmp_id", $cmpId, $updArrayCompany);
        $aRows2 = $db->affected_rows;
        if ($aRows1 > 0 && $aRows2 > 0) :
           $retArray = array("0","OK");
        else :
           $retArray = array("203","<err_no>203</err_no>\n","<err_desc>" . getLngt("Update failed!") . "</err_desc>\n");
        endif;
     else :
        $retArray = array("202","<err_no>202</err_no>\n","<err_desc>" . getLngt("Update failed because of emty items!") . "</err_desc>\n");
     endif;
  else:
     $retArray = array("201","<err_no>201</err_no>\n","<err_desc>" . getLngt("Request has emty items!") . "</err_desc>\n");
  endif;
  return $retArray;
}

function getCoupon ($cpnId, $cpnCode) {
	$retArray = array();
  if (($cpnId != "" && is_numeric($cpnId)) || $cpnCode != "") :
     if ($cpnId != "") :
        $tmpFields = getFieldsValueFromId("phoenix.coupon","bc_id",$cpnId,array("bc_id","cpn_code"));
     endif;
     if ($cpnCode != "") :
        $tmpFields = getFieldsValueFromId("phoenix.coupon","cpn_code",$cpnCode,array("bc_id","cpn_code"));
     endif;
     $retArray = array("0",$tmpFields[0],$tmpFields[1]);
  else:
     $retArray = array("201","<err_no>201</err_no>\n","<err_desc>" . getLngt("Request has emty items!") . "</err_desc>\n");
  endif;
  return $retArray;
}

function insertCoupon ($cpnCode) {
	$retArray = array();
  if ($cpnCode != "") :
     if (!existsEntry("phoenix.coupon", array("cpn_code",$cpnCode))) :
        insertStmt("phoenix.coupon", array("cpn_code",$cpnCode));
        $cpnId = getLastInsertId();
        $retArray = array("0",$cpnId,$cpnCode);
     else :
        $retArray = array("202","<err_no>202</err_no>\n","<err_desc>" . getLngt("Coupon number does exist!") . "</err_desc>\n");
     endif;
  else:
     $retArray = array("201","<err_no>201</err_no>\n","<err_desc>" . getLngt("Coupon number is empty!") . "</err_desc>\n");
  endif;
  return $retArray;
}

function updateCoupon ($cpnId, $cpnCode) {
  global $db;
	$retArray = array();
	$cpnCode = trim($cpnCode);
  if (($cpnId != "" && is_numeric($cpnId)) && $cpnCode != "") :
     $cpnIdCheck = getFieldValueFromId("phoenix.coupon","cpn_code",$cpnCode,"cpn_id");
     if ($cpnId == $cpnIdCheck) :
        $res = updateStmt("phoenix.coupon", "cpn_id", $cpnId, array("cpn_code",$cpnCode));
        if ($db->affected_rows > 0) :
           $retArray = array("0",$cpnId,$cpnCode);
        else :
           $retArray = array("203","<err_no>203</err_no>\n","<err_desc>" . getLngt("Update failed!") . "</err_desc>\n");
        endif;
     else :
        $retArray = array("202","<err_no>202</err_no>\n","<err_desc>" . getLngt("Coupon number does exist!") . "</err_desc>\n");
     endif;
  else:
     $retArray = array("201","<err_no>201</err_no>\n","<err_desc>" . getLngt("Request has emty items!") . "</err_desc>\n");
  endif;
  return $retArray;
}

function getCouponSingleTransaction ($cpnta_id) {
  if ($cpnta_id != "" && is_numeric($cpnta_id)) :
     $tmpFields = getFieldsValueFromId("phoenix.coupontransaction","bcta_id",$cpnta_id,array("cpnta_id","cpn_id","cpnta_obj_type","cpnta_obj_id","cpnta_createtime"));
     $retArray = array_merge(array("0"), $tmpFields);
  else:
     $retArray = array("201","<err_no>201</err_no>\n","<err_desc>" . getLngt("Request has emty items!") . "</err_desc>\n");
  endif;
  return $retArray;
}

function getCouponTransactionList ($dateFrom, $dateTo, $orderByClause = "", $objType = "", $objId = "") {
	global $db, $PHP_SELF;
	$retArray = array();
  if ($dateFrom != "" && $dateTo != "") :
     if ($orderByClause == "") : $orderByClause = "cpnta_id"; endif;
     $whereClause = "cpnta_createtime >= '" . $dateFrom . "' AND cpnta_createtime <= '" . $dateTo . "'";
     if ($objType != "" && $objId != "" && is_numeric($objId)) : $whereClause .= " AND cpnta_obj_type = '" . $objType . "' AND cpnta_obj_id = '" . $objId . "' "; endif;
     $sqlStmt = "SELECT cpnta_id,cpn_id,cpnta_obj_type,cpnta_obj_id,cpnta_createtime FROM phoenix.coupontransaction WHERE " . $whereClause . " ORDER BY " . $orderByClause;
     $retArray = getMatrixFromDbResultByStatement($sqlStmt);
     $retArray = array("0", $retArray);
  else:
     $retArray = array("201","<err_no>201</err_no>\n","<err_desc>" . getLngt("Request has emty items!") . "</err_desc>\n");
  endif;
  return $retArray;
}

function getCouponTransactionListByClause ($whereClause, $orderByClause = "") {
	global $db, $PHP_SELF;
	$retArray = array();
  if ($whereClause != "") :
     if ($orderByClause == "") : $orderByClause = "bcta_id"; endif;
     $sqlStmt = "SELECT cpnta_id,cpn_id,cpnta_obj_type,cpnta_obj_id,cpnta_createtime FROM phoenix.coupontransaction WHERE " . $whereClause . " ORDER BY " . $orderByClause;
     $retArray = getMatrixFromDbResultByStatement($sqlStmt);
     $retArray = array("0", $retArray);
  else:
     $retArray = array("201","<err_no>201</err_no>\n","<err_desc>" . getLngt("Request has emty items!") . "</err_desc>\n");
  endif;
  return $retArray;
}

function setCouponSingleTransaction ($cpnId, $objType, $objId) {
	global $db, $PHP_SELF;
	$retArray = array();
  if (($cpnId != "" && is_numeric($cpnId)) && $objType != "" && ($objId != "" && is_numeric($objId))) :
     if (existsEntry("phoenix.coupon", array("cpn_id",$cpnId))) :
        if (($objType == "usr" && !existsEntry("phoenix.user", array("usr_id",$objId))) || 
            ($objType == "cmp" && !existsEntry("phoenix.company", array("cmp_id",$objId)))) :
           if (true) :  // existsEntry("phoenix.xxxx", array("xxxx_id",$xxxxId))
              // if ($cpntaValue == "") : $cpntaValue = 0; endif;
              // if ($cpntaPoints == "") : $cpntaPoints = 0; endif;
              // $cpntaValue = str_replace (",", ".", $cpntaValue);
              // $cpntaPoints = str_replace (",", ".", $cpntaPoints);
              if (true) :  // is_numeric($bctaValue) && is_numeric($bctaPoints)
                 $currentTime = getDateTime("0");
                 $res = insertStmt("phoenix.coupontransaction", array("cpn_id", $cpnId, "cpnta_obj_type", $objType, "cpnta_obj_id", $objId));  // , "shp_id", $shpId, "bcta_value", $bctaValue, "bcta_points", $bctaPoints, "bcta_createtime ", $currentTime, "bcta_remark ", $bctaRemark
                 if ($db->affected_rows > 0) :
                    $cpntaId = getLastInsertId();
                    $retArray = array("0",$cpntaId);
                 else :
                    $retArray = array("206","<err_no>206</err_no>\n","<err_desc>" . getLngt("Row has not been inserted!") . "</err_desc>\n");
                 endif;
              else :
                 $retArray = array("205","<err_no>205</err_no>\n","<err_desc>" . getLngt("Value or points is not numeric!") . "</err_desc>\n");
              endif;
           else :
              $retArray = array("204","<err_no>204</err_no>\n","<err_desc>" . getLngt("XXXX does not exist!") . "</err_desc>\n");
           endif;
        else :
           $retArray = array("203","<err_no>203</err_no>\n","<err_desc>" . getLngt("User or company does not exist!") . "</err_desc>\n");
        endif;
     else :
        $retArray = array("202","<err_no>202</err_no>\n","<err_desc>" . getLngt("Coupon does not exist!") . "</err_desc>\n");
     endif;
  else:
     $retArray = array("201","<err_no>201</err_no>\n","<err_desc>" . getLngt("Request has emty items!") . "</err_desc>\n");
  endif;
  return $retArray;
}

function getGiftCoupon ($gcpn_id, $gcpn_code) {
	$retArray = array();
  if (($gcpn_id != "" && is_numeric($gcpn_id)) || $gcpn_code != "") :
     if (($gcpn_id != "" && is_numeric($gcpn_id))) :
         $whereClause = "gcpn_id = '" . $gcpn_id . "'";
     elseif ($gcpn_code != "") :
         $whereClause = "gcpn_code = '" . $gcpn_code . "'";
     endif;
     $sqlStmt = "SELECT gcpn_id,gcpn_code,gcpn_recipient,gcpn_valid,gcpn_value,gcpn_freetext,gcpn_image_name,gcpn_payment_code,gcpn_createtime"
              . "  FROM phoenix.giftcoupon WHERE " . $whereClause . " ORDER BY " . $orderByClause;
     $retArray = getMatrixFromDbResultByStatement($sqlStmt);
     $retArray = array_merge(array("0"), $retArray);
  else:
     $retArray = array("201","<err_no>201</err_no>\n","<err_desc>" . getLngt("Request has emty items!") . "</err_desc>\n");
  endif;
  return $retArray;
}

function getGiftCouponByClause ($whereClause, $orderByClause = "") {
	global $db, $PHP_SELF;
	$retArray = array();
  if ($whereClause != "") :
     if ($orderByClause == "") : $orderByClause = "bcta_id"; endif;
     $sqlStmt = "SELECT gcpn_id,gcpn_code,gcpn_recipient,gcpn_valid,gcpn_value,gcpn_freetext,gcpn_image_name,gcpn_payment_code,gcpn_createtime"
              . "  FROM phoenix.giftcoupon WHERE " . $whereClause . " ORDER BY " . $orderByClause;
     $retArray = getMatrixFromDbResultByStatement($sqlStmt);
     $retArray = array("0", $retArray);
  else:
     $retArray = array("201","<err_no>201</err_no>\n","<err_desc>" . getLngt("Request has emty items!") . "</err_desc>\n");
  endif;
  return $retArray;
}

function insertGiftCoupon ($gcpnCode, $gcpnRecipient, $gcpnValue, $gcpnImageName = "", $gcpnValid = "1", $gcpnFreetext = "", $gcpnPaymentCode = "") {
	global $db, $PHP_SELF;
	$retArray = array();
	$gcpnCode = trim($gcpnCode);
  if ($gcpnCode != "" && $gcpnRecipient != "" && $gcpnValue != "") :
     if (!existsEntry("phoenix.giftcoupon", array("gcpn_code",$gcpnCode))) :
        // $sqlStmt = "SELECT shp.shp_id FROM phoenix.shop AS shp, phoenix.company AS cmp WHERE cmp.cmp_comp = '" . $shpName . "' AND cmp.cmp_id = shp.shp_id AND shp.hq_id = '" . $hqId . "'";
        // $shpId = getOneStmt($sqlStmt, "shp_id");
        if (true || $shpId == "") :
           $gcpnValue = str_replace (",", ".", $gcpnValue);
           if (is_numeric($gcpnValue)) :
              $currentTime = getDateTime("0");  // gcpn_createtime
              insertStmt("phoenix.giftcoupon", array("gcpn_code", $gcpnCode, "gcpn_recipient", $gcpnRecipient, "gcpn_valid", $gcpnValid, "gcpn_value", $gcpnValue, 
                         "gcpn_freetext", $gcpnFreetext, "gcpn_image_name", $gcpnImageName, "gcpn_payment_code", $gcpnPaymentCode, "gcpn_createtime", $currentTime));
              $gcpnIdNew = getLastInsertId();
              if ($gcpnIdNew != "" && is_numeric($gcpnIdNew)) :
                 $retArray = array("0",$gcpnIdNew);
              else :
                 $retArray = array("205","<err_no>205</err_no>\n","<err_desc>" . getLngt("Gift coupon insertion failed by transaction abort!") . "</err_desc>\n");
              endif;
           else :
              $retArray = array("204","<err_no>204</err_no>\n","<err_desc>" . getLngt("Value is not numeric!") . "</err_desc>\n");
           endif;
        else :
           $retArray = array("203","<err_no>203</err_no>\n","<err_desc>" . getLngt("Gift coupon does exist for the center!") . "</err_desc>\n");
        endif;
     else :
        $retArray = array("202","<err_no>202</err_no>\n","<err_desc>" . getLngt("Gift coupon does exist!") . "</err_desc>\n");
     endif;
  else:
     $retArray = array("201","<err_no>201</err_no>\n","<err_desc>" . getLngt("Request has emty items!") . "</err_desc>\n");
  endif;
  return $retArray;
}

function updateGiftCoupon ($gcpnId, $gcpnCode, $gcpnRecipient, $gcpnValue, $gcpnImageName = "", $gcpnValid = "1", $gcpnFreetext = "", $gcpnPaymentCode = "") {
  global $db;
	$retArray = array();
  if (($gcpnId != "" && is_numeric($gcpnId))) :
  
     $updArray = array();
     $doContinue = true;
     if ($gcpnCode != ""):
        $gcpnIdCheck = getFieldValueFromId("phoenix.giftcoupon","gcpn_code",$gcpnCode,"gcpn_id");
        if ($gcpnId == $gcpnIdCheck) :
           $updArray = array_merge($updArray, array("gcpn_code", $gcpnCode));
        else :
           $doContinue = false;
           $retArray = array("205","<err_no>205</err_no>\n","<err_desc>" . getLngt("Gift coupon number does exist!") . "</err_desc>\n");
        endif;
     endif;

     if ($doContinue && $gcpnRecipient != "") :
        $updArray = array_merge($updArray, array("gcpn_recipient", $gcpnRecipient));
     endif;

     if ($doContinue && $gcpnValue != "") :
        $gcpnValue = str_replace (",", ".", $gcpnValue);
        if (is_numeric($gcpnValue)) :
           $updArray = array_merge($updArray, array("gcpn_recipient", $gcpnRecipient));
        else :
           $doContinue = false;
           $retArray = array("206","<err_no>206</err_no>\n","<err_desc>" . getLngt("Value is not numeric!") . "</err_desc>\n");
        endif;
     endif;

     if ($doContinue) :
        if ($gcpnImageName != ""):
           $updArray = array_merge($updArray, array("gcpn_image_name", $gcpnImageName));
        endif;
     
        if (count($updArray) > 0) :
           $res = updateStmt("phoenix.giftcoupon", "gcpn_id", $gcpnId, $updArray);
           if ($db->affected_rows > 0) :
              $retArray = array("0","OK");
           else :
              $retArray = array("204","<err_no>204</err_no>\n","<err_desc>" . getLngt("Update failed!") . "</err_desc>\n");
           endif;
        else :
           $retArray = array("203","<err_no>203</err_no>\n","<err_desc>" . getLngt("Update failed because of emty items!") . "</err_desc>\n");
        endif;
     else :
        $retArray = array("202","<err_no>202</err_no>\n","<err_desc>" . getLngt("Update failed because of incorrect items!") . "</err_desc>\n");
     endif;
  else:
     $retArray = array("201","<err_no>201</err_no>\n","<err_desc>" . getLngt("Request has emty items!") . "</err_desc>\n");
  endif;
  return $retArray;
}

// ---------------------------------------------
?>
