<?php
/*=======================================================================
 *
 * ati_bank_announcement_scan.php
 *
 =======================================================================*/


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

getSecHttpVars("1",array("f_act", "customerId", "cscIdRoot", "cscIdActual", "objecttypemode", "correctScannedCodes", "errLevel", "trackingIDsNotFound",
                         "f_article_type", "f_csc_selected", "numOfObjectsToBeBooked", "statusMessage", "deactivateMenu"));

// Select user-type for mode of security check 
$userType = getFieldValueFromId("user","usr_id",$usr_id,"usr_type");
$userTypeName = getUserTypeName($userType);

// Check for authentication access and granted rights
$usrAccessArray["cs"] = "1";
authCheckForAccess($hq_id, $usr_id, $emp_id, "1", $customerId, $cscIdRoot, $cscIdActual);
if (!(authCheckEmployeeRights($emp_id, "0") || authCheckEmployeeRights($emp_id, "4"))) : gotoReferer("1"); endif;

if ($selYear == "") : $selYear = date("Y"); endif;
if ($selMonth == "") : $selMonth = date("m"); endif;
if ($selDay == "") : $selDay = date("d"); endif;

include_once ("../groupware/calendar.php");

$deactivateMenuStatic = "1";

getLanguage(__FILE__);

$pageTitel = getLngt("Objekte ausbuchen");
include_once ("../admin/menu.php");
include_once ("../include/html.inc.php");

getCurrentScript(__FILE__);

// Init
$debug = false;
$execute = true;
if ($objecttypemode == "") : $objecttypemode = "ati_announcement_1"; endif;
if (!isset($correctScannedCodes)) : $correctScannedCodes = ""; endif;
$correctScannedCodesArr = array();
if ($correctScannedCodes != "") : 
   $correctScannedCodesArr = explode(",", $correctScannedCodes);
endif;
$correctScannedCodesArrLen = count($correctScannedCodesArr);
$cscPreIdOfSelected = "";
if ($f_csc_selected != "" && is_numeric($f_csc_selected)) :
   $cscPreIdOfSelected = getFieldValueFromId("costcenter","csc_id",$f_csc_selected,"csc_pre_id");  // Selected costcenter has to have a "csc_pre_id" (!!!!)
endif;
$currCscName = "Keine " . wrapPhrase("Kostenstelle", $objecttypemode) . " ausgewählt!";

if ($debug) :
   echo "errLevel = " . $errLevel . "<br>";
   echo "cscIdActual = " . $cscIdActual . "<br>";
   echo "f_article_type = " . $f_article_type . "<br>";
   echo "f_csc_selected = " . $f_csc_selected . "<br>";
   echo "cscPreIdOfSelected = " . $cscPreIdOfSelected . "<br>";
   echo "correctScannedCodesArrLen = " . $correctScannedCodesArrLen . "<br>";
   echo "selYear = " . $selYear . "<br>";
   echo "selMonth = " . $selMonth . "<br>";
   echo "selDay = " . $selDay . "<br>";
   echo "execute = " . $execute . "<br>";
endif;


// Get objects to be booked
function getObjectsToBeBooked ($cscId, $atId) {
	global $db, $PHP_SELF;
	$objectsToBeBooked = array();
  if ($cscId != "" && is_numeric($cscId) && $atId != "" && is_numeric($atId)) :
     // Get all fixed objects (e.g. safebags) to be booked to bank by costcenter employee in frontend
     $sqlquery = "SELECT atih.atih_serialno, atih.atih_createtime"
               . "  FROM phoenix_log.articleitemhistory AS atih"
               . "  WHERE atih.csc_id = '" . $cscId . "' AND"
               . "        atih.at_id = '" . $atId . "' AND"
               . "        atih.atih_data_28 = '1'"
               . "  ORDER BY atih.atih_serialno";
     // echo $sqlquery;
     $result = $db->query($sqlquery);
     if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
     while ($row = $result->fetch_assoc()):
           $objectsToBeBooked[] = $row["atih_serialno"];
     endwhile;
     $result->free();
  endif;
  return $objectsToBeBooked;
}


