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

include_once ("../include/mcglobal.inc.php");
include_once ("../include/auth.inc.php");
// include_once ("../include/html.inc.php");


$httpVarsArray = array("f_act", "customerId", "orderClause", "statusMessage", 
                       "f_relationStatus", "f_del_courier_id", "g_cr_id", "f_cscr_description_new", "deactivateMenu");

getSecHttpVars("1", $httpVarsArray);

getLanguage(__FILE__);

$deactivateMenuStatic = "1";
$pageTitel = getLngt("BEZIEHUNG KUNDE-TRANSPORTEUR");
include_once ("../admin/menu.php");
include_once ("../include/html.inc.php");
getCurrentScript(__FILE__);

// Check for authentication access and granted rights
$usrAccessArray["hq"] = "1";
authCheckForAccess($hq_id, $usr_id, $emp_id, "1", $customerId, $cscIdRoot, $cscIdActual);
authCheckEmployeeRights($emp_id, "1", "1");

// Initializations
mcIsSet($f_relationStatus, "0");
mcIsSet($f_actText);
mcTrim($f_cscr_description_new);                                   // Description related to an association between customer and courier


// Only for output
$htmlClass01 = "class=\"smaller\"";                // input,select
$html_td_01  = "valign=\"top\" align=\"left\"";    // input
$html_td_02  = "valign=\"top\" align=\"right\"";   // input



   // **************************************
   // * Operations for the couriercustomer *   
   // **************************************

   // Insert new couriercustomer
   if ($f_act == "newCustomerCourier" && $customerId != "" && $g_cr_id != "" && $g_cr_id != "0") :

      if (!existsEntry("customercourier",array("cs_id",$customerId,"cr_id",$g_cr_id))) :
                                                         
            TA("B");

            // Get max sort value of favoured couriers and increment
            $maxSortValue = 0;
            if ($f_relationStatus == "1") :
               $maxSortValue = getMaxOfField("customercourier", "cscr_sort", "cs_id = '" . $customerId . "' AND cscr_relation = '1' ");
               if ($maxSortValue != "" && is_numeric($maxSortValue)) :
                  $maxSortValue++;
               else :
                  $maxSortValue = 1;
               endif;
            endif;

            // Insert customercourier
            insertStmt("customercourier", array("cs_id",$customerId,"cr_id",$g_cr_id,"cscr_relation",$f_relationStatus,"cscr_sort",$maxSortValue,"cscr_description",$f_cscr_description_new));

            writeToLogDB("181",$hq_id,"0",$usr_id,$g_cr_id,"",$customerId,"CR_ID=" . $g_cr_id . "|CS_ID=" . $customerId . "|CSCR_RELATION=" . $f_relationStatus,"0","0",$emp_id);

            TA("C");
            TA("E");        
      else :
         $statusMessage = getLngt("Es existiert schon eine Beziehung zwischen dem Kurier und diesem Kunden!");
      endif;
   endif;            

   // Remove couriercustomer
   if ($f_act == "removeCustomerCourier" && $customerId != "") :

      TA("B");       

      // Entries to be deleted?
      $fieldsLength = count($f_del_courier_id);

      if ($fieldsLength > 0 && $f_del_courier_id[0] != "") :
      
         // Remove all associations
         for ($i = 0; $i < $fieldsLength; $i++) :
             deleteStmt("customercourier","cs_id = " . $customerId . " AND cr_id = " . $f_del_courier_id[$i]);

             writeToLogDB("182",$hq_id,"0",$usr_id,$f_del_courier_id[$i],"",$customerId,"CR_ID=" . $f_del_courier_id[$i] . "|CS_ID=" . $customerId,"0","0",$emp_id);
         endfor;
         
         // Resort the sort value of the favoured couriers of the customer
         $sqlquery = "SELECT cs_id, cr_id FROM customercourier WHERE cs_id = " . $customerId . " AND cscr_relation = '1' ORDER BY cscr_sort";
         $result = $db->query($sqlquery);
         if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
         $sortCounter = 1;
         while ($row = $result->fetch_assoc()):
               $csId          = $row["cs_id"];
               $crId          = $row["cr_id"];                 
               updateStmt("customercourier", "cs_id", $csId, array("cscr_sort", $sortCounter),"cr_id = '" . $crId . "' AND cscr_relation = '1'");
               $sortCounter++;
         endwhile;
         $result->free();
      else :
         $statusMessage = getLngt("Bitte markieren Sie zu löschende Beziehungen durch anklicken der jeweiligen Checkbox hinter dem Eintrag!");
      endif;
  
       TA("C");
       TA("E");
   endif;
   
   
   // ****************************************************************************
   // * Get the courier-customer relations of a specified customer for selection *
   // ****************************************************************************

   $count = 0;
   if ($customerId != "") :

      $sqlquery = "SELECT usr.usr_firstname, usr.usr_name, usr.usr_phone, usr.usr_email, cr.cr_id, cr.cr_eid, cr.cr_sid, cscr.cscr_relation, cscr.cscr_description"
                      . " FROM customercourier AS cscr, courier AS cr, customer AS cs, "
                      . "      user AS usr"
                      . " WHERE cscr.cs_id = $customerId AND"
                      . "       cr.cr_id = cscr.cr_id    AND"
                      . "       cr.hq_id = $hq_id        AND"
                      . "       cs.cs_id = cscr.cs_id    AND"
                      . "       cs.hq_id = $hq_id        AND"
                      . "       usr.usr_id = cr.usr_id"
                      . " ORDER BY cr.cr_sid";

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

      while ($row = $result->fetch_assoc()): 
               $f_usr_firstname[$count]    = $row["usr_firstname"];
               $f_usr_name[$count]         = $row["usr_name"];
               $f_usr_phone[$count]        = $row["usr_phone"];
               $f_usr_email[$count]        = $row["usr_email"];
               $f_cr_id[$count]            = $row["cr_id"];
               $f_cr_eid[$count]           = $row["cr_eid"];
               $f_cr_sid[$count]           = $row["cr_sid"];
               $f_cscr_relation[$count]    = $row["cscr_relation"];
               $f_cscr_description[$count] = $row["cscr_description"];
               $count++;
      endwhile;
      $result->free();      
   endif;


   // Only for output
   $tmp_cmp_id = getFieldValueFromId("customer", "cs_id", "$customerId", "cmp_id");
   $tmpFields = getFieldsValueFromId("company","cmp_id",$tmp_cmp_id,array("cmp_comp","cmp_comp2"));
   $pageHeadline = getLngt("Transporteursbeziehungen von:") . " " . $tmpFields[0] . " " . $tmpFields[1];

   // Output of the existing relations of the current selected area
   $courierOutput = "";
   for ($j = 0; $j < $count; $j++) :
       $courierOutput .= $f_usr_firstname[$j] . " " . $f_usr_name[$j] . "<br>";
       $courierOutput .= getLngt("EID:") . " " . $f_cr_eid[$j] . " / " . getLngt("Akt. SID:") . " " . $f_cr_sid[$j] . "&nbsp;&nbsp;";
       
       $imgName = "circle_red.jpg";
       if ($f_cscr_relation[$j] == "1") : $imgName = "circle_green.jpg"; endif;
       $courierOutput .= "<img src=\"../images/" . $imgName . "\" border=\"0\" height=\"10\" width=\"25\">&nbsp;&nbsp;";
       
       $courierOutput .= "<input type=\"checkbox\" name=\"f_del_courier_id[]\" value=\"" . $f_cr_id[$j] . "\"><br>";
       $courierOutput .= $f_cscr_description[$j];
       $courierOutput .= "<br><br>\n";
   endfor;   
   
   // Button to remove associations between courier and customer(s). Only show if at least one customer is associated to the current area.
   if ($count > 0) :
      $courierOutput .= "<br>\n";
      $courierOutput .= defineButtonType10(getLngt("Markierte&nbsp;Verknüpfungen&nbsp;entfernen"), "action_remove", "finishPage('removeCustomerCourier');", "240");
      $courierOutput .= "<br><br>\n";
   endif;
   
   if ($courierOutput == "") :
      $courierOutput = getLngt("Zur Zeit sind keine Beziehungen eingetragen!");
   endif;
