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

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


// 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");

// Check for right to access amount fields
$crvhRgtRule01 = false;
if (authCheckEmployeeRights($emp_id, "39")) : $crvhRgtRule01 = true; endif;


$httpVarsArray = array("f_act", "courierId", "orderClause", "statusMessage", "f_cr_id", 
                       "f_relationStatus", "f_del_customer_id", "g_cs_id", "f_cscr_description_new", "deactivateMenu");

if ($crvhRgtRule01) :
   $httpVisualVarsRgtRule01 = array("f_cscr_prov", );

   $httpVarsArray = array_merge($httpVarsArray, $httpVisualVarsRgtRule01);
endif;

getSecHttpVars("1", $httpVarsArray);


getLanguage(__FILE__);

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

// Initializations
if ($f_relationStatus == "") : $f_relationStatus = "0"; endif;     // 0 = bad relation between cs and cr (blocked), 1 = good relation (favoured)
$f_cscr_description_new = trim($f_cscr_description_new);           // Description related to an association between customer and courier
if ($f_cscr_prov == "") : $f_cscr_prov = "0"; endif;               // Commission rate for good relations (favoured couriers only)

$currentTime = getDateTime("0");

// 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 == "newCourierCustomer" && $courierId != "" && $g_cs_id != "") :

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

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

            // Insert couriervehicle
            $defaultFields = array("cs_id",$g_cs_id,"cr_id",$courierId,"cscr_relation",$f_relationStatus,"cscr_sort",$maxSortValue,"cscr_description",$f_cscr_description_new);

            if ($crvhRgtRule01) :
               $f_cscr_prov = str_replace (",", ".", $f_cscr_prov);
               $crvhRgtRule01Fields = array("cscr_prov", $f_cscr_prov);
               $defaultFields = array_merge($defaultFields, $crvhRgtRule01Fields);
            endif;
            
            insertStmt("customercourier", $defaultFields);
            
            writeToLogDB("181",$hq_id,"0",$usr_id,$courierId,"",$g_cs_id,"CR_ID=" . $courierId . "|CS_ID=" . $g_cs_id . "|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 == "removeCourierCustomer" && $courierId != "") :

      TA("B");       

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

      if ($fieldsLength > 0 && $f_del_customer_id[0] != "") :
      
         // Remove all associations according to the zipcode nested in array $f_del_zipcode_id
         for ($i = 0; $i < $fieldsLength; $i++) :

             deleteStmt("customercourier","cr_id = " . $courierId . " AND cs_id = " . $f_del_customer_id[$i]);

             writeToLogDB("182",$hq_id,"0",$usr_id,$courierId,"",$f_del_customer_id[$i],"CR_ID=" . $courierId . "|CS_ID=" . $f_del_customer_id[$i],"0","0",$emp_id);

             // Resort the sort value of the favoured couriers of the customer
             $sqlquery = "SELECT cs_id, cr_id FROM customercourier WHERE cs_id = " . $f_del_customer_id[$i] . " 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();             
         endfor;
      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 courier for selection *
   // ***************************************************************************
   
   $f_cmp_comp = array(); $f_cmp_comp2 = array(); $f_cs_id = array(); $f_cs_eid = array(); $f_cscr_relation = array(); $f_cscr_prov = array(); $f_cscr_description = array();
   $count = 0;
   if ($courierId != "") :
            
      $sqlquery = "SELECT cmp.cmp_comp, cmp.cmp_comp2, cs.cs_id, cs.cs_eid, cscr.cscr_relation, cscr.cscr_prov, cscr.cscr_description"
                      . " FROM customercourier AS cscr, courier AS cr, customer AS cs, "
                      . "      company AS cmp"
                      . " WHERE cscr.cr_id = $courierId 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"
                      . "       cmp.cmp_id = cs.cmp_id";
      $result = $db->query($sqlquery);
      if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
      
      while ($row = $result->fetch_assoc()): 
               $f_cmp_comp[$count]         = $row["cmp_comp"];
               $f_cmp_comp2[$count]        = $row["cmp_comp2"];
               $f_cs_id[$count]            = $row["cs_id"];
               $f_cs_eid[$count]           = $row["cs_eid"];
               $f_cscr_relation[$count]    = $row["cscr_relation"];
               $f_cscr_prov[$count]        = $row["cscr_prov"];
               $f_cscr_description[$count] = $row["cscr_description"];
               $count++;
      endwhile;
      $result->free();      
   endif;


   // Only for output
   // $tmp_usr_id = getFieldValueFromId("courier", "cr_id", $courierId, "usr_id");
   $tmpFields2 = getFieldsValueFromId("courier", "cr_id", $courierId, array("usr_id","cr_eid","cr_sid"));
   $tmp_usr_id = $tmpFields2[0];
   $tmp_cr_eid = $tmpFields2[1];
   $tmp_cr_sid = $tmpFields2[2];   
   $tmpFields = getFieldsValueFromId("user","usr_id",$tmp_usr_id,array("usr_name","usr_firstname"));
   $tmp_usr_name = $tmpFields[0];
   $tmp_usr_firstname = $tmpFields[1];

   $title = getLngt("Kundenbeziehungen von:") . "<br>" . $tmp_usr_firstname . " " . $tmp_usr_name . "&nbsp;&nbsp;";
   if ($tmp_cr_eid != "" || $tmp_cr_sid != "") : $title .= "(" . getLngt("EID:") . " " . $tmp_cr_eid . " / " . getLngt("Akt. SID:") . " " . $tmp_cr_sid . ")"; endif;

   // Output of the existing relations of the current selected area
   $customerOutput = "";
   for ($j = 0; $j < $count; $j++) :
       $customerOutput .= $f_cmp_comp[$j] . "<br>";
       if ($f_cmp_comp2[$j] != "") : $customerOutput .= $f_cmp_comp2[$j] . "<br>"; endif;
       $customerOutput .= $f_cs_eid[$j] . "&nbsp;&nbsp;";
       $imgName = "circle_red.jpg";
       if ($f_cscr_relation[$j] == "1") : $imgName = "circle_green.jpg"; endif;
       $customerOutput .= "<img src=\"../images/" . $imgName . "\" border=\"0\" height=\"10\" width=\"25\">&nbsp;&nbsp;";

       $customerOutput .= "<input type=\"checkbox\" name=\"f_del_customer_id[]\" value=\"" . $f_cs_id[$j] . "\">&nbsp;&nbsp;&nbsp;&nbsp;";

       if ($f_cscr_relation[$j] == "1") :
          $f_cscr_prov[$j] = str_replace (".", ",", $f_cscr_prov[$j]);
          if ($crvhRgtRule01) :
             $customerOutput .= "<input type=\"text\" class=\"f8bp1\" name=\"f_cscr_prov_" . $f_cs_id[$j] . "\" value=\"" . $f_cscr_prov[$j] . "\" onChange=\"setProvWasChanged('" . $f_cs_id[$j] . "', '" . $f_cscr_prov[$j] . "', $(this).val());\" size=\"6\" maxlength=\"6\"> [%]";
          else :
             $customerOutput .= "[" . $f_cscr_prov[$j] . " %]";
          endif;
       endif;       
       $customerOutput .= "</br>";
       $customerOutput .= $f_cscr_description[$j] . "</br>";       
       
       $customerOutput .= "</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) :
      $customerOutput .= "<br>\n";
      $customerOutput .= defineButtonType10(getLngt("Markierte&nbsp;Verknüpfungen&nbsp;entfernen"), "action_remove", "finishPage('removeCourierCustomer');", "240");
      $customerOutput .= "<br><br>\n";      
   endif;
   
   if ($customerOutput == "") :
      $customerOutput = getLngt("Zur Zeit sind keine Beziehungen eingetragen!");
   endif;
?>

<html>

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

<link rel="stylesheet" type="text/css" href="../css/phoenix.css">
<style type="text/css">
  <?php include_once ("../css/navigation.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 == 'newCourierCustomer') {
     if (document.forms[0].g_cs_id.value != '') {
        document.forms[0].f_act.value = mode;
        document.forms[0].submit();
     } else {
     	alert('<?php echo getLngt("Wählen Sie bitte einen Kunden aus!") ?>');
     }
  }

  if (mode == 'removeCourierCustomer') {
     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");
};

// Set commissionv alue to relation between courier and customer
function setProvWasChanged (csId, provValueOld, provValueNew) {
	// var su = '#' + 'f_su_chkbx_' + serialno;
	var crId = '<?php echo $courierId ?>';
	var crEid = '<?php echo getFieldValueFromId("courier", "cr_id", $courierId, "cr_eid") ?>';
	provValueOld = provValueOld.replace(',', '.');
	provValueNew = provValueNew.replace(',', '.');
// alert(crId + ' ' + csId + ' ' + provValueOld + ' ' + provValueNew);
  if (csId != '' && crId != '' && provValueNew != '' && provValueOld != provValueNew) {
     if (checkIsNaN(provValueNew, '<?php echo getLngt("Bitte geben Sie eine Zahl ein!") ?>')) {
     	  if (provValueNew != provValueOld) {
     	  	if (confirm('<?php echo getLngt("Möchten Sie den neuen Wert speichern?!") ?>')) {
     	  		 // "customercourier"
             ajaxRequestGet('../include/ajaxReqLib.php', 'mode=100&db_table=customercourier&db_id_field=cr_id&search_value=' + crId + '&db_op_field=cscr_prov&new_content=' + provValueNew + '&clause=cs_id=' + csId + ' AND cscr_relation=1');
             // "servicepricehistory"
             ajaxRequestGet('../include/ajaxReqLib.php', 'mode=200&db_table=servicepricehistory&db_op_field=srvprch_obj_type---cr---srvprch_obj_id---' + crId + '---srvprch_obj_eid---' + crEid + '---srvprch_fieldname---cscr_prov---srvprch_context---' + csId + '---srvprch_price---' + provValueNew + '---srvprch_validfrom---<?php echo $currentTime ?>');
             // "log"
             ajaxRequestGet('../include/ajaxReqLib.php', 'mode=300&db_id_field=180&db_op_field=cr&search_value=' + crId + '&id_01=CS_ID&value_01=' + csId + '&id_02=CSCR_PROV_OLD&value_02=' + provValueOld + '&id_03=CSCR_PROV_NEW&value_03=' + provValueNew + '&id_04=VALID_FROM&value_04=<?php echo $currentTime ?>');
          }
        }
     }
  }
}
-->
</script>

</head>

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

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

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

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

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

  <div class="f12bp1_blue">
    <?php echo $title ?>
  </div>

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

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

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

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

  <?php echo defineButtonType10(getLngt("Kunde&nbsp;suchen"), "action_search", "searchCsCsc();", "100"); ?>

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

  <div>
    <div <?php echo setStyleHtmlDiv("100px","left"); ?>><?php echo getLngt("Firma:") ?></div>
    <div>
      <input type="text" name="g_cscad_comp" value="" size="36" disabled >
    </div>
  </div>
  <?php echo htmlDivLineSpacer("5px"); ?>
  <div>
    <div <?php echo setStyleHtmlDiv("100px","left"); ?>>&nbsp;</div>
    <div>
      <input type="text" name="g_cscad_comp2" value="" size="36" disabled >
    </div>
  </div>
  <?php echo htmlDivLineSpacer("10px"); ?>
  <div>
    <div <?php echo setStyleHtmlDiv("100px","left"); ?>><?php echo getLngt("Adresse:") ?></div>
    <div>
      <input type="text" name="g_ad_street" value="" size="30" disabled >&nbsp;
      <input type="text" name="g_cscad_hsno" value="" size="5" disabled >
    </div>
  </div>
  <?php echo htmlDivLineSpacer("5px"); ?>
  <div>
    <div <?php echo setStyleHtmlDiv("100px","left"); ?>>&nbsp;</div>
    <div>
      <input type="text" name="g_ad_zipcode" value="" size="5" disabled >&nbsp;
      <input type="text" name="g_ad_city" value="" size="30" disabled >
    </div>
  </div>
  <?php echo htmlDivLineSpacer("10px"); ?>
  <div>
    <div <?php echo setStyleHtmlDiv("100px","left"); ?>><?php echo getLngt("Bemerkung:") ?></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("Kunde&nbsp;dem&nbsp;Transporteur&nbsp;zuordnen"), "action_assoc", "finishPage('newCourierCustomer');", "230"); ?>
    <?php echo htmlDivLineSpacer("50px"); ?>
    <?php echo defineButtonType10(getLngt("Schließen"), "action_close", "window.close();", "80", "left", "3"); ?>
  </div>

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

</html>
