<?php
/*=======================================================================
 *
 * survey.php
 *
 * Autor: Marc Vollmann
 *
 =======================================================================*/

include_once ("../include/mcglobal.inc.php");
include_once ("../include/inc_parseXML.inc.php");
include_once ('../include/email/htmlMimeMail.php');
// include_once ("../include/inc_customer.inc.php");


// Check HTTP-Parameters
getSecHttpVars("1",array("f_act", "op", "jb", "f_annotation", "f_01", "f_02", "f_03", "f_04", "f_05", "f_06", "f_07", "f_08", "f_09"));

// Get the IP of the current client calling the page
$currentClientIP = trim($_SERVER['REMOTE_ADDR']);


// Write DB log
function writeToLogRemoteDB($logoId, $hqId, $jb_id, $usrId, $crId, $crSid, $csId, $logoDescription, $atId = "0", $ptId = "0", $empId = "0") {
  global $db_conn, $PHP_SELF;
  $tmpArray = array("logo_id", $logoId, "hq_id", $hqId, "jb_id", $jb_id, "usr_id", $usrId, "cr_id", $crId, "cr_sid", $crSid, "cs_id", $csId, "at_id", $atId, "pt_id", $ptId, "emp_id", $empId, "logo_description", $logoDescription);
  $result = $db_conn->query("INSERT INTO phoenix_log.log (logo_id, hq_id, cs_id, logo_description) VALUES ('" . $logoId . "','" . $hqId . "','" . $csId . "','" . $logoDescription . "')");
  return $result;
}

// Remove postparser tags
function convertSpecialMC($op) {
  $op = convertSpecial($op);
  if (substr($op, 0, 12) == "<postparser>") : $op = substr($op, 12); endif;
  if (substr($op, -13) == "</postparser>") : $op = substr($op, 0, -13); endif;
  if (substr($op, 0, 16) == "%3Cpostparser%3E") : $op = substr($op, 16); endif;
  if (substr($op, -17) == "%3C/postparser%3E") : $op = substr($op, 0, -17); endif;
  return $op;
}

function dcSpecial($value, $dcStr = "__") {
   global $eca;
   $len = strlen($dcStr);
   if ((substr($value, 0, $len) == $dcStr) && (substr($value, -$len) == $dcStr)) :
      // Extract value from identificator-box
      $value = substr($value, strlen($dcStr), -strlen($dcStr));      

      // Decrypt the encrypted value
      if (is_numeric($value)) :
         $value = (((((((($value - $eca[4]) / 2) - $eca[3]) / 2) - $eca[2]) / 2) - $eca[1]) / 2) - $eca[0];
      else :
         $value = urldecode($value);
      endif;      
   endif;
   return $value;
}

$pageTitel = getLngt("Bewertung durch den Kunden");
$generalOutErrMsg = getLngt("Wir konnten Ihre Anfrage leider nicht bearbeiten. Eine automatische Mail an die Systemadministration wurde versendet.");

$jb = dcSpecial($jb);

$out = $generalOutErrMsg;
$imgIdentifyer = "adsg";  // Init

$questionArray = array("Wurden Sie durch unsere Mitarbeiter am Telefon kompetent beraten?",
                       "Waren Sie mit den Bereitstellzeiten und  Durchführungszeiten zufrieden?",
                       "Entsprachen Erscheinungsbild und Freundlichkeit der Kuriere Ihren Vorstellungen?",
                       "Wurden Ihre Anforderungen zur Auftragsdurchführung durch den Kurierunternehmer umgesetzt?",
                       "Würden Sie den Stadtboten weiterempfehlen?");
$questionArrayLen = count($questionArray);