?>

<html>

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

<style type="text/css">
  <?php include_once ("../css/phoenix.css.php"); ?>
  <?php include_once ("../css/navigation.css.php"); ?>
  <?php include_once ("../css/mc.css.php"); ?>
</style>

<?php include_once ("../include/js_framework.inc.php"); ?>

<script src="../include/checkFormTags.js" type="text/javascript"></script>
<script src="../include/searchLists.js" type="text/javascript"></script>

<script type="text/javascript">
<!--
// NAVIGATION
<?php echo $jsMenuOut; ?>

function finishPage(mode) {
  var ok = true;
  if (mode == 'newCustomerCourier') {
     if (document.forms[0].g_cr_id.value != '') {
        document.forms[0].f_act.value = mode;
        document.forms[0].submit();
     } else {
     	alert('<?php echo getLngt("Wählen Sie bitte einen Transporteur aus!") ?>');
     }
  }

  if (mode == 'removeCustomerCourier') {
     if (confirm('<?php echo getLngt("Möchten Sie die bestehende(n) Beziehung(en) wirklich löschen?") ?>')) {
     	document.forms[0].f_act.value = mode;
        document.forms[0].submit();
     }
  }
};

function searchCsCsc() {
  var f_act = 'search';
  
  var widthPopupWin = 950;
  var heightPopupWin = 600;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../admin/cs_csc_list.php?f_act=" + f_act + "&generic=100111111000",
    "","dependent=yes,width=" + widthPopupWin + ",height=" +
    heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin +
    ",scrollbars=yes");
};
-->
</script>

