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

include_once ("../include/mcglobal.inc.php");
include_once ("../include/inc_dbfields2array.inc.php");


// Sets the costsplit for a specified job
function setCostsplit($jobId = "") {
  global $db;
  if ($jobId != "" && is_numeric($jobId)) :
  
     // *** 1. ***
     // Get the persistent tourservice data of the current job from the homonymous table 
     $fieldString = getDBFields("tourservice");
     $sqlquery = "SELECT " . $fieldString
               . " FROM tourservice AS trs"
               . " WHERE trs.jb_id = '" . $jobId . "' AND"
               . "       trs.csc_id = '0'"
               . " ORDER BY trs.tr_sort";

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

     // Convert to transient array
     $fieldArray = $tmp = spliti(",",$fieldString);
     $idArrayLen = count($fieldArray);
     $trsData = convertRowToArray($result, $fieldArray, $idArrayLen);
     $trsDataLen = count($trsData);

     $result->free();


     // *** 2. ***
     // Get all costcenters (not external!) for the costsplit (containing the paying 3rd party if exists)     
     // "jb.csc_id_payer" is needed to check for an existing 3rd party
     $fieldString = "jb.csc_id_payer, tr.csc_id";
     $sqlquery = "SELECT " . $fieldString
               . " FROM job AS jb, tour AS tr, costcenter AS csc"
               . " WHERE jb.jb_id = '" . $jobId . "'   AND"
               . "       tr.jb_id = jb.jb_id           AND"
               . "       tr.csc_id = csc.csc_id        AND"
               . "       csc.csc_is_extern = '0'"
               . " ORDER BY tr.tr_sort";

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

     // Convert to transient array
     $fieldArray = spliti(",",$fieldString);
     $idArrayLen = count($fieldArray);
     $cscData = convertRowToArray($result, $fieldArray, $idArrayLen);
     $cscDataLen = count($cscData);

     $result->free();


     // *** 3. ***
     // Check for existence of a 3rd party AND get number of involved (unique) costcenters
     $cscIdArray = array();
     if ($cscDataLen > 0) :
        $cscIdPayer = $cscData[0]["csc_id_payer"];    // The payer is the same in all rows!
        for ($i = 0; $i < $cscDataLen; $i++) :
            // If $cscIdPayer exists in tour data it is NOT a third party => Initialize value
            if ($cscData[$i]["csc_id_payer"] == $cscData[$i]["csc_id"]) :
               $cscIdPayer = "";
            endif;

            // Add current costcenter to $cscIdArray if it is not in the list
            $val = array_search($cscData[$i]["csc_id"], $cscIdArray);
            if ($val === FALSE) :
               $cscIdArray[] = $cscData[$i]["csc_id"];
            endif;
        endfor;
     endif;
     // If exists add 3rd party to array of csc-IDs
     if ($cscIdPayer != "" && $cscIdPayer != "0") : $cscIdArray[] = $cscIdPayer; endif;
     $cscIdArrayLen = count($cscIdArray);          


     // *** 4. ***
     // Generate new row for all involved costcenters (perhaps the 3rd party, too) according to the costsplit
     if ($cscIdArrayLen > 1) :

        // TA("B");     

        // Delete existing persistent data out of the tourservice table
        deleteStmt("tourservice","jb_id = '" . $jobId . "'");
     
        // Iterate for all rows in $cscData and all rows in $trsData
        for ($i = 0; $i < $cscIdArrayLen ; $i++) :

            for ($j = 0; $j < $trsDataLen; $j++) :

                $price = $trsData[$j]["trs_price"] / $cscIdArrayLen;
                // $discount = $trsData[$j]["trs_discount"] / $cscIdArrayLen;   // only activate, if amount-values are stored in DB !!!
                $discount = $trsData[$j]["trs_discount"];                       // %-values are stored in DB !!!

                insertStmt("tourservice", array("jb_id", $jobId, "csc_id", $cscIdArray[$i], 
                           "tr_sort", $trsData[$j]["tr_sort"], 
                           "srv_id", $trsData[$j]["srv_id"], "trs_srv_name", $trsData[$j]["trs_srv_name"],
                           "srvt_id", $trsData[$j]["srvt_id"], "trs_srvt_name", $trsData[$j]["trs_srvt_name"], 
                           "trs_price", $price, "trs_discount", $discount));
            endfor;
        endfor;

        // TA("C");
        // TA("E");
     endif;
    
  endif;
}
?>