<?php
/*=======================================================================
 *
 * numbers_sb.php
 *
 * Autor: Carsten Annacker
 *
 =======================================================================*/

$special_numbers = array(
//  01736280777 Dresden "Managemant" (Profil geändert)
  "01736280800" => "<i>NL Ball</i>", // "Management"
//  01736280847 Leipzig "Team 1" (Profil geändert)
//  01736281003 Hannover "Team 1" (Profil geändert)
//  01736281013 Hannover "Team 1" (Profil geändert)
//  01736281034 Hannover "Team 1" (Profil geändert)
  "01736281081" => "<i>NL Essen</i>", // "Management"
//  01736281103 Notruf Dresden Profil 1 (Profil geändert)
  "01736281104" => "<i>Notruf Leipzig</i>", // "Profil 1"
//  01736281260 Berlin "Rufbereitschaft"
//  01736281373 Berlin "Rufbereitschaft"
//  01736281388 Berlin "Rufbereitschaft"
//  01736281392 Berlin "Rufbereitschaft"
//  01736281464 Berlin "Rufbereitschaft"
  "01736480168" => "<i>Notruf Bremen</i>", // "Profil 1"
  "01736480177" => "<i>Notruf Systemlogistik</i>" // "Profil 1"
);

//mysql_connect("localhost", "root", "%Fidewz37%")
mysql_connect("127.0.0.1:3711", "root", "%Fidewz37%")
  or die (mysql_error());
mysql_select_db("mobiledata")
  or die (mysql_error());
mysql_query('SET NAMES latin1')
  or die ('SET NAMES latin1');

$HTTP_GET_VARS = !empty($HTTP_GET_VARS) ? $HTTP_GET_VARS : $_GET;
$HTTP_POST_VARS = !empty($HTTP_POST_VARS) ? $HTTP_POST_VARS : $_POST;
//print_r($HTTP_POST_VARS);
$pn = $HTTP_GET_VARS['pn'];
$new_pn = $HTTP_POST_VARS['new_pn'];
$new_remark = $HTTP_POST_VARS['new_remark'];
$new_assignment = $HTTP_POST_VARS['new_assignment'];
$cur_time = time();
$wait_time = 2;
$free_count = 0;
$now = getdate();
$now_date = $now['year'] . "-" . sprintf("%02d", $now['mon']) . "-" . sprintf("%02d", $now['mday']);
$now_time = sprintf("%02d", $now['hours']) . ":" . sprintf("%02d", $now['minutes']) . ":" . sprintf("%02d", $now['seconds']);

$ob = $HTTP_GET_VARS['ob'];
$od = $HTTP_GET_VARS['od'];
$oda = array ($od, $od, $od, $od, $od, $od, $od, $od, $od);
$om = $HTTP_GET_VARS['om'];
$omStr = "";
if ($ob != "")
  $oda[$ob] = ($od == "d" ? "a" : "d");
if ($ob == "" && $om != 1)
  $omStr = "?om=1";

/**************************************************************************************************************************************************/
// 

// Änderungen speichern, falls vorhanden
if ($new_pn != ""):
  $sqlquery = "SELECT MAX(pa_id) AS mpa_id FROM phoneassign WHERE pa_number = '$new_pn'";
  $res = mysql_query($sqlquery) or die ($sqlquery);
  if ($row = mysql_fetch_array($res, MYSQL_ASSOC)):
    $mpa_id = $row["mpa_id"];
  else:
    die($sqlquery);
  endif;
  mysql_free_result($res);
  if ($new_assignment == "1"):
    $sqlquery = "INSERT INTO phoneassign (pa_number, pa_date, pa_remark) VALUES ('$new_pn', '$now_date $now_time', '$new_remark')";
  else:  
    $sqlquery = "UPDATE phoneassign SET pa_remark = '$new_remark' WHERE pa_id = $mpa_id";
  endif;
  mysql_query($sqlquery) or die ($sqlquery);
endif;

// Aktuelle (d.h. größte) Rechnungsnummer des Stadtboten finden
$sqlquery = "SELECT MAX(rechnungsnummer) AS mrn, MAX(abrechnungszeitraum_bis) AS azb FROM invoicedetails WHERE rechnungskonto = 91390786";
$res = mysql_query($sqlquery) or die ($sqlquery);
if ($row = mysql_fetch_array($res, MYSQL_ASSOC)):
  $mrn = $row["mrn"];
  $azb = $row["azb"];
