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


// Get all ids of the bundled articles (next sublevel)
// $atId : Article id to be requested
// $mode : Recursion mode ("0" = top down, "1" = bottom up)
function getBundledArticles($atId, $mode = "0") {
  global $db, $PHP_SELF;
  $retArray = array();
  if ($atId != "" && is_numeric($atId)) :  
      $sqlStmt = "SELECT atb.at_id2 AS at_id_special, atb.atb_bundlequantity FROM articlebundle AS atb WHERE atb.at_id = '" . $atId . "' ";
      if ($mode == "1") :
         $sqlStmt = "SELECT atb.at_id AS at_id_special, atb.atb_bundlequantity FROM articlebundle AS atb WHERE atb.at_id2 = '" . $atId . "' ";
      endif;
      $result = $db->query($sqlStmt);
      if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
      while ($row = $result->fetch_assoc()):
        $retArray[$row["at_id_special"]] = $row["atb_bundlequantity"];
      endwhile;
      $result->free();
  endif;
  return $retArray;
}

// Checks for an article being a bundle (at least one "subarticle" does exist)
// $atId : Article id to be checked
function isBundledArticle($atId) {
  $retBool = false;
  if ($atId != "" && is_numeric($atId)) :
     $tmpArray = getBundledArticles($atId);
     $keys = array_keys($tmpArray);
     $keysLen = count($keys);
     if ($keysLen > 0) :
        $retBool = true;
     endif;
  endif;
  return $retBool;
}

// Updates the quantity of an existing bundled article
// $atId           : Parent article id to be checked
// $atId2          : Child article id to be checked
// $bundleQuantity : Quantity to be added to the existing quantity
function updateQuantityOfExistingBundledArticle($atId, $atId2, $bundleQuantity) {
	global $db, $PHP_SELF;
  $retBool = false;

  if ($atId != "" && is_numeric($atId) && $atId2 != "" && is_numeric($atId2) && is_numeric($bundleQuantity) && $bundleQuantity > 0) :
     $sqlStmt = "SELECT atb.atb_bundlequantity FROM articlebundle AS atb WHERE atb.at_id = '" . $atId . "' AND atb.at_id2 = '" . $atId2 . "' ";
     $result = $db->query($sqlStmt);
     if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
     $tmpBundleQuantity = 0;
     while ($row = $result->fetch_assoc()):
           $tmpBundleQuantity = $row["atb_bundlequantity"];
     endwhile;
     $result->free();

     // Add quantities and update
     $tmpBundleQuantity = $tmpBundleQuantity + $bundleQuantity;
     updateStmt("articlebundle","at_id",$atId,array("atb_bundlequantity", $tmpBundleQuantity),"at_id2 = '" . $atId2 . "'");

     $retBool = true;
  endif;
  return $retBool;
}

// Checks for cycles starting with a specified bundle (bottom up recursion)
// $currAtId        : Current Article to get the path(s) bottom up to root
// $atIdToBeChecked : Bundled article to be checked for cycle along the path(s)
function checkForCycle($currAtId, $atIdToBeChecked) {
  global $db, $PHP_SELF;
  global $noCycle, $recurseCount;

  // Number of recursions
  $recurseCount++;

  if ($noCycle) :
     if ($expandedBundleQuantitiy == "") : $expandedBundleQuantitiy = 1; endif;

     // Select bundled articles
     $tmpArray = getBundledArticles($currAtId, "1");  // Get parent(s)
     $keys = array_keys($tmpArray);
     $keysLen = count($keys);

     if ($keysLen > 0) :
        // Iterate current article being a bundle article
        for ($i = 0; $i < $keysLen; $i++) :
            $tmpAtId = $keys[$i];

            // Prepare to abort because cycle found
            // Check first current article (in $articleId [has to be defined]) is NOT a bundled article (<=> it is a leaf of the tree)
            // ONLY BUNDLED ARTICLES have to be checked for an existing cycle !!!
            if ($atIdToBeChecked == $tmpAtId) :
               // Cycle detected
               $noCycle = false;
            endif;                                                

            // Recursion ...	       		
            checkForCycle($tmpAtId, $atIdToBeChecked);
        endfor;
     endif;
  endif;
}

// Gets all articles of a specified bundle and gets all piece quantities (top down recursion)
// Following global parameters have to be set before: "atArray", "bundleArray", "noCycle"
// $atId : Article id to be requested
function getTreeOfBundledArticles($atId, $bundleQuantity, $expandedBundleQuantitiy) {
  global $db, $PHP_SELF;
  global $atArray, $noCycle, $recurseCount;

  // Number of recursions
  $recurseCount++;

  if ($noCycle && $recurseCount < 2000) :
     if ($expandedBundleQuantitiy == "") : $expandedBundleQuantitiy = 1; endif;

     // Select bundled articles
     $tmpArray = getBundledArticles($atId);  // Get children
     $keys = array_keys($tmpArray);
     $keysLen = count($keys);

     if ($keysLen > 0) :
        // Iterate current article being a bundle article
        for ($i = 0; $i < $keysLen; $i++) :
            $tmpAtId = $keys[$i];

            // Recursion ...	       		
            getTreeOfBundledArticles($tmpAtId, $tmpArray[$tmpAtId], ($expandedBundleQuantitiy * $tmpArray[$tmpAtId]));
        endfor;
     else :
	      // Current article is NOT a bundle article
        if ($atArray[$atId] == "") :
           // Get quantity explicitly
           $atArray[$atId] = 0;
        endif;
        // $atArray[$atId] = $atArray[$atId] + ($bundleQuantity * $expandedBundleQuantitiy);
        $atArray[$atId] = $atArray[$atId] + $expandedBundleQuantitiy;
     endif;
  endif;
}


// Init globals for bundle recursion
$atArray = array();
$bundleArray = array();
$bundleArray[$articleId] = 0;  // Init with current article
$noCycle = true;
$recurseCount = 0;
// getTreeOfBundledArticles($articleId, 0, 1);


// REMARK ...
/*
if ($noCycle) :
   // OK, no cycle found ...
   
   echo "<br>";
   echo "recurseCount: " . $recurseCount . "<br><br>";
   
   echo "atArray:<br>";
   $keys = array_keys($atArray);
   $keysLen = count($keys);
   for ($i = 0; $i < $keysLen; $i++) :
       $tmpAtId = $keys[$i];
       echo $tmpAtId . " : " .  $atArray[$tmpAtId] . "<br>";
   endfor;
   
   echo "----------------<br>";
   
   echo "bundleArray:<br>";
   $keys = array_keys($bundleArray);
   $keysLen = count($keys);
   for ($i = 0; $i < $keysLen; $i++) :
       $tmpAtId = $keys[$i];
       echo $tmpAtId . " : " .  $bundleArray[$tmpAtId] . "<br>";
   endfor;
else :
   echo "Cycle detected !!!<br>";
endif;
*/
?>
