<?php
/*=======================================================================
 *
 * inv.inc.php
 *
 * Autor: Carsten Annacker
 *
 =======================================================================*/

include_once("../include/caglobal.inc.php");
include_once("../include/global.inc.php");
include_once("../include/auth.inc.php");

if ($dbhostStatistic != ""):
   $db2 = getDbConnectionSpecial ($dbhostStatistic, $dbname2, $dblogin2, $dbpassword2);
else:
   getDb2Connection();
endif;

$csc_id_customer_list_complete = array();
$csc_id_customer_list = array();

//list ($csc_id) =
getSecHttpVars("1", array("csc_id"));
//echo "'$csc_id'";
$hq_id = isset($HTTP_SESSION_VARS['hq_id']) ? $HTTP_SESSION_VARS['hq_id'] : 0;
$usr_id = isset($HTTP_SESSION_VARS['usr_id']) ? $HTTP_SESSION_VARS['usr_id'] : 0;
$usr_type = getFieldValueFromId("user", "usr_id", "$usr_id", "usr_type");
$cs_id = getFieldValueFromId("costcenter", "csc_id", "$csc_id", "cs_id");
$all_csc_ids = array();

// Decision to use the archive or normal tables
list ($dbhistory) = getHttpVars(array("dbhistory"));
getDBNames($dbhistory);

if ($usr_type == 2):
  // customer (employee)
  // get usr data
  list($csc_id_usr, $emp_rights) =
    getFieldsValueFromId("employee", "usr_id", $usr_id,
      array("csc_id", "emp_rights"));
  // check whether employee has invoice-rights
  if (substr($emp_rights, 5, 1) != '1'):
    reportDie ("$PHP_SELF: 'usr_id' '$usr_id' hat keine Rechte für das Rechnungsmodul!", false);
  endif;
  // if csc_id is given as parameter, check
  // whether csc_id_usr is parent of csc_id
  mkCsc_id_customer_list_complete();
  if (!costcenterIsParent($csc_id_usr, $csc_id)):
    $csc_id = $csc_id_usr;
  endif;
elseif ($usr_type == 1 || $usr_type == 0):
  // headquarter or sysadmin
  $cs_id = "";
elseif ($usr_type == 3):
else:
  reportDie ("$PHP_SELF: Ungültiger 'usr_type': '$usr_type'", false);
endif;