else:
  die("Keine Rechnungsnummer für Rechnungskonto '91390786' gefunden");
endif;

// Alle aktuellen Rufnummern des Stadtboten sortiert nach dem Datum der letzten Verbindung
$sqlquery = "SELECT DISTINCT invoicedetails.interne_kennziffer AS ik, invoicedetails.rechnungsposten AS rp, MAX(calldetails.datum) AS mcd " .
  "FROM invoicedetails LEFT JOIN calldetails ON invoicedetails.rechnungsposten = calldetails.vd2_nummer_optional " .
  "WHERE invoicedetails.rechnungsnummer = $mrn AND LEFT(invoicedetails.rechnungsposten, 1) = '0' " .
  "GROUP BY invoicedetails.rechnungsposten ORDER BY mcd, calldetails.vd2_nummer_optional";
$res = mysql_query($sqlquery) or die ($sqlquery);
$phonenumbers = array();
while ($row = mysql_fetch_array($res, MYSQL_ASSOC)):
  $phonenumbers[$row["rp"]] = array($row["rp"], (trim($row["mcd"]) == '' ? "-" : $row["mcd"]), (trim($row["ik"]) == '' ? "-" : $row["ik"]), "", "", "", "", "", "", "");
endwhile;
mysql_free_result($res);

// Nur Datenverbindungen
$sqlquery = "SELECT vd2_nummer_optional AS vno, MAX(datum) AS mcd FROM calldetails " .
  "WHERE LEFT(vd2_nummer_optional, 1) = '0' " .
  "AND (rufnummer = '' AND NOT (call_info_indicator = 'A' OR call_info_indicator = 'r'))" .
  "GROUP BY vd2_nummer_optional ORDER BY mcd, vd2_nummer_optional";
$res = mysql_query($sqlquery) or die ($sqlquery);
while ($row = mysql_fetch_array($res, MYSQL_ASSOC)):
  if (array_key_exists($row["vno"], $phonenumbers))
    $phonenumbers[$row["vno"]][3] = $row["mcd"];
endwhile;
mysql_free_result($res);

// Nur Sprachverbindungen
$sqlquery = "SELECT vd2_nummer_optional AS vno, MAX(datum) AS mcd FROM calldetails " .
  "WHERE LEFT(vd2_nummer_optional, 1) = '0' " .
  "AND NOT (rufnummer = '' AND NOT (call_info_indicator = 'A' OR call_info_indicator = 'r'))" .
  "GROUP BY vd2_nummer_optional ORDER BY mcd, vd2_nummer_optional";
$res = mysql_query($sqlquery) or die ($sqlquery);
while ($row = mysql_fetch_array($res, MYSQL_ASSOC)):
  if (array_key_exists($row["vno"], $phonenumbers))
    $phonenumbers[$row["vno"]][4] = $row["mcd"];
endwhile;
mysql_free_result($res);

// Bereits vergebene Nummern holen
$sqlquery = "SELECT MAX(pa_id) AS mpa_id FROM phoneassign GROUP BY pa_number";
$res = mysql_query($sqlquery) or die ($sqlquery);
$pa_ids = "";
while ($row = mysql_fetch_array($res, MYSQL_ASSOC)):
  if ($pa_ids != "")
    $pa_ids .= ",";
  $pa_ids .= $row["mpa_id"];
endwhile;
mysql_free_result($res);
$sqlquery = "SELECT pa_number, pa_date, pa_remark FROM phoneassign WHERE pa_id IN (" . $pa_ids . ")";
$res = mysql_query($sqlquery) or die ($sqlquery);
while ($row = mysql_fetch_array($res, MYSQL_ASSOC)):
  if (array_key_exists($row["pa_number"], $phonenumbers)):
    $phonenumbers[$row["pa_number"]][7] = substr($row["pa_date"], 0, 10);
    $phonenumbers[$row["pa_number"]][8] = $row["pa_remark"];
  endif;
endwhile;
mysql_free_result($res);

// Alle in der Tabelle courier ordnungsgemäß eingetragene Rufnummern des Stadtboten sortiert nach dem Datum des letzten Logins
mysql_close();
mysql_connect("127.0.0.1:3391", "root", "%Fidewz37%")
  or die (mysql_error());