// Check days having access regarding special costcenter (!!!!)
$atihDailyBookingPermanentlyEnabled = false;
$parDailyBookingPermanentlyEnabled =  getParameterValue("0", "ATIH_DAILY_BOOKING_PERMANENTLY_ENABLED", $hq_id);
if ($parDailyBookingPermanentlyEnabled == "") : $parDailyBookingPermanentlyEnabled = getParameterValue("0", "ATIH_DAILY_BOOKING_PERMANENTLY_ENABLED", "0"); endif;
if ($parDailyBookingPermanentlyEnabled == "1") :
   $atihDailyBookingPermanentlyEnabled = true;
endif;
$f_selUsrId = "0"; $f_ap_cat_search_1 = ""; $f_ap_cat_search_2 = ""; $f_ap_cat_search_3 = ""; $f_ap_cat_search_4 = ""; $f_ap_visibility_search = array(); $f_hq_id = array($hq_id);
$bookingDaysArr = getAppointmentsFromDB($selYear, $selMonth, $selDay, $selYear, $selMonth, $selDay, "", $f_csc_selected, "1");
$bookingDaysArrLen = count($bookingDaysArr);  // Has to be at least >= 1 regarding the ap_type = "1". Otherwise access will not be granted! (!!!!)

if ($atihDailyBookingPermanentlyEnabled || $bookingDaysArrLen > 0) :

   if ($execute && $f_csc_selected != "" && is_numeric($f_csc_selected) && $cscPreIdOfSelected != "" && is_numeric($cscPreIdOfSelected) && $f_article_type != "" && is_numeric($f_article_type)) :
   
      // Book objects
      if ($f_act == "book") :
   
         $objectsToBeBooked = getObjectsToBeBooked($f_csc_selected, $f_article_type);
         $objectsToBeBookedLen = count($objectsToBeBooked);
   
         if ($debug) :
            echo "objectsToBeBookedLen = " . $objectsToBeBookedLen . "<br>";
            echo "numOfObjectsToBeBooked = " . $numOfObjectsToBeBooked . "<br>";
         endif;
   
         // Get POST parameter for scanned objects
         for ($i = 0; $i < $objectsToBeBookedLen; $i++) :
             list($snr[$objectsToBeBooked[$i]]) = getSecHttpVars("1",array("snr_" . $objectsToBeBooked[$i]));
         endfor;
   
         if ($debug) :
            echo "<br>"; print_r($snr); echo "<br><br>";
         endif;
   
         // Scans without concrete objects in database
         // HERE !!!!!!!!!!!!!!!!!!!!!!!!!!!!
   
         if ($objectsToBeBookedLen > 0 && $correctScannedCodesArrLen > 0 && $numOfObjectsToBeBooked > 0) :
   
            if ($objectsToBeBookedLen == $numOfObjectsToBeBooked) :  //  && $correctScannedCodesArrLen == $numOfObjectsToBeBooked
   
               // First check all codes being scanned are identically to codes to be scanned after submit
               $codesScannedCorrectly = true;
               for ($i = 0; $i < $objectsToBeBookedLen; $i++) :
                   // Check for object being scanned correctly. If NOT then check for $errLevel has to be "1" (!!!!)
                   if (!in_array($objectsToBeBooked[$i],$correctScannedCodesArr)) :
                      $codesScannedCorrectly = false;
                      break;
                   endif;
               endfor;
   
               if ($debug) :
                  echo "<br>"; print_r($objectsToBeBooked); echo "<br><br>"; print_r($correctScannedCodesArr); echo "<br><br>";
               endif;
   
               if (true) :
   
                  TA("B");
   
                  $objectsNotScanned = "";  // For status message output only
                  for ($i = 0; $i < $objectsToBeBookedLen; $i++) :
                      if ($debug) :
                         echo "snr[$objectsToBeBooked[$i]] = " . $snr[$objectsToBeBooked[$i]] . "<br>";
                      endif;
                      if ($snr[$objectsToBeBooked[$i]] == "1") :
                         updateStmt("phoenix_log.articleitemhistory", "atih_serialno", $objectsToBeBooked[$i], array("atih_data_28", "2"),"csc_id = '" . $f_csc_selected . "' AND atih_data_28 = '1'");
                         // Log update
                         // ............
                      else :
                         if ($objectsNotScanned != "") : $objectsNotScanned .= ","; endif;
                         $objectsNotScanned .= $objectsToBeBooked[$i];
                      endif;
                  endfor;
                  if ($objectsNotScanned != "") :
                     $statusMessage = getLngt("Folgende Objekte wurden NICHT ausgebucht, weil ein Scan NICHT erfolgte:") . " [" . $objectsNotScanned . "]";
                  endif;
   
                  TA("C");
                  TA("E");
   
                  // Send mail for failed scan(s)
                  $sendMailText = "";
                  if (!$codesScannedCorrectly || ($errLevel & 1) == 1) :
                     $sendMailText .= "Fehlende Objekte: " . $objectsNotScanned . "    ";
                  endif;
                  if (($errLevel & 2) == 2) :
                     $sendMailText .= "Zusätzliche Objekte: " . $trackingIDsNotFound;
                  endif;
                  if ($sendMailText != "") :
                     sendExternalMail($sendMailText, "HHA.SCAN.EREIGNISSE", "ASSECUTOR-INFO@hochbahn.de", "sys-op@assecutor.de", "", "proj.hha@assecutor.de", "", "", "sendMailBooking.log");
                  endif;
               else :
                  $statusMessage = getLngt("TRANSAKTIONSFEHLER! Die gescannten Objekte scheinen mit den abzuschließenden Objekten NICHT übereinzustimmen! Bitte leider nochmal den Scan-Prozess wiederholen!");
               endif;
            else :
               $statusMessage = getLngt("ÜBERTRAGUNGSFEHLER! Die Anzahl der gescannten Objekte scheint mit der Anzahl abzuschließender Objekte NICHT übereinzustimmen! Bitte leider nochmal den Scan-Prozess wiederholen!");
            endif;
         else :
            $statusMessage = getLngt("Es sind derzeit keine Objekte im Bestand, die ausgebucht werden können!");
         endif;
      endif;
   
      // Reload objects to be scanned
      $objectsToBeBooked = getObjectsToBeBooked ($f_csc_selected, $f_article_type);
      $objectsToBeBookedLen = count($objectsToBeBooked);
   
      // Current costcenter name regarding a special virtual number mapping it
      if ($f_csc_selected != "") :
         $currCscName = getFieldValueFromId("costcenter", "csc_id", $f_csc_selected, "csc_name");
      endif;
   
   
      $htmlOut = "";
      for ($i = 0; $i < $objectsToBeBookedLen; $i++) :
          $htmlOut .= "<input type=\"text\" id=\"atih_" . $objectsToBeBooked[$i] . "\" name=\"atih_" . $objectsToBeBooked[$i] . "\" value=\"" . $objectsToBeBooked[$i] . "\" size=\"20\" readonly>\n";
          $htmlOut .= "<input type=\"hidden\" id=\"snr_" . $objectsToBeBooked[$i] . "\" name=\"snr_" . $objectsToBeBooked[$i] . "\" value=\"\"><br>\n";
      endfor;
   else :
      $execute = false;
      $currCscName = "";
      if ($f_csc_selected == "" || $cscPreIdOfSelected == "") :
         $currCscName .= "Es wurde keine " . wrapPhrase("Kostenstelle", $objecttypemode) . " ausgewählt!" . "<br><br>";
      endif;
      if ($f_article_type == "" || !is_numeric($f_article_type)) :
         $currCscName .= "Es wurde kein Objekttyp ausgewählt!" . "<br><br>";
      endif;
      $statusMessage = getLngt("Ein Bearbeitung kann nur nach Auswahl der operativen Einheit bzw. des Objekttyps erfolgen!");
   endif;