function mkCsc_id_customer_list_complete($mode = 0)
{
  global $PHP_SELF, /*$db2,*/ $hq_id, $cs_id, $csc_id_customer_list_complete, $usr_type, $dateSelectionStmt, $cs_eid, $cmp_name, $dbh_jb;

  $sqlQuery =
    "SELECT costcenter.csc_id, costcenter.csc_name, costcenter.csc_pre_id, costcenter.csc_path, customer.cs_eid, company.cmp_comp" .
    " FROM company, customer, costcenter" .
    " WHERE customer.cs_id = costcenter.cs_id AND company.cmp_id = customer.cmp_id";

  if ($usr_type == 0);
    // system administrator gets all costcenters in the system
  if ($usr_type == 1):
    if ($mode == 0):
    // MODE 0 IS CURRENTLY NOT USED ANY MORE
      // headquarter gets only costcenters of its customers ($mode == 0)
//      $sqlQuery =
//        "SELECT costcenter.csc_id, costcenter.csc_name, costcenter.csc_pre_id, costcenter.csc_path" .
//        " FROM costcenter, customer" .
//        " WHERE customer.csc_id = costcenter.csc_id AND customer.hq_id = '$hq_id'";
    elseif ($mode == 1):
      // Headquarter gets all costcenters of current customer
      // (for invoicing only, not for navigation)
      if ($cs_id != ''):
        $sqlQuery .= " AND customer.cs_id = '$cs_id'";
      else:
        // if no customer is given, get all costcenters of current hq_id

        // only costcenters with invoices are to be shown here!!!
//        $res = $db2->query("SELECT DISTINCT csc_id_payer FROM $dbh_jb WHERE jb_status = 2 AND hq_id = '$hq_id'");
//// TOBEDONE: consider date in query!!!
//        if (DB::isError($res))
//          reportDie ("$PHP_SELF: 'SELECT DISTINCT csc_id_payer FROM $dbh_jb WHERE jb_status = 2 AND hq_id = $hq_id': " . $res->getMessage());
//        $i = 0;
//        $csc_id_list_sql_arr = array();
//        while ($row = $res->fetch_assoc()):
//          $csc_id_list_sql_arr[] = $row["csc_id_payer"];
//        endwhile;
//        $res->free();
//        $csc_id_list_sql = implode(",", array_unique($csc_id_list_sql_arr));

//        $sqlQuery =
//          "SELECT costcenter.csc_id, costcenter.csc_name, costcenter.csc_pre_id, costcenter.csc_path" .
//          " FROM costcenter, customer" .
//          " WHERE customer.cs_id = costcenter.cs_id AND customer.hq_id = '$hq_id' AND " .
//          " costcenter.csc_id IN ($csc_id_list_sql)";
        $sqlQuery =
          "SELECT DISTINCT costcenter.csc_id, costcenter.csc_name, costcenter.csc_pre_id, costcenter.csc_path, customer.cs_eid, company.cmp_comp" .
          " FROM company, customer, costcenter, $dbh_jb" .
          " WHERE customer.cs_id = costcenter.cs_id AND company.cmp_id = customer.cmp_id " .
          " AND $dbh_jb.csc_id_payer = costcenter.csc_id AND $dbh_jb.jb_status = 2 AND $dbh_jb.hq_id = '$hq_id'";
        if ($cs_eid != "" || $cmp_name != ""):
          if ($cs_eid != ""):
            $sqlQuery .= " AND customer.cs_eid LIKE '%$cs_eid%'";
          endif;
          if ($cmp_name != ""):
            $sqlQuery .= " AND (company.cmp_comp LIKE '%$cmp_name%' OR company.cmp_match LIKE '%$cmp_name%')";
          endif;
          $sqlQuery .= " AND costcenter.csc_is_extern = 0";
        endif;
//          " WHERE costcenter.csc_id IN ($csc_id_list_sql)";
//"SELECT cs.cs_eid from customer AS cs, costcenter AS csc" .
//         " WHERE cs.cs_id = csc.cs_id AND csc.csc_id = '" . $$dbh_jb["csc_id_payer"] . "'"
//die( $sqlQuery);
      endif;
    else:
      reportDie ("$PHP_SELF: Ungültiger Wert für Parameter 'mode' : '$mode'");
    endif;
  endif;
  if ($usr_type == 2)
    // customer (employee) gets all its own costcenters
    $sqlQuery .= " AND customer.cs_id = '$cs_id'";
  // given cs_eid overrules date selection
//  if ($cs_eid == "" && $cmp_name == "")  
    $sqlQuery .= $dateSelectionStmt;
  $sqlQuery .= " ORDER BY csc_name";
  // select costcenters
//echo $sqlQuery . "<br>";
//include_once("../include/caglobal.inc.php");
  mkCsc_id_customer_list_complete_with_csc_pre_id($sqlQuery);
//print_r ($csc_id_customer_list_complete);
//  global $all_csc_ids;
//  print_r ($all_csc_ids);
  usort ($csc_id_customer_list_complete, "cmp_csc_id_customer_list_complete");

//print_r($csc_id_customer_list_complete);
//echo count($csc_id_customer_list_complete) . "<br>";
}