mysql_select_db("phoenix")
  or die (mysql_error());
$sqlquery = "SELECT REPLACE(REPLACE(REPLACE(cr_mobile_pda, '+49', '0'), '49173', '0173'), ' ', '') AS cmp, cr_sid, cr_logintime, hq_id FROM courier ORDER BY cmp, cr_logintime ASC";
$res = mysql_query($sqlquery) or die ($sqlquery);
$prev_row = array("", "", "", "");
while ($row = mysql_fetch_array($res, MYSQL_ASSOC)):
  if ($prev_row[0] != "" && $prev_row[0] != $row["cmp"]):
    if (array_key_exists($prev_row[0], $phonenumbers)):
      $phonenumbers[$prev_row[0]][5] = $prev_row[2];
      $phonenumbers[$prev_row[0]][6] = $prev_row[1];
      switch ($prev_row[3]):
        case 1: $phonenumbers[$prev_row[0]][9] = " (HB)"; break;
        case 2: $phonenumbers[$prev_row[0]][9] = " (HH)"; break;
        case 3: $phonenumbers[$prev_row[0]][9] = " (B)"; break;
        case 4: $phonenumbers[$prev_row[0]][9] = " (H)"; break;
        case 5: $phonenumbers[$prev_row[0]][9] = " (F)"; break;
        case 6: $phonenumbers[$prev_row[0]][9] = " (DD)"; break;
        case 7: $phonenumbers[$prev_row[0]][9] = " (E)"; break;
        case 8: $phonenumbers[$prev_row[0]][9] = " (L)"; break;
        case 11: $phonenumbers[$prev_row[0]][9] = " (S)"; break;
        default: $phonenumbers[$prev_row[0]][9] = " (" . $prev_row[3] . ")";
      endswitch;
    endif;
  endif;
  $prev_row = array($row["cmp"], $row["cr_sid"], $row["cr_logintime"], $row["hq_id"]);
endwhile;
mysql_free_result($res);

usort($phonenumbers, "cmp");
if ($ob != "")
  usort($phonenumbers, "cmpo");
 
$content =
  "<table border=1 width=100% cellspacing=0 cellpadding=0 vspace=0 hspace=0>\n" .
  "  <tr>\n" .
  "    <td align=left><div class=\"f7np1\">&nbsp;<a href=\"numbers_sb.php$omStr\"><b>Lfd. Nr.</b></a>&nbsp;</div></td>" .
  "    <td align=left><div class=\"f7np1\">&nbsp;<a href=\"numbers_sb.php?ob=0&od=".$oda[0]."\"><b>Rufummer</b></a>&nbsp;</div></td>" .
  "    <td align=left><div class=\"f7np1\">&nbsp;<a href=\"numbers_sb.php?ob=5&od=".$oda[5]."\"><b>Letzter Login</b></a>&nbsp;</div></td>" . 
  "    <td align=left><div class=\"f7np1\">&nbsp;<a href=\"numbers_sb.php?ob=6&od=".$oda[6]."\"><b>SID</b></a>&nbsp;</div></td>" . 
  "    <td align=left><div class=\"f7np1\">&nbsp;<a href=\"numbers_sb.php?ob=3&od=".$oda[3]."\"><b>Letzte<br>Datenverbindung</b></a>&nbsp;</div></td>" . 
  "    <td align=left><div class=\"f7np1\">&nbsp;<a href=\"numbers_sb.php?ob=4&od=".$oda[4]."\"><b>Letzte<br>Sprachverbindung</b></a>&nbsp;</div></td>" . 
  "    <td align=left><div class=\"f7np1\">&nbsp;<a href=\"numbers_sb.php?ob=2&od=".$oda[2]."\"><b>Interne Kennziffer</b></a>&nbsp;</div></td>" .
  "    <td align=left><div class=\"f7np1\">&nbsp;<a href=\"numbers_sb.php?ob=7&od=".$oda[7]."\"><b>Letzte<br>Neuvergabe</b></a>&nbsp;</div></td>" .
  "    <td align=left><div class=\"f7np1\">&nbsp;<a href=\"numbers_sb.php?ob=8&od=".$oda[8]."\"><b>Bemerkung</b></a>&nbsp;</div></td>" .
  "  </tr>\n";