else :
  $execute = false;
  $currCscName = getLngt("Am heutigen Tag findet keine Ausbuchung statt!") . "<br><br>";
  $statusMessage = getLngt("Am heutigen Tag findet keine Ausbuchung statt!");
endif;

if ($debug) :
   echo "currCscName = " . $currCscName . "<br>";
   echo "statusMessage = " . $statusMessage . "<br>";
   echo "execute = " . $execute . "<br>";
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 type="text/javascript">
<!--

/********************************************************************************/
// Quelle: http://9elements.com/html5demos/audio/
// Audioelement erstellen
var ackSnd;
var hintSnd;
var warnSnd;
var finishOkSnd;
var soundOn = true;

try {
  ackSnd = new Audio("");
  hintSnd = new Audio("");
  warnSnd = new Audio("");
  finishOkSnd = new Audio("");
} catch (e) {
  soundOn = false;
}

function initSounds() {
  if (soundOn) {
     // im DOM einfügen, sonst wird es nicht abgespielt
     // document.body.appendChild(ackSnd);
     document.body.appendChild(hintSnd);
     document.body.appendChild(warnSnd);

     // herausfinden welcher Medientyp abgespielt werden kann
     var canPlayType = warnSnd.canPlayType("audio/wav");
     if(canPlayType.match(/maybe|probably/i)) {
       ackSnd.src = '../tools/sound/coin.mp3';
	     hintSnd.src = '../tools/sound/dead.wav';
  	   warnSnd.src = '../tools/sound/smash.mp3';
  	   finishOkSnd.src = '../tools/sound/doorbell.wav';
     } else {
       soundOn = false;
     }
  }
//	if (soundOn) {
//		alert("Sound is on!")
//  } else {
//		alert("Sound is off!")
// 	}  
}