function mkCsc_id_customer_list_complete_with_csc_pre_id($sqlQuery)
{
  global $db2, $csc_id_customer_list_complete, $all_csc_ids;

  $tmp_csc_ids = array();
  $res = $db2->query($sqlQuery);
  if (DB::isError($res))
    reportDie ("$PHP_SELF: '$sqlQuery' : " . $res->getMessage());
  $i = count($csc_id_customer_list_complete);
  while ($row = $res->fetch_assoc()):
    if (!in_array ($row["csc_id"], $all_csc_ids)):
      $all_csc_ids[] = $row["csc_id"];
      $csc_id_customer_list_complete[$i]["csc_id"] = $row["csc_id"];
      $csc_id_customer_list_complete[$i]["csc_pre_id"] = $row["csc_pre_id"];
      if ($row["csc_pre_id"] != ""):
        $csc_id_customer_list_complete[$i]["csc_name"] = $row["csc_name"] . " (". $row["cs_eid"] . ")";
        if (!in_array ($row["csc_pre_id"], $all_csc_ids)):
          if (!in_array ($row["csc_pre_id"], $tmp_csc_ids)):
            $tmp_csc_ids[] = $row["csc_pre_id"];
          endif;
        endif;
      else:
        $csc_id_customer_list_complete[$i]["csc_name"] = $row["cmp_comp"] . " (". $row["cs_eid"] . ")";
      endif;
      $csc_id_customer_list_complete[$i++]["csc_path"] = $row["csc_path"];
    endif;
  endwhile;
  $res->free();
  if (count($tmp_csc_ids) > 0):
    $tmp_csc_ids_sql = implode(",", array_unique($tmp_csc_ids));
    $sqlQuery =
      "SELECT DISTINCT costcenter.csc_id, costcenter.csc_name, costcenter.csc_pre_id, costcenter.csc_path, customer.cs_eid, company.cmp_comp" .
      " FROM company, customer, costcenter" .
      " WHERE customer.cs_id = costcenter.cs_id AND company.cmp_id = customer.cmp_id " .
      " AND costcenter.csc_id IN ($tmp_csc_ids_sql)";
    mkCsc_id_customer_list_complete_with_csc_pre_id($sqlQuery);
  endif;
}

function cmp_csc_id_customer_list_complete ($a, $b) {
    if ($a["csc_name"] == $b["csc_name"]) return 0;
    return ($a["csc_name"] < $b["csc_name"]) ? -1 : 1;
}

function mkCsc_id_customer_list()
{
  global $cs_id, $csc_id, $csc_id_root,
    $csc_id_customer_list, $usr_type, $csc_id_usr,
    $csc_id_customer_list_complete;

  if ($usr_type == 2 || $usr_type == 1):
    // get identification of external costcenters
    // external costcenters cannot be invoiced,
    // private costcenters are not to be seen for anybody in the customer's company
    $csc_id_root = getFieldValueFromId("customer", "cs_id", "$cs_id", "csc_id");
    $csc_name_root = getFieldValueFromId("costcenter", "csc_id", "$csc_id_root", "csc_name");
    $csc_path_extern = "//" . $csc_name_root . "//EXTERN//";
    $csc_path_private = "//" . $csc_name_root . "//PRIVAT//";
    // write all costcenters for the current user
    // except external ones in array
    $j = 0;
//echo count($csc_id_customer_list_complete);
    for ($i = 0; $i < count($csc_id_customer_list_complete); $i++):
//echo "'" . strtoupper(substr($csc_id_customer_list_complete[$i]["csc_path"], 0,
//          strlen($csc_path_extern))) . "' == '" . strtoupper($csc_path_extern) . "'<br>";
      if ((strtoupper(substr($csc_id_customer_list_complete[$i]["csc_path"], 0,
          strlen($csc_path_extern)))
        != strtoupper($csc_path_extern)) &&
          (strtoupper(substr($csc_id_customer_list_complete[$i]["csc_path"], 0,
            strlen($csc_path_private)))
        != strtoupper($csc_path_private)) &&
          (strtoupper($csc_id_customer_list_complete[$i]["csc_name"]) != "EXTERN") &&
          ((strtoupper($csc_id_customer_list_complete[$i]["csc_name"]) != "PRIVAT" || $usr_type == 1))
        ):
//      if (substr($csc_id_customer_list_complete[$i]["csc_path"], 0, strlen($csc_path_start))
//        != $csc_path_extern):
//echo "'" . $csc_id_usr . "' '" . $csc_id_customer_list_complete[$i]["csc_id"] . "'<br>";
        if ($usr_type == 1):
          // Only if the costcenter of the user currently logged in
          // is parent of the current costcenter, then take it
          $csc_id_customer_list[$j]["csc_id"] = $csc_id_customer_list_complete[$i]["csc_id"];
          $csc_id_customer_list[$j]["csc_name"] = $csc_id_customer_list_complete[$i]["csc_name"];
          $csc_id_customer_list[$j++]["csc_pre_id"] = $csc_id_customer_list_complete[$i]["csc_pre_id"];
        else:
          if (costcenterIsParent($csc_id_usr, $csc_id_customer_list_complete[$i]["csc_id"])):
            $csc_id_customer_list[$j]["csc_id"] = $csc_id_customer_list_complete[$i]["csc_id"];
            $csc_id_customer_list[$j]["csc_name"] = $csc_id_customer_list_complete[$i]["csc_name"];
            $csc_id_customer_list[$j++]["csc_pre_id"] = $csc_id_customer_list_complete[$i]["csc_pre_id"];
          endif;
        endif;
      endif;
    endfor;
  else:
    // usr_type 0
    for ($i = 0; $i < count($csc_id_customer_list_complete); $i++):
      $csc_id_customer_list[$i]["csc_id"] = $csc_id_customer_list_complete[$i]["csc_id"];
      $csc_id_customer_list[$i]["csc_name"] = $csc_id_customer_list_complete[$i]["csc_name"];
      $csc_id_customer_list[$i]["csc_pre_id"] = $csc_id_customer_list_complete[$i]["csc_pre_id"];
    endfor;
  endif;
//print_r($csc_id_customer_list);
}