if ($op != "" && $jb != "" && is_numeric($jb)) :

   $constExtDbInst = getExternalMetaDbInst();
   $dbMetaConn = getDbConnectionSpecial($constExtDbInst, $dbname, $dblogin, $dbpassword);

   // Check existence of the hash value
   if (existsEntry("meta_object.metaobject",array("mo_hash",$op), $dbMetaConn)) :

      $moId      = getFieldValueFromId("meta_object.metaobject", "mo_hash", $op, "mo_id", $dbMetaConn);
      $moIdRefDB = getFieldValueFromId("meta_object.metaobject", "mo_id", $moId, "mo_id_ref_db", $dbMetaConn);
      $objType   = getFieldValueFromId("meta_object.metaobject", "mo_id", $moId, "mo_obj_type", $dbMetaConn);
      $objId     = getFieldValueFromId("meta_object.metaobject", "mo_id", $moId, "mo_obj_id", $dbMetaConn);

      if ($moId != "" && $moId > "0") :

         // Get database instance
         $dbInst = getFieldValueFromId("meta_object.metaobject", "mo_id", $moIdRefDB, "mo_value", $dbMetaConn);

         if ($dbInst != "") :

            // Get database connection
            $db_conn = getDbConnectionSpecial($dbInst, $dbname, $dblogin, $dbpassword);

            // Get header and footer image global identifyer for target database
            // $imgIdentifyer = getFieldValueFromClause("parameter", "par_value", "par_key = 'MD_GLOBAL_SHORTNAME' AND hq_id = '0'", $db_conn);
            $imgIdentifyer = $db_conn->getOne("SELECT par_value FROM phoenix.parameter WHERE par_key = 'MD_GLOBAL_SHORTNAME' AND hq_id = '0'");