foreach (array_keys($phonenumbers) as $phonenumber) {

  $edit_link = "<a href=\"numbers_sb.php?pn=" . $phonenumbers[$phonenumber][0] . "\"><img src=\"../mobiledata/p.gif\" border=0></a>";
  $new_assignment_disabled = "";
  $new_assignment_checked = "";
  $new_assignment_hidden = "";
  if (check_date($phonenumbers[$phonenumber][5]) && check_date($phonenumbers[$phonenumber][3]) && check_date($phonenumbers[$phonenumber][4])
    && check_date($phonenumbers[$phonenumber][7]) && $phonenumbers[$phonenumber][9] != " (B)" && !array_key_exists($phonenumbers[$phonenumber][0], $special_numbers)):
    $cur_no = "<span style=\"color:red\">" . ($phonenumber + 1) . "</span>";    
    $free_count++;
    $new_assignment_checked = "checked";
    if ($phonenumbers[$phonenumber][7] == ""):
      $new_assignment_disabled = "disabled";
      $new_assignment_hidden = "<input type=\"hidden\" name=\"new_assignment\" value=\"1\">";
    endif;
  else:
    $cur_no = ($phonenumber + 1);
    if ($phonenumbers[$phonenumber][7] == "" || $phonenumbers[$phonenumber][9] == " (B)" /* || array_key_exists($phonenumbers[$phonenumber][0], $special_numbers) */)
      $edit_link = "&nbsp;&nbsp;&nbsp;";
    else
      $new_assignment_disabled = "disabled";
      // Löschen ermöglichen
  endif;

  if (array_key_exists($phonenumbers[$phonenumber][0], $special_numbers)):
    $phonenumbers[$phonenumber][8] = $special_numbers[$phonenumbers[$phonenumber][0]];
  endif;

  $edit_form = "&nbsp;" . $phonenumbers[$phonenumber][8] . "&nbsp;";
  if ($phonenumbers[$phonenumber][0] == $pn):
    $edit_link = "<a href=\"numbers_sb.php\"><img src=\"../mobiledata/m.gif\" border=0></a>";
    $edit_form = "<form action=\"numbers_sb.php\" method=\"post\"><textarea name=\"new_remark\" cols=\"40\" rows=\"1\">" . $phonenumbers[$phonenumber][8] . "</textarea><br>\n" .
      "<input type=\"checkbox\" name=\"new_assignment\" value=\"1\" $new_assignment_checked $new_assignment_disabled> Neuvergabe&nbsp;&nbsp;&nbsp;$new_assignment_hidden<input type=\"hidden\" name=\"new_pn\" value=\"$pn\"><input type=\"submit\" value=\"Speichern\"></form>\n";
  endif;

  $content .=
    "  <tr>\n" .
    "    <td align=right><div class=\"f7np1\">&nbsp;" . $cur_no . "&nbsp;</div></td>\n" .        
    "    <td align=left><div class=\"f7np1\">&nbsp;" . 
    "      <a href=\"../mobiledata/details.php?rp=" . $phonenumbers[$phonenumber][0] . "\" target=\"_blank\" onclick=\"oeffnefenster(this.href); return false\">" .
           $phonenumbers[$phonenumber][0] . "</a>&nbsp;</div></td>\n" .
    "    <td align=left><div class=\"f7np1\">&nbsp;" . span_date($phonenumbers[$phonenumber][5]) . $phonenumbers[$phonenumber][9] . "&nbsp;</div></td>\n" .
    "    <td align=left><div class=\"f7np1\">&nbsp;" . $phonenumbers[$phonenumber][6] . "&nbsp;</div></td>\n" .
    "    <td align=right><div class=\"f7np1\">&nbsp;" . span_date($phonenumbers[$phonenumber][3]) . "&nbsp;</div></td>\n" .
    "    <td align=right><div class=\"f7np1\">&nbsp;" . span_date($phonenumbers[$phonenumber][4]) . "&nbsp;</div></td>\n" .
    "    <td align=left><div class=\"f7np1\">&nbsp;" . $phonenumbers[$phonenumber][2] . "&nbsp;</div></td>\n" .
    "    <td align=left><div class=\"f7np1\">" . $edit_link . "&nbsp;" . span_date($phonenumbers[$phonenumber][7]) . "&nbsp;</div></td>\n" .
    "    <td align=left><div class=\"f7np1\">" . $edit_form . "</div></td>\n" .
    "  </tr>\n";
}
$content .= 
  "</table><br>\n";