function costcenterIsParent($csc_id_parent, $csc_id_child)
{
  global $csc_id_customer_list_complete;

//echo $csc_id_child . "<br>";
  if ($csc_id_parent == $csc_id_child)
    return true;
  for($i = 0; $i < count($csc_id_customer_list_complete); $i++):
    if ($csc_id_customer_list_complete[$i]["csc_id"] == $csc_id_child):
      if ($csc_id_customer_list_complete[$i]["csc_pre_id"] == $csc_id_parent):
        return true;
      else:
        if ($csc_id_child == "")
          return false;
        else
          return costcenterIsParent($csc_id_parent, $csc_id_customer_list_complete[$i]["csc_pre_id"]);
      endif;
    endif;
  endfor;
}

function check_daterange()
{
  global $dateSelectionStmt, $day_from, $month_from, $year_from, $day_to, $month_to, $year_to,
    $jb_costcenter, $fromDateRange, $toDateRange, $dbh_jb, $price_title;

  list ($day_from, $month_from, $year_from,
    $day_to, $month_to, $year_to, $jb_costcenter) =
      getHttpVars(array("day_from", "month_from", "year_from",
        "day_to", "month_to", "year_to", "jb_costcenter"));
  // check daterange
  $dateSelectionStmt = "";
  if ($day_from != "" && $month_from != "" && $year_from != "" ||
    $day_to != "" && $month_to != "" && $year_to != ""):
     // dates are given
  else:
    // dates are not given
//    include_once("../include/calendar.inc.php");
    $day_to = date("d");
    $day_from = 1;
    $month_to = date("m");
    $month_from = $month_to;
    $year_to = date("Y");
    $year_from = $year_to;
//    list($year_from, $month_from) = addMonths($year_to, $month_to, -1);
//    $day_from = $day_to + 1;
//    if (daysPerMonth($year_from, $month_from) < $day_from)
//      $day_from = daysPerMonth($year_from, $month_from);
  endif;
  $fromDateRange = $year_from . "-" . pad($month_from,2) . "-" . pad($day_from,2) . " 00:00:00";
  $toDateRange = $year_to . "-" . pad($month_to,2) . "-" . pad($day_to,2) . " 23:59:59";
  $dateSelectionStmt = " AND ($dbh_jb.jb_finishtime BETWEEN '$fromDateRange' AND '$toDateRange')";

  if (MASK_CR_PRICE_MODE == "1") {
    $price_title = "Vergütung";
    if (strtotime(MASK_CR_PRICE_MODE_DATE) > strtotime($fromDateRange))
      $price_title .= " (bis " . substr(MASK_CR_PRICE_MODE_DATE, 8, 2) . "." . substr(MASK_CR_PRICE_MODE_DATE, 5, 2) . "."  . substr(MASK_CR_PRICE_MODE_DATE, 0, 4) . " Auftragspreis)";
  }
}

?>