// echo "imgIdentifyer: " . $imgIdentifyer . "<br>";
            $trId = $db_conn->getOne("SELECT tr.tr_id FROM phoenix.tour AS tr WHERE tr.jb_id = '" . $jb . "' AND tr.tr_sort = '1' ");

            // if (!existsEntry("phoenix.genericdatacontainer",array("gdc_obj_type","jb","gdc_obj_id",$jb,"gdc_gen_fieldname",'survey'), $db_conn)) :
            if (!existsEntry("phoenix.genericdatacontainer",array("gdc_obj_type","tr","gdc_obj_id",$trId,"gdc_gen_fieldname",'survey'), $db_conn)) :

               if ($f_act == "send") :
   
                  if ($objType == "cs") :
   
                        $cmpId = $db_conn->getOne("SELECT cs.cmp_id FROM phoenix.customer AS cs WHERE cs.cs_id = '" . $objId . "' ");
                        $csEid = $db_conn->getOne("SELECT cs.cs_eid FROM phoenix.customer AS cs WHERE cs.cs_id = '" . $objId . "' ");
   
                        if ($cmpId != "" && $cmpId > "0") :
   
                           $hqId = $db_conn->getOne("SELECT cs.hq_id FROM phoenix.customer AS cs WHERE cs.cs_id = '" . $objId . "' ");
   
                           TA("B");
   
                           // Store responses
                           $err = "";
                           for ($i = 1; $i <= $questionArrayLen; $i++) :
                               $f_question = ${("f_" . pad($i,2))};
                               if ($f_question == "") : $f_question = "0"; endif;
                               // $tmpSqlQuery = "INSERT INTO phoenix.genericdatacontainer (gdc_obj_type, gdc_obj_id, gdc_gen_fieldname, gdc_content, gdc_context) VALUES ('jb', '" . $jb . "', 'survey', '" . $f_question . "', '1" . pad($i,2) . "')";
                               $tmpSqlQuery = "INSERT INTO phoenix.genericdatacontainer (gdc_obj_type, gdc_obj_id, gdc_gen_fieldname, gdc_content, gdc_context) VALUES ('tr', '" . $trId . "', 'survey', '" . $f_question . "', '1" . pad($i,2) . "')";
                               $result = $db_conn->query($tmpSqlQuery);
                               if (DB::isError($result)) {$err = "ERR";};
                           endfor;                        

                           if ($err == "") :

                              TA("C");
                              TA("E");

                              $f_annotation = trim($f_annotation);
                              $errMsg = "";
                              if ($f_annotation != "") :

                                 $mailResult = false;  // Init

                                 $mailSenderAddress = getFieldValueFromClause("phoenix.parameter","par_value","par_key = 'MAIL_SURVEY_SENDER_ADDRESS' AND hq_id = '" . $hqId . "'", $db_conn);
                                 if ($mailSenderAddress == "") : $mailSenderAddress = getFieldValueFromClause("phoenix.parameter","par_value","par_key = 'MAIL_SURVEY_SENDER_ADDRESS' AND hq_id = '0'", $db_conn); endif;
                                 if ($mailSenderAddress == "") : $mailSenderAddress = getFieldValueFromClause("phoenix.parameter","par_value","par_key = 'MAIL_SENDER_ADDRESS' AND hq_id = '" . $hqId . "'", $db_conn); endif;
                                 if ($mailSenderAddress == "") : $mailSenderAddress = getFieldValueFromClause("phoenix.parameter","par_value","par_key = 'MAIL_SENDER_ADDRESS' AND hq_id = '0'", $db_conn); endif;

                                 if ($mailSenderAddress != "") : 

                                    $mailSubject = getLngt("Bewertung durch den Kunden") . " " . $csEid;
                                    $mailText = $f_annotation;

                                    $mailObj = new htmlMimeMail();
                                    $mailObj->setFrom($mailSenderAddress);
                                    if ($mailCcAddresses != "") :
                                       $mailObj->setCc($mailCcAddresses);
                                    endif;
                                    if ($mailBccAddresses != "") :
                                       $mailObj->setBcc($mailBccAddresses);
                                    endif;
                                    $mailObj->setSubject($mailSubject);

                                    // Mail content
                                    // $mailObj->setHtml($htmlOut, null, "./");
                                    $mailObj->setText($mailText);

                                    $mailToAddresses = getFieldValueFromClause("phoenix.parameter","par_value","par_key = 'MAIL_SURVEY_ADDRESS_TO' AND hq_id = '" . $hqId . "'", $db_conn);
                                    if ($mailToAddresses == "") : $mailToAddresses = getFieldValueFromClause("phoenix.parameter","par_value","par_key = 'MAIL_SURVEY_ADDRESS_TO' AND hq_id = '0'", $db_conn); endif;
                                    if ($mailToAddresses == "") : $mailToAddresses = $mailSenderAddress; endif;

                                    if ($mailToAddresses != "" && checkEmailFormat($mailToAddresses)) :
                                       $mailResult = $mailObj->send(array($mailToAddresses), 'smtp');
                                       
                                       if (!$mailResult) :
                                          $errMsg = "Fehler bei Versendung!";
                                       endif;
                                    else :
                                       $errMsg = "Die Syntax der Mailadresse ist nicht korrekt!";
                                    endif;

                                    $mailObj = NULL;
                                 else :
                                    $errMsg = "Keine Senderadresse eingetragen!";
                                 endif;

                                 // Error handling
                                 if (!$mailResult) :
                                    // Send internal mail with error message
                                    $errMsg = "BEWERTUNG :: [CS_ID:" . $objId . "][CS_EID:" . $csEid . "] :: " . $errMsg;
                                    sendInternalMail($errMsg);
                                 endif;
                              endif;

                              // Write logdata into log database
                              // writeToLogRemoteDB("96",$hqId,"","","","",$objId,"STATUS=OK|IP=" . $currentClientIP . "|MO_ID=" . $moId);
   
                              $out = "<h3>" . getLngt("Vielen Dank für die Beantwortung der Fragen!") . "</h3>";
                           else :
                              TA("R");
                              TA("E");
   
                              // writeToLogRemoteDB("96",$hqId,"","","","",$objId,"STATUS=UPDATE_ERR|IP=" . $currentClientIP . "|MO_ID=" . $moId);
                           endif;
                        else :
                           // Customer not found
                           // writeToLogRemoteDB("96","","","","","","","STATUS=CS_NOT_FOUND|IP=" . $currentClientIP . "|MO_ID=" . $moId);
                        endif;
   
                  elseif ($objType == "cr") :
   /*             
                        $cmpId = $db_conn->getOne("SELECT cr.cmp_id FROM phoenix.courier AS cr WHERE cr.cr_id = '" . $objId . "' ");
                  
                        if ($cmpId != "" && $cmpId > "0") :
                  
                           $hqId = $db_conn->getOne("SELECT cr.hq_id FROM phoenix.courier AS cr WHERE cr.cr_id = '" . $objId . "' ");
                  
                           // Change state of the newsletter abonnement
                           $result = $db_conn->query("UPDATE phoenix.company SET cmp_newsletter = '0' WHERE cmp_id='" . $cmpId . "'");
                           $err = "";
                           if (DB::isError($result)) : $err = "ERR"; endif;
                  
                           if ($err == "") :
                  
                              // Write logdata into log database
                              writeToLogRemoteDB("96",$hqId,"","","","",$objId,"STATUS=OK|IP=" . $currentClientIP . "|MO_ID=" . $moId);
                  
                              $out = "<h2>" . getLngt("Herzlicher Dank für die Beantwortung der Fragen!") . "</h2>";
                           else :
                              // Update failed
                              writeToLogRemoteDB("96",$hqId,"","","","",$objId,"STATUS=UPDATE_ERR|IP=" . $currentClientIP . "|MO_ID=" . $moId);
                           endif;
                        else :
                           // Customer not found
                           writeToLogRemoteDB("96","","","","","","","STATUS=CS_NOT_FOUND|IP=" . $currentClientIP . "|MO_ID=" . $moId);
                        endif;
   */             
                  elseif ($objType == "emp") :
                        // ...
                  else :
                        // Write logdata into log database
                        writeToLogRemoteDB("96",$hqId,"","","","",$objId,"STATUS=OBJTYPE_NOT_FOUND|IP=" . $currentClientIP . "|MO_ID=" . $moId);
                  
                        // OBJECTTYPE nicht gesetzt oder nicht bekannt
                        $out = $generalOutErrMsg;
                  endif;
   
               else :
   
                  $maxlength = "150";
                  $size = "100";
                  $cols = "50";
                  $rows = "5";
   
                  $out = "<table  align=\"left\">";
                  $out .= "<tr><td class=\"f12bp1\">" . "Unsere Qualität auf dem Prüfstand." . "<br><br>" . "</td></tr>";
                  $out .= "<tr><td class=\"f10bp1\">" . "Ihre Meinung ist uns wichtig!" . "<br><br>" . "</td></tr>";
                  $out .= "<tr><td class=\"f8bp1\">" . "Bitte nehmen Sie sich kurz Zeit für uns. Unser Anspruch ist es, Ihnen ein hohes Maß an Qualität zu bieten. Mit Ihrem Feedback helfen Sie uns, diesem Anspruch gerecht zu werden." . "<br><br>" . "</td></tr>";
   
                  for ($i = 1; $i <= $questionArrayLen; $i++) :
                      $out .= "<tr><td class=\"f8np1\">" . "[" . $i . ".] " . $questionArray[($i - 1)] . "</td></tr>";
                      // $out .= "<tr><td class=\"f8np1\">" . "<input class=\"f8np1\" type=\"text\" name=\"f_" . pad($i,2) . "\" value=\"\" maxlength=\"" . $maxlength . "\" size=\"" . $size . "\">" . "<br><br>" . "</td></tr>";
                      $out .= "<tr><td class=\"f8np1\">";
                      $out .= "<input class=\"smaller\" type=\"radio\" name=\"f_" . pad($i,2) . "\" value=\"3\" " . ($f_showDateAndTime == "0" ? "checked" : "") . ">" . "Ja" . "</br>";
                      $out .= "<input class=\"smaller\" type=\"radio\" name=\"f_" . pad($i,2) . "\" value=\"2\" " . ($f_showDateAndTime == "1" ? "checked" : "") . ">" . "Neutral" . "</br>";
                      $out .= "<input class=\"smaller\" type=\"radio\" name=\"f_" . pad($i,2) . "\" value=\"1\" " . ($f_showDateAndTime == "2" ? "checked" : "") . ">" . "Nein" . "</br>";
                      $out .= "</br>" . "</td></tr>";
                  endfor;

                  $out .= "<tr><td class=\"f8np1\">" . "</br>" . "Ihre Anmerkungen:" . "</td></tr>";
                  $out .= "<tr><td class=\"f8np1\">" . "<textarea class=\"f8np1\" name=\"f_annotation\" cols=\"" . $cols . "\" rows=\"" . $rows . "\"></textarea>" . "<br><br>" . "</td></tr>";
                  
                  $out .= "<tr><td class=\"f12bp1\">" . "<input class=\"f8np1\" type=\"button\" value=\"Abschicken\" onClick=\"finishPage('send')\">" . "<br><br>" . "</td></tr>";
                  $out .= "</table>";
               endif;
            else :
                  // Survey had been done in the past
                  $out = "<h3>" . getLngt("Die Bewertung zu diesem Auftrag wurde schon erfasst.") . "</h3>";
                  $out .= "<h3>" . getLngt("Dafür noch einmal vielen Dank!") . "</h3>";
            endif;
         else :
            // database not specified in metaobject row
            writeToLogRemoteDB("96","","","","","","","STATUS=DB_NOT_SPECIFIED|IP=" . $currentClientIP . "|MO_ID=" . $moId);
         endif;
      else :
         // HASH nicht gefunden um Zuordnung herzustellen
         $out = $generalOutErrMsg;
      endif;
   endif;