function cmp($a, $b)
{
	global $om;
	
	$a1 = ($a[3] < $a[4] ? $a[4] : $a[3]);
	$a1 = ($a1 < $a[5] ? $a[5] : $a1);
	if ($om != 1)
    $a1 = ($a1 < $a[7] ? $a[7] : $a1);
	
	$b1 = ($b[3] < $b[4] ? $b[4] : $b[3]);  	
	$b1 = ($b1 < $b[5] ? $b[5] : $b1);
	if ($om != 1)
    $b1 = ($b1 < $b[7] ? $b[7] : $b1);
	
	if ($a1 == $b1)
    return 0;
  return ($a1 < $b1) ? -1 : 1;
}

function cmpo($a, $b)
{
	global $ob, $od;

	if ($a[$ob] == $b[$ob])
    return 0;
  if ($od == "d")
    return ($a[$ob] > $b[$ob]) ? -1 : 1;
  return ($a[$ob] < $b[$ob]) ? -1 : 1;
}

function formDate ($sqlDate) {
  return substr($sqlDate, 8, 2) . "." . substr($sqlDate, 5, 2) . "." . substr($sqlDate, 0, 4);
}

function check_date($date_val)
{
	global $cur_time, $wait_time;
	
//  if (mktime(23, 59, 59, substr($date_val, 5, 2), substr($date_val, 8, 2), substr($date_val, 0, 4)) < $cur_time - ($wait_time * 24 * 60 * 60))
  if (mktime(23, 59, 59, substr($date_val, 5, 2) + $wait_time, substr($date_val, 8, 2), substr($date_val, 0, 4)) < $cur_time)
    return true;
  return false;
}

function span_date($date_val)
{
  if (check_date($date_val))
    return "<span style=\"color:red\">" . $date_val . "</span>";
  return $date_val;
}

/**************************************************************************************************************************************************/
// HTML-Output

?>

<html>
<head>
<title>RUFNUMMERN-NUTZUNG</title>
<link rel="stylesheet" type="text/css" href="phoenix.css">
<style type="text/css">
<!--
.verysmall
{ font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 2pt; font-weight: normal; padding: 0px}
-->
</style>
<script type="text/javascript">
//  Quelle: http://molily.de/javascript-popups
function oeffnefenster (url) {
 fenster=window.open(url, "_blank", "width=625,height=1000,status=yes,scrollbars=yes,resizable=yes");
 fenster.focus();
 return false;
}
</script>
</head>
<body>
  <table border="0" width="100%" cellspacing="0" cellpadding="0" vspace="0" hspace="0">
    <tr>
      <td>
        &nbsp;
      </td>
      <td align="center">
        <table border="0" cellspacing="0" cellpadding="0" vspace="0" hspace="0">
          <tr>
          	<td align="center"> <div class="f10bp1_blue">
              <br>
              Rufnummern-Nutzung Stadtbote<br>
              <br>
            </td>
          </tr>
          <tr>
          	<td align="center"> <div class="f8np1_blue">
              <i><b>
              <?php echo "Einzelverbindungen verfügbar vom 15.10.2008 bis " . formDate($azb) . "\n";?>
              <br></b></i>
              <br>
              <?php echo "Wartezeit vor Neuvergabe: <span style=\"color:red\"><b>" . $wait_time .
                 "</b></span> Monate; dies ergibt heute (" . formDate($now_date) . ") <span style=\"color:red\"><b>" . $free_count . "</b></span> neu vergebbare Rufnummern.\n<br>" .
                 "Nummern mit letztem Login eines Berliner Fahrers sowie fünf spezielle Nummern (siehe kursive Bemerkung) sind von der Neuvergabe ausgeschosssen.\n<br>";
              ?>
              <br>
              <br>
            </td>
          </tr>
          <tr>
          	<td align="center">
              <?php echo $content;?>
            </td>
          </tr>
        </table>
      </td>
      <td>
        &nbsp;
      </td>
    </tr>
  </table>
</body>
</html>