function beepAck () {
	if (soundOn)
    ackSnd.play();
}

function beepHint () {
	if (soundOn)
    hintSnd.play();
}

function beepWarn () {
	if (soundOn)
    warnSnd.play();
}

function beepFinishOk () {
	if (soundOn)
    finishOkSnd.play();
}
/********************************************************************************/

// NAVIGATION
<?php echo $jsMenuOut; ?>

var numOfObjectsToBeBooked = <?php echo $objectsToBeBookedLen ?>;

var atihArr = Array();
<?php
for ($i = 0; $i < $objectsToBeBookedLen; $i++) :
    echo "atihArr[" . $i . "] = '" . $objectsToBeBooked[$i] . "'\n";
endfor;
?>
var atihArrLen = atihArr.length;  // Equals "$objectsToBeBookedLen" and equals "numOfObjectsToBeBooked"

function setScanFocus() {
  if ($('#f_scan')) {
     $('#f_scan').focus();
  }
}

// Check all barcodes of the list are scanned completely
function checkAllCodesAreScanned () {
  var listSannedCompletely = true;
  for(var i=0; i<atihArrLen; ++i) {
     if ($('#snr_' + atihArr[i]).val() != '1') {
     	 listSannedCompletely = false;
     }
  }
  return listSannedCompletely;
}

function executeScanCode() {
	frm = document.forms[0];
  var scan_value = trim($('#f_scan').val());
  var trackingIDsNotFound;
  var IDfound = false;
  if (scan_value != '') {
  	 IDfound = false;
     for(var i=0; i<atihArrLen; ++i) {
     	  atih_val = $('#atih_' + atihArr[i]).val();
     	  snr_found_val = $('#snr_' + atihArr[i]).val();
        if (atih_val == scan_value) {
        	 IDfound = true;
        	 $("#atih_" + atihArr[i]).css("background-color", "#00FF00");
           if (snr_found_val == '1') {
              beepHint();
  	          alert('<?php echo getLngt("Das Objekt hatten Sie schon gescanned!") ?>');
           } else {
           	 // Single existing code has been scanned correctly
             $('#snr_' + atihArr[i]).val('1');
             // Update list of correct scanned Codes
             correctScannedCodes = $('#correctScannedCodes').val();
     	       if (correctScannedCodes != '') {$('#correctScannedCodes').val($('#correctScannedCodes').val().concat(','))};
     	       $('#correctScannedCodes').val($('#correctScannedCodes').val().concat(scan_value))
             beepAck();
           }
        }
     }
     if (!IDfound) {
     	  beepWarn();
     	  alert('<?php echo getLngt("Das Objekt ist NICHT in der Liste enthalten!") ?>');
     	  // Check number is in the text field of numbers doing not exist ("double or multiple fail scan")
     	  trackingIDsNotFound = $('#trackingIDsNotFound').val();
     	  if (trackingIDsNotFound.indexOf(scan_value) == -1) {
     	     if (trackingIDsNotFound != '') {$('#trackingIDsNotFound').val($('#trackingIDsNotFound').val().concat(','))};
     	     $('#trackingIDsNotFound').val($('#trackingIDsNotFound').val().concat(scan_value))
     	  } else {
           beepHint();
  	       alert('<?php echo getLngt("Das Objekt hatten Sie schon gescanned UND es ist NICHT in der Liste enthalten!") ?>');
     	  }
     }
     if (checkAllCodesAreScanned ()) {
        beepFinishOk();
     }
  }
  $('#f_scan').val('');
  setScanFocus();
}

function execBodyOnLoad() {
<?php 
  echo $phpCurrentNavigationOnLoad;
?>
initSounds();
// initForm();
displayStatusMessage();
setScanFocus();
}