else :
   // Write logdata into log database
   writeToLogRemoteDB("96","","","","","","","STATUS=EMPTY_OPCODE|IP=" . $currentClientIP . "|MO_ID=" . $moId);

   $out = $generalOutErrMsg;
endif;
?>

<html>

<head>
<title><?php echo $pageTitel ?></title>

<link rel="stylesheet" type="text/css" href="../css/phoenix.css">

<style type="text/css">
.mcTable { border:0px; width:650px; background:#CDD9FD; }
.mcTable2 { border:0px; width:630px; background:#CDD9FD; }
.mcTd { vertical-align:top; padding:5px; font-size:10pt; font-family:Helvetica,Arial; 
        font-style:normal; font-weight:normal; background:#CDD9FD; color:#000000; }
.spacer05 { height:5px; background:#CDD9FD;}
.spacer15 { height:15px; background:#CDD9FD;}
</style>

<script type="text/javascript">
<!--
function finishPage(f_act) {
	document.forms[0].f_act.value = f_act;
	document.forms[0].submit();
}
-->
</script>

</head>


<body class="menu_bgcol">

<form action="../service/survey.php" method="post">

  <input type="hidden" name="f_act" value="">
  <input type="hidden" name="op" value="<?php echo $op ?>">
  <input type="hidden" name="jb" value="<?php echo $jb ?>">

  <center>
  <table class="mcTable">
    <tr>
    	<td style="width:650px;" align="center">
    		<img src="../images/external/<?php echo strtolower($imgIdentifyer) ?>_header.jpg" border="0" height="157" width="640">
      </td>
    </tr>
  </table>
  <table class="mcTable"><tr><td class="spacer15"></td></tr></table>
  
  <table class="mcTable">
    <tr>
      <td class="mcTd" align="center">
      	<?php echo $out ?>
      </td>
    </tr>
  </table>
  <table class="mcTable"><tr><td class="spacer15"></td></tr></table>
  
  <table class="mcTable">
    <tr>
    	<td style="width:650px;" align="center">
    		<img src="../images/external/<?php echo strtolower($imgIdentifyer) ?>_footer.jpg" border="0" height="107" width="640">
      </td>
    </tr>
  </table>
  </center>

</form>

</body>

</html>
