<script language="javascript"> 
  function checkOperator() {
      myForm = document.forms.suchen;
      operatorDropdown = myForm.operatorkontostand;
      operatorkontostand = myForm.kontostand;

      if ((operatorkontostand.value) && (!operatorDropdown.value)) {
          operatorDropdown.selectedIndex=1;
      }
  }
</script>

<div class="module">Erweiterte Suche</div>
<?
#$searchfields = array('versnummer', 'name', 'vorname', 'strasse', 'plz', 'ort', 'email', 'datefrom', 'dateto', 'datefrompraemie', 'datetopraemie', 'kontomatch', 'loggedin', 'praemiebestellt');
$searchfields = array('versnummer', 'anrede', 'name', 'vorname', 'strasse', 'plz', 'ort','land', 'email', 'datefrom', 'dateto', 'datefromchange', 'datetochange', 'status', 'datefrompraemie', 'datetopraemie', 'kontomatch', 'kontostand', 'operatorkontostand', 'loggedin', 'praemiebestellt','u18');
if (! isset($state)) { $state = ""; }
if ($state == "savematches")
{
    if (!$saveas) {
        echo '<div class="error">Bitte geben Sie einen Namen f&uuml;r die zu speichernden Suchkriterien an.</div>';
    } else {
        $saveas=escape($saveas);
        $query = "SELECT * FROM matches WHERE matchname LIKE '$saveas'";
        $result = dbQuery($query) or error("Kann Matches nicht auslesen: $query - " . dbError());
        if (dbNumRows($result) > 0)
        {
            echo '<div class="error">Unter diesem Namen sind schon Suchkriterien abgespeichert.</div>';
        } else {
            $query = "INSERT into matches VALUES ('$saveas'";
            foreach ($searchfields as $searchfield) $query .= ",'" . $$searchfield . "'";
            $query .= ")";
            dbQuery($query) or error("Kann Match nicht eintragen: " .  dbError());
            $matchFilename = convertFileName($saveas);

        }
    }
    $state="submitted";
}

if ($state == "loadmatches")
{
    $matchname = escape(escape($matchname));
    $_SESSION[$module] = '';
    $query = "SELECT * FROM matches WHERE matchname LIKE '$matchname'";
    $result = dbQuery($query);
    $row = dbFetchRow($result);
    dbFreeResult($result);
    foreach ($searchfields as $searchfield)
    {
        if ($row[$searchfield]) {
            $$searchfield = $row[$searchfield];
        }
    }
    # $state="submitted";
}

if ($state == "deletematches")
{
    $matchname = escape(escape($matchname));
    $_SESSION[$module] = '';
    $query = "DELETE FROM matches WHERE matchname LIKE '$matchname'";
    $result = dbQuery($query) or error("Kann Match $matchname nicht l&ouml;schen: " . dbError());

    if (file_exists("exportfiles/extended/$matchname.csv.xls"))
    {
        unlink("exportfiles/extended/$matchname.csv.xls");
    }
    # $state="submitted";
}