function finishPage(f_act) {
	document.forms[0].f_act.value = f_act;
	document.forms[0].submit();
}	

function finishSave() {
	var listScannedCompletly = checkAllCodesAreScanned();
	var trackingIDsNotFound = $('#trackingIDsNotFound').val();
	var doBook = false;
	var errLevel = '0';
	// Check cases
	if (listScannedCompletly && trackingIDsNotFound == '') {
	   if (confirm('<?php echo getLngt("Alle Objekte einwandfrei gescanned und keine fehlerhaften Scans! Möchten Sie die Ausbuchung jetzt durchführen?") ?>')) {
	   	  doBook = true;
     }
  } else {
  	 if (!listScannedCompletly) {
  	    if (confirm('<?php echo getLngt("Mindestens ein Objekt wurde NICHT gescanned! Möchten Sie DENNOCH die Ausbuchung jetzt durchführen?") ?>')) {
  	    	 errLevel = '1';
  	    	 doBook = true;
  	    }
  	 }
  	 if (trackingIDsNotFound != '') {
  	    if (confirm('<?php echo getLngt("Es wurde mindestens ein Objekt zusätzlich gescanned, welches nicht in der Liste verzeichnet ist! Möchten Sie DENNOCH die Ausbuchung jetzt durchführen?") ?>')) {
  	    	 if (errLevel == '1') {
  	    	 	  errLevel = '3';
  	    	 } else {
  	    	 	  errLevel = '2';
  	    	 }
  	    	 doBook = true;
  	    }
  	 }
  }
  if (doBook) {
  	 if (errLevel != '0') {
  	 	  $('#errLevel').val(errLevel);
  	 }
  	 finishPage('book');
  } else {
  	 alert('<?php echo getLngt("Der Vorgang wurde abgebrochen! Schließen Sie ggfs. die Seite, öffnen Sie sie neu und wiederholen Sie den Vorgang!") ?>');
  }
}

-->
</script>


</head>

<body onLoad="execBodyOnLoad();">

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

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

  <form name="scan" action="../illt/ati_bank_announcement_scan.php" method="post">

    <input type="hidden" name="f_act" value="">
    <?php echo $phpCurrentNavigationInputHidden ?>
    <input type="hidden" name="deactivateMenu" value="<?php echo ec($deactivateMenu) ?>">
    <input type="hidden" name="statusMessage" value="">

    <input type="hidden" name="customerId" value="<?php echo $customerId ?>">
    <input type="hidden" name="cscIdRoot" value="<?php echo $cscIdRoot ?>">
    <input type="hidden" name="cscIdActual" value="<?php echo $cscIdActual ?>">

    <input type="hidden" name="numOfObjectsToBeBooked" value="<?php echo $objectsToBeBookedLen ?>">
    <input type="hidden" name="f_article_type" value="<?php echo $f_article_type ?>">
    <input type="hidden" name="f_csc_selected" value="<?php echo $f_csc_selected ?>">

    <input type="hidden" id="errLevel" name="errLevel" value="0">
    <input type="hidden" id="correctScannedCodes" name="correctScannedCodes" value="">

    <br><br>

    <center>

    <?php if ($execute) : ?>
      <span class="f10bp1_blue"><?php echo getLngt(wrapPhrase("KOSTENSTELLE", $objecttypemode)) ?>:&nbsp;&nbsp;<?php echo $currCscName ?></span><br><br><br>
    <?php else : ?>
      <span class="f10bp1_blue"><?php echo $currCscName ?></span><br><br><br>
    <?php endif; ?>

    <?php if ($execute) : ?>
  	  <b><?php echo getLngt("BARCODE-SCAN:") ?></b>&nbsp;<input type="text" id="f_scan" name="f_scan" value="" size="20" onblur="javascript:executeScanCode();" border="2">

      <br><br>

      <?php echo $htmlOut ?>

      <br><br>

      <b><?php echo getLngt("Nicht zuzuordnende Objektnummern:") ?></b><br>
      <textarea id="trackingIDsNotFound" name="trackingIDsNotFound" cols="100" rows="3" onblur="javascript:setScanFocus();"></textarea>

      <br><br>

      <input type="button" name="button_save_changes" value="<?php echo getLngt("Ausbuchen") ?>" onclick="javascript:finishSave();">
    <?php endif; ?>

    </center>

  </div>

  </form>

</div>

</body>

</html>