</head>

<body class="menu_bgcol" onLoad="<?php echo $phpCurrentNavigationOnLoad ?>displayStatusMessage();">

<?php echo $phpMenuOut ?>
<?php echo $phpReducedMenuOut ?>
<?php echo $phpPageTitelOut ?>

<div class="mc_page-header">
  <?php echo $pageHeadline ?>
</div>

<div class="maincontent mc_elem" name="maincontent" id="maincontent">

<form action="../admin/customer_courier.php" method="post">
  <input type="hidden" name="f_act" value="">
  <input type="hidden" name="customerId" value="<?php echo ec($customerId) ?>">
  <input type="hidden" name="g_cr_id" value="">
  <?php echo $phpCurrentNavigationInputHidden ?>
  <input type="hidden" name="deactivateMenu" value="<?php echo ec($deactivateMenu) ?>">

  <?php echo htmlDivLineSpacer("10px"); ?>
    
  <div class="f10bp1">
    Transporteure:
  </div>

  <?php echo htmlDivLineSpacer("10px"); ?>

  <div class="f10bp1">
    <?php echo $courierOutput; ?>
  </div>

  <?php echo htmlDivLineSpacer("15px"); ?>

  <?php echo defineButtonType10(getLngt("Transporteur&nbsp;suchen"), "action_search", "searchCourier('2');", "140"); ?>

  <?php echo htmlDivLineSpacer("15px"); ?>

  <div>
    <div <?php echo setStyleHtmlDiv("250px","left"); ?>><?php echo getLngt("Name:") ?></div>
    <div><input type="text" name="g_usr_firstname" value="" size="20" disabled ></div>
  </div>
  <div>
    <div <?php echo setStyleHtmlDiv("250px","left"); ?>><?php echo getLngt("Vorname:") ?></div>
    <div><input type="text" name="g_usr_name" value="" size="20" disabled ></div>
  </div>
  <div>
    <div <?php echo setStyleHtmlDiv("250px","left"); ?>><?php echo getLngt("EID:") ?></div>
    <div><input type="text" name="g_cr_eid" value="" size="10" disabled ></div>
  </div>
  <div>
    <div <?php echo setStyleHtmlDiv("250px","left"); ?>><?php echo getLngt("SID:") ?></div>
    <div><input type="text" name="g_cr_sid" value="" size="10" disabled ></div>
  </div>
  <div>
    <div <?php echo setStyleHtmlDiv("250px","left"); ?>><?php echo getLngt("Telefon:") ?></div>
    <div><input type="text" name="g_usr_phone" value="" size="20" disabled ></div>
  </div>
  <div>
    <div <?php echo setStyleHtmlDiv("250px","left"); ?>><?php echo getLngt("E-Mail:") ?></div>
    <div><input type="text" name="g_usr_email" value="" size="20" disabled ></div>
  </div>
  <div>
    <div <?php echo setStyleHtmlDiv("250px","left"); ?>><?php echo getLngt("Beschreibung:") ?></div>
    <div><input type="text" name="f_cscr_description_new" value="" size="50" maxlength="255"></div>
  </div>

  <?php echo htmlDivLineSpacer("15px"); ?>

  <div>
    <div>
      <input type="radio" <?php echo $htmlClass01 ?> name="f_relationStatus" value="0" checked> <?php echo getLngt("Sperren") ?><br>
      <input type="radio" <?php echo $htmlClass01 ?> name="f_relationStatus" value="1"> <?php echo getLngt("Besonders erwünscht") ?><br>
      <br>
    </div>
    <?php echo defineButtonType10(getLngt("Transporteur&nbsp;dem&nbsp;Kunden&nbsp;zuordnen"), "action_assoc", "document.forms[0].f_act.value='" . ec($f_actText) . "';finishPage('newCustomerCourier');", "240"); ?>
    <?php echo htmlDivLineSpacer("50px"); ?>
    <?php echo defineButtonType10(getLngt("Schließen"), "action_close", "window.close();", "80", "left", "3"); ?>
  </div>

</form>
</div>
</body>

</html>