if ($state == "submitted" || isset($matchFilename))
{

    /* wenn sorfield nicht gesetzt ist, dann hole Matchdaten aus der
     * Session
     */
    if ($_SESSION[$module] && (!$sortfield))
    {
        /* wenn Session gesetzt ist */
        foreach ($searchfields as $searchfield)
        {
            $$searchfield = $_SESSION[$searchfield];
        }
        $from = $_SESSION['from'];
        $sortfield = $_SESSION['sortfield'];
        $dir = $_SESSION['dir'];
    }

    /* create user template to match */
    $matchUser = new user();

    foreach ($searchfields as $searchfield)
    {
        $matchUser->$searchfield = $$searchfield;
    }

    if ($status) { $matchUser->status = '0'; }
    if ($datefrom) { $matchUser->datefrom = dateToTimestamp($datefrom); }
    if ($dateto) { $matchUser->dateto = dateToTimestamp($dateto); }
    if ($u18) { $matchUser->u18 = $u18; }
    
    if ($datefromchange) { $matchUser->datefromchange = dateToTimestamp($datefromchange); }
    if ($datetochange) { $matchUser->datetochange = dateToTimestamp($datetochange); }

    if ($datefrompraemie) { $matchUser->datefrompraemie = dateToTimestamp($datefrompraemie); }
    if ($datetopraemie) { $matchUser->datetopraemie = dateToTimestamp($datetopraemie) + 86400; }
    if ($loggedin) { $matchUser->loggedIn = $loggedin; }
    if ($praemiebestellt) { $matchUser->praemiebestellt = true; }
    if ($kontomatch) { $matchUser->kontomatch = $kontomatch; }
    if ($operatorkontostand) { $matchUser->operatorkontostand =
        $operatorkontostand; }
    if ($kontostand) { $matchUser->kontostand = $kontostand; }

    /* Trage matchdaten fuer spaetere Verwendung in die Session ein */
    foreach ($searchfields as $searchfield)
    {
        $_SESSION[$searchfield] = $$searchfield;
    }
    $_SESSION[$module] = true;
    $_SESSION['from'] = $from;
    $_SESSION['sortfield'] = $sortfield;
    $_SESSION['dir'] = $dir;

    if (!$from) ($from = 0);
    /* get matching users */
    #print_r ($matchUser);
    #break;
    $users = $matchUser->getUsers($sortfield, $dir,1);

    if (count($users) == 0)
    { 
            echo "Kann Teilnehmer nicht finden<br>\n";
            $state="";
    } else {
        /* schreibe Exportdatei */
        $filename = exportCSVselected($users);
        if ($matchFilename)
        {
            copy($filename, "exportfiles/extended/". unescape($matchFilename) . ".xls");
        }

        /* Zeige Ergebnisse */

       if (!$sortfield) $sortfield = "erstellungsdatum";

   if (count($users) < $maxLinesPerTable) {
       $maxLinesPerTable = count($users);
   }

   $to = $from + $maxLinesPerTable;
   if (count($users) < $to) { $to = count($users); }
?>
 <br />

<? /* Downloadfeld anzeigen */ ?>
 <form name="filename" action="#" method="POST" onsubmit="return submitdownload()"  >
   <input type="hidden" name="module" value="<?=$module?>" />
   <input type="hidden" name="state" value="download" />
   <fieldset class="fieldset"><legend>CSV-Datei herunterladen</legend>
   <table>
     <tr>
       <td>Dateiname</td>
       <td><input class="inputgen" size="40" type="text" name="downloadfilename" value="<?=$filename?>" /></td>
     </tr>
     <tr>
       <td>&nbsp;</td>
       <td><input class="submit" title="Laden sie hiermit eine Datei mit dem Suchergebnis als Excel-Datei herunter" type="submit" name="submit" value="Herunterladen" /></td>
   </table>
   </fieldset>
 </form>
<? /*---------------------------------*/ ?>

<? /* Suchkriterien speichern */ ?>
 <form name="savematches" action="<?=$_SERVER['REQUEST_URI']?>" method="POST">
   <input type="hidden" name="module" value="<?=$module?>" />
   <input type="hidden" name="state" value="savematches" />
   <fieldset class="fieldset"><legend>Suchkriterien speichern</legend>
   <table>
   <? foreach ($searchfields as $searchfield)
   {
       if ($$searchfield) {
           ?>
     <tr>
       <td><?=$searchfield?><input type="hidden" name="<?=$searchfield?>" value="<?=$$searchfield?>" /></td>
       <td><?=$$searchfield?></td>
     </tr>
   <?
       }
   }
   ?>
     <tr>
       <td>Speichern unter</td>
       <td><input type="text" class="inputgen" name="saveas" value="<?=unescape($saveas)?>"/></td>
     </tr>
     <tr>
       <td>&nbsp;</td>
       <td><input type="submit" class="submit" value="abspeichern"
       title="Hiermit k&ouml;nnen Sie Ihre Auswahlkriterien zur sp&auml;teren Verwendung abspeichern."
       /></td>
     </tr>
   </table>
   </fieldset>
 </form>
<? /*---------------------------------*/ ?>

     <script language="JavaScript">
       document.forms.filename.downloadfilename.focus();
       function submitdownload()
       {
           downloadfile = document.forms.filename.downloadfilename.value;
           newhref='downloadcsv.php?downloadfile=' +
               downloadfile + '&file=extended/datenexport.csv.xls';

           document.location.href=newhref;
           return false;
       }

       function formsubmit(name)
       {
           /* first change sorting order */
           if (document.forms.usertable.sortfield.value=='<?=$sortfield?>')
           {
               if (document.forms.usertable.dir.value == 'ASC')
               {
                   document.forms.usertable.dir.value = 'DESC';
               } else {
                   document.forms.usertable.dir.value = 'ASC';
               }
           }
           document.forms.usertable.sortfield.value=name;
           document.forms.usertable.submit();
       }

       function formstart()
       {
           document.forms.usertable.from.value='0';
           document.forms.usertable.submit();
       }

       function formback(start)
       {
           document.forms.usertable.from.value=start;
           document.forms.usertable.submit();
       }

       function formforward(start)
       {
           document.forms.usertable.from.value=start;
           document.forms.usertable.submit();
       }
     </script>

     <form name="usertable" action="<?=$_SERVER['REQUEST_URI']?>" method="POST" width="650">
       <input type="hidden" name="module" value="<?=$module?>" />
       <input type="hidden" name="state" value="submitted" />
<?
    foreach ($searchfields as $searchfield)
    {
        if ($$searchfield) 
?>
       <input type="hidden" name="<?=$searchfield?>" value="<?=$$searchfield?>" />
<?
    }
?>
       <input type="hidden" name="sortfield" value="<?=$sortfield?>" />
       <input type="hidden" name="dir" value="<?=$dir?>" />
       <input type="hidden" name="from" value="<?=$from?>" />
       <p>
       Ergebnisse: <?=$from +1?> bis <?=$from + (count($users)<$maxLinesPerTable)?count($users):$maxLinesPerTable?> von <strong><?=count($users)?></strong>, sortiert nach: <?=$sortfield?><br>
       <? if ($from >= 1) { ?><a href="javascript:formstart()">&lt;&lt;</a> | <?  } else { echo "&lt;&lt | ";} ?>
       <? if ($from >= 1) { ?><a href="javascript:formback(<?=$from - $maxLinesPerTable?>)">&lt;</a> | <?  } else { echo "&lt | ";} ?>
       <? if ($from < (count($users) - $maxLinesPerTable -1)) { ?><a href="javascript:formforward(<?=$from + $maxLinesPerTable?>)">&gt;</a><?  } else { echo "&gt | ";} ?>
       <? if ($from < count($users) - $maxLinesPerTable) { ?> | <a href="javascript:formforward(<?=round(count($users)/$maxLinesPerTable - 0.5)*$maxLinesPerTable?>)">&gt;&gt;</a><?  } else { echo "&gt&gt ";} ?>

       </p>
       <table border="0" cellspacing="1" cellpadding="3" style="border: 1px solid black">
         <tr bgcolor='#dddddd'>
           <td width="42"><a href="javascript:formsubmit('anrede')">Anrede/Titel</a></td>
           <td width="110"><a href="javascript:formsubmit('vorname')">Vorname</a></td>
           <td width="120"><a href="javascript:formsubmit('name')">Name</a></td>
           <td width="200"><a href="javascript:formsubmit('strasse')">Strasse</a></td>
           <td width="50"><a href="javascript:formsubmit('plz')">Plz</a></td>
           <td width="120"><a href="javascript:formsubmit('ort')">Ort</a></td>
           <td width="120"><a href="javascript:formsubmit('land')">Land</a></td>
           <td><a href="javascript:formsubmit('email')">E-Mail</a></td>
           <td width="100"><a href="javascript:formsubmit('versnummer')">Vers.Nr.</a></td>
           <td width="100"><a href="javascript:formsubmit('versnummer')">Vers.Nr.Neu</a></td>
           <td>&nbsp;</td>
         </tr>
<?
       $color[0] = "#eeeeee";
       $color[1] = "#f2f2f2";
       $coln=0;
       for ($i = $from; $i < $to; $i++)
       {
           $user = new user('',$users[$i]);
           $colnr=1-$colnr;
           $mycolor = $color[$colnr];
           if ($userId == $user->userId)
           {
               $mycolor = '#fff2f2';
           }
?>
         <tr bgcolor="<?=$mycolor?>">
           <td><?=$user->anrede . ' ' . $user->titel?></td> 
           <td><?=$user->vorname?></td>
           <td><?=$user->name?></td>
           <td><?=$user->strasse . " " . $user->hausnummer?></td>
           <td><?=$user->plz?></td>
           <td><?=$user->ort?></td>
           <td><?=$user->land?></td>
           <td><?=$user->email?></td> 
           <td><?=$user->versnummer?> <?=$user->rechtskreis?></td>
           <td><?=$user->versnummerneu?></td>
           <td>
             <table>
               <tr>
                 <td>
             <a href="<?=$_SERVER['SELF_PHP']?>?module=<?=$module?>&action=edit&userId=<?=$user->userId?>&deleted=<?=$deleted?>"><img src="/grafik/button_edit.png" border="0" alt="Editieren" /></a>
                 </td>
                 <td>
                   <a href="mailto:<?=$user->email?>"><img src="/grafik/button-mail.gif" border="0" alt="EMail" /></a>
                 </td>
                 <td>
             <a href="<?=$_SERVER['SELF_PHP']?>?module=<?=$module?>&action=addpoints&userId=<?=$user->userId?>&deleted=<?=$deleted?>"><img src="/grafik/button_points.png" border="0" alt="Punkte vergeben" /></a>
             <!-- <a href="<?=$_SERVER['SELF_PHP']?>?module=delete&userId=<?=$user->userId?>"><img src="../grafik/button_points.png" border="0" alt="Teilnehmer loeschen" /></a> -->
                 </td>
                 <? if ($loggedIn->role == 'superuser') { ?>
                 <td>
             <a href="<?=$_SERVER['SELF_PHP']?>?module=<?=$module?>&action=delete&userId=<?=$user->userId?>"><img src="/grafik/button_drop.png" border="0" alt="Teilnehmer loeschen" /></a>
                 </td>
                 <? } ?>
               <tr>
             </table>
           </td>
         </tr>
<?
       }
?>
</table>
</form>
<?
    }
}

  if ($state!="submitted")
{
    $_SESSION[$module] = false;
    ?>

 <br>
 <form name="suchen" action="<?=$_SERVER['REQUEST_URI']?>" method="POST">
    <input type="hidden" name="module" value="<?=$module?>" />
    <input type="hidden" name="state" value="submitted" />

    <fieldset class="fieldset"><legend>Pers. Daten</legend>
    <table>
      <tr>
        <td>Vers.Nummer</td><td><input type="text" name="versnummer" value="<?=$versnummer?>" /></td>
      </tr>
      <tr>
        <td>Anrede</td><td><input type="text" name="anrede" /></td>
      </tr>
      <tr>
        <td>Name</td><td><input type="text" name="name" value="<?=$name?>" /></td>
      </tr>
      <tr>
        <td>Vorname</td><td><input type="text" name="vorname" value="<?=$vorname?>" /></td>
      </tr>
      <tr>
        <td>Stra&szlig;e</td><td><input type="text" name="strasse" value="<?=$strasse?>" /></td>
      </tr>
      <tr>
        <td>PLZ</td><td><input type="text" name="plz" value="<?=$plz?>" /></td>
      </tr>

      <tr>
        <td>Ort</td><td><input type="text" name="ort" value="<?=$ort?>" /></td>
      </tr>

      <tr>
        <td>Land</td><td><select name="land">
<? foreach ($eucountries as $iso=>$country) { ?>
                  <option value="<?=$country?>" <?=($country==$land)?'selected="selected"':''?>><?=$country?></option>
<? } ?></td>
      </tr>

      <tr>
          <td>Geburtsdatum</td>
          <td><input type="text" name="geburtsdatumtag" value="<?=$geburtsdatumtag?>" size="2" maxlength="2" /> .
          <input type="text" name="geburtsdatummonat" value="<?=$geburtsdatummonat?>" size="2" maxlength="2" /> .
          <input type="text" name="geburtsdatumjahr" value="<?=$geburtsdatumjahr?>" size="4" maxlength="4" />
          </td>
        </tr>

      <tr>
        <td>E-Mail</td><td><input type="text" name="email" value="<?=$email?>" /></td>
      </tr>
<!-- TODO: U18-Selektion -->
      <tr>
        <td>Vollj&auml;hrig?</td><td>
          <input title="Ist der Teilnhmer Vollj&auml;hrig?" class="inputradio" type="radio" name="u18" value="yes" <? if ($u18 == 'no') echo " checked";?> /> nein
          <input title="Ist der Teilnhmer Vollj&auml;hrig?" class="inputradio" type="radio" name="u18" value="no" <? if ($u18 == 'yes') echo " checked";?> /> ja
        </td>
      </tr>

      <tr>
        <td>Erstellungsdatum<br />Datum von</td><td><input type="text" name="datefrom" value="<?=$datefrom?>" title="Zeitraum in dem der Teilnehmer eingetragen wurde, z.B. 12.11.2004 13:06" /></td>
      </tr>
      <tr>
        <td>Datum bis ausschliesslich</td><td><input type="text" name="dateto" value="<?=$dateto?>" title="Zeitraum in dem der Teilnehmer eingetragen wurde" /></td>
      </tr>
      <tr>
        <td>&Auml;nderungsdatum<br />Datum von</td><td><input type="text" name="datefromchange" value="<?=$datefromchange?>" title="Zeitraum in dem der Teilnehmer ge&auml;ndert wurde, z.B. 12.11.2004 13:06" /></td>
      </tr>
      <tr>
        <td>Datum bis</td><td><input type="text" name="datetochange" value="<?=$datetochange?>" title="Zeitraum in dem der Teilnehmer ge&auml;ndert wurde" /></td>
      </tr>
      <tr>
        <td>Nur f&uuml;r Export vorge-<br />sehene Daten anzeigen</td><td><input title="Wird der Teilnehmer beim n&auml;chsten Export ber&uuml;cksichtigt?" class="inputradio" type="checkbox" name="status" <? if ( isset($status)) echo " checked";?> /></td>
      </tr>


    </table>
    </fieldset>
    <br />
    <fieldset class="fieldset"><legend>Weitere Einschr&auml;nkungen</legend>
    <table>
      <tr>
        <td>Hat Pr&auml;mie bestellt</td><td><input title="Hat der Teilnehmer bereits eine Pr&auml;mie bestellt?" class="inputradio" type="checkbox" name="praemiebestellt" <? if ($praemiebestellt) echo " checked";?> /></td>
      </tr>
      <tr>
        <td>Login</td><td>
          <input title="Hat der Teilnehmer sich auf der Healthmiles-Site schon einmal angemeldet?" class="inputradio" type="radio" name="loggedin" value="no" <? if ($loggedin == 'no') echo " checked";?> /> nein
          <input title="Hat der Teilnehmer sich auf der Healthmiles-Site schon einmal angemeldet?" class="inputradio" type="radio" name="loggedin" value="yes" <? if ($loggedin == 'yes') echo " checked";?> /> ja
          <input title="Hat der Teilnehmer sich auf der Healthmiles-Site schon einmal angemeldet?" class="inputradio" type="radio" name="loggedin" value="" <? if (!$loggedin) echo " checked";?> /> egal
        </td>
      </tr>
      <tr>
        <td>Text in Pr&auml;mienkonto</td><td><input title="z.B. Bezeichnung der Pr&auml;mie" type="text" name="kontomatch" value="<?=$kontomatch?>" /></td>
      </tr>

      <tr>
        <td>Kontostand <select name="operatorkontostand" title="Vergleichsoperator fuer Kontostand" onChange="checkOperator()">
          <option></option>
          <option>&gt;=</option>
          <option value='=='>=</option>
          <option>&lt;</option>
        </select>
        </td><td><input title="Kontostand X Punkte" type="text" name="kontostand" value="<?=$kontostand?>" onChange="checkOperator()" /></td>
      </tr>

      <tr>
        <td>Datum von</td><td><input type="text" name="datefrompraemie"
        value="<?=$datefrompraemie?>" title="Zeitraum fuer die Suche im Pr&auml;mienlog bzw. Kontostand, zB: 12.11.2004 13:06" /></td>
      </tr>
      <tr>
        <td>Datum bis</td><td><input type="text" name="datetopraemie" value="<?=$datetopraemie?>" title="Zeitraum fuer die Suche im Pr&auml;mienlog bzw. Kontostand, zB: 12.11.2004 13:06" /></td>
      </tr>

      <tr>
        <td>&nbsp;</td>
        <td><input type="submit" value="suchen"></td>
      </tr>
    </table>
    </fieldset>
  </form>
  <script language="JavaScript">
    document.forms.suchen.versnummer.focus();
  </script>

<? /* Gespeicherte Suchkriterien anzeigen */ ?>
   <input type="hidden" name="module" value="<?=$module?>" />
   <input type="hidden" name="state" value="loadmatches" />
   <fieldset class="fieldset"><legend>Gespeicherte Suchkriterien</legend>
   <table>
     <tr>
<? $query = "SELECT * FROM matches";
$result = dbQuery($query) or error('Kann gespeicherte Suchkriterien nicht laden: ' . dbError());
$i=0;
while ($row = dbFetchRow($result)) { ?>
     <td valign="top">
     <table style="border: solid 1px black" width="320">
     <tr bgcolor="#dddddd">
       <td>Matchname</td>
       <td><a href="<?=$_SERVER['REQUEST_URI']?>?module=<?=$module?>&state=loadmatches&matchname=<?=unescape($row['matchname'])?>"><?=unescape($row['matchname'])?></a></td>
     </tr>
<?  foreach ($searchfields as $searchfield) { 
      if ($row[$searchfield]) { ?>
     <tr>
       <td width="120"><?=$searchfield?></td>
           <td><?=$row[$searchfield]?></td>
       </td>
     </tr>
<? } }
  if (file_exists("exportfiles/extended/" . unescape(convertFileName($row['matchname'])). ".csv.xls"))
  {?>
      <tr>
        <td>
          Voriges Ergebnis herunter-<br />
          laden
        </td>
        <td>
          <a href="exportfiles/extended/<?=unescape(convertFileName($row['matchname']))?>.csv.xls"><?=unescape($row['matchname'])?>.csv.xls</a>
        </td>
      </tr>
      <?
  }
?>
     <tr>
       <form action="<?=$_SERVER['REQUEST_URI']?>" method="POST">
       <input type="hidden" name="module" value="<?=$module?>" />
       <input type="hidden" name="state" value="deletematches" />
       <input type="hidden" name="matchname" value="<?=unescape($row['matchname'])?>" />
       <td>&nbsp;</td>
       <td><input type="submit" name="loeschen" value="l&ouml;schen" /></td>
       </form>
     </table>
     </td>
<? 
  $i++;
  if (($i % 2) == 0)
  {
      echo "</td></tr><tr>\n";
  }

} ?>
     </tr>
   </table>
  </fieldset>
<? /*---------------------------------*/ ?>


<?
}
?>
