<?php
  include('../functions.php');
  include('../login.php'); // Only for using central script to securely get parameter $startdate
  // FIXME: Do we ned check login also?
  
  /*

- Automatisiert aufrufen
  - crontab -e
  - http://preview.healthmiles.de/admin/include/tests/myexp.php

  */

set_time_limit (600); // darf ich das?

  $exportroot = "./teilnehmer4kasse";

  $healthmiles = new healthmiles();

  // $healthmiles->getNewUsers([$starttimestamp][, $endtimestamp]);
  
  // Parameter $startdate == "auto" holt das Datum des letzten exports aus userlog
  if (! isset($startdate)) {
    // getNewUsers() automatically gets new users from start last day til end last day!
    $userids = $healthmiles->getNewUsers();
    print "No Parameter given: Export from start last day till end last day!<br />\n";
  }
  else if ($startdate == "auto") {
    $row = '';
    $query = "SELECT * FROM userlogs WHERE aktion='Teilnehmer Kassenexport' ORDER BY timestamp DESC";
    $result = dbQuery($query)
      or error ("Konnte log nicht aus der Datenbank lesen: " . dbError());
    $row = dbFetchRow($result);
    dbFreeResult($result);
    if ($row) {
      $userids = $healthmiles->getNewUsers($row['timestamp']);
      print "Export from ".$row['timestamp']." to now.<br />\n";
    }
    else {
      // Erster Aufruf mit Parameter "auto" -> alle exportieren
      $starttimestamp = strtotime("1990-01-01 00:00:00", time());
      $userids = $healthmiles->getNewUsers($starttimestamp);
      print "No last export found in DB: Export from 1990 to now.<br />\n";
    }
  }
  else {
    // $starttimestamp = strtotime("2011-01-01 00:00:00", time());
    $starttimestamp = strtotime($startdate, time());
    // getNewUsers($startime) automatically gets new users from starttimestamp til now!
    $userids = $healthmiles->getNewUsers($starttimestamp);
    print "Date as Parameter: Export from ".$startdate." to now.<br />\n";
  }


  // IF AT ALL USERIDS...

  if (count($userids) > 0) {
  
    // if not exist create dir "teilnehmer4kasse"
    if (!is_dir($exportroot)) {
      $oldumask = umask(0);
      if (!mkdir($exportroot, 0775)) {
        umask($oldumask);
        die('Erstellung des Verzeichnisses '.$exportroot.' schlug fehl!');
      }
      umask($oldumask);
    }
  
    // in that create dir "date time, seconds"
    $exportdirname = date("Ymd-His");
    if (!is_dir($exportroot."/".$exportdirname)) {
      $oldumask = umask(0);
      if (!mkdir($exportroot."/".$exportdirname, 0775)) {
        umask($oldumask);
        die('Erstellung des Verzeichnisses '.$exportroot."/".$exportdirname.' schlug fehl!');
      }
      umask($oldumask);
    }

    /* populate array with data first and not write 4 test
    
    $exportdata = array();  
    foreach ($userids as $userid) {
      $myUser = new user(0,$userid);
      $exportfilename = $exportroot."/".$exportdirname."/";
      if ($myUser->rechtskreis == "West") $exportfilename .= "20_";
      elseif ($myUser->rechtskreis == "Ost") $exportfilename .= "70_";
      else $exportfilename .= "NA_";
      $exportfilename .= $myUser->versnummer;
      $exportfilename .= "_healthmiles.xml";
      $xml = $myUser->toXML();

      $actudata=array();
      $actudata['filename'] = $exportfilename;
      $actudata['xml'] = $xml;
      $exportdata[] = $actudata;
      
    } */

    $exportfilenames = array();  
    foreach ($userids as $userid) {
      $myUser = new user(0,$userid);
      $exportfilename = $exportroot."/".$exportdirname."/";
  
      if ($myUser->rechtskreis == "West") $exportfilename .= "20_";
      elseif ($myUser->rechtskreis == "Ost") $exportfilename .= "70_";
      else $exportfilename .= "NA_";
      $exportfilename .= $myUser->versnummer;
      $exportfilename .= "_healthmiles.xml";
      
      $xml = $myUser->toXML();
      
      if ($exportfilehandle=fopen($exportfilename,"w")) {
        fwrite ($exportfilehandle, $xml);
        fclose ($exportfilehandle);
        $exportfilenames[] = $exportfilename;
        print "Written ".$exportfilename."<br />\n";
      }
      else {
        print "Writing of ".$exportfilename." FAILED!<br />\n";
      }
    }

    
    if ($startdate == "auto") {
      $logUser = new user(0,$userids[0]);
      $logUser->log('Teilnehmer Kassenexport', $logUser->userId);
      print "<br />Parameter was auto, export is logged in table userlogs.<br />";
    }
    else {
    print "<br />Parameter was not auto, export is not noted in table userlogs.<br />";
    }

    // packen ueber system -> verschluesselt
    echo system('/home/pages/healthmiles.de/bin/zip -e -q -j -P secviexp4crmkv -r '.$exportroot.'/TeilnehmerExport-'.$exportdirname.' '.$exportroot.'/'.$exportdirname);
    print "<br />Moved results to enrypted archive TeilnehmerExport-".$exportdirname.".zip <br />";

    // Temp-Dateien loeschen
    rrmdir ($exportroot.'/'.$exportdirname);
    print "<br />Deleted temporary files.<br />";

    /* vermailen
    $empfaenger = "carsten@germer.org"; // Empfänger E-Mail Adresse
    $betreff = "Export der Teilnehmer für die Kasse vom ".date("d.m.Y"); // Betreff
    $dateiname = $filename;
    $dateiname_mail = $exportdirname."_TeilnehmerKassenExport.zip";
    $id = md5(uniqid(time()));
    $dateiinhalt = fread(fopen($dateiname, "r"), filesize($dateiname));
     // Absender Name und E-Mail Adresse
    $kopf = "From: noreply@healthmiles.de\n";
    $kopf .= "MIME-Version: 1.0\n";
    $kopf .= "Content-Type: multipart/mixed; boundary=$id\n\n";
    $kopf .= "This is a multi-part message in MIME format\n";
    $kopf .= "--$id\n";
    $kopf .= "Content-Type: text/plain\n";
    $kopf .= "Content-Transfer-Encoding: 8bit\n\n";
    $kopf .= "E-Mail mit Anhang des aktuellen Exports.\n"; // Inhalt der E-Mail (Body)
    $kopf .= "\n--$id";
    // Content-Type: image/gif, image/jpeg, image/png » MIME-Typen - selfHtml.org
    $kopf .= "\nContent-Type: image/gif; name=$dateiname_mail\n";
    $kopf .= "Content-Transfer-Encoding: base64\n";
    $kopf .= "Content-Disposition: attachment; filename=$dateiname_mail\n\n";
    $kopf .= chunk_split(base64_encode($dateiinhalt));
    $kopf .= "\n--$id--";
    mail($empfaenger, $betreff, "", $kopf); // E-Mail versenden
    */
  }

  else {
    print "no IDs to export<br />\n";
  }

  function rrmdir($dir) {
    if (is_dir($dir)) {
      $objects = scandir($dir);
      foreach ($objects as $object) {
        if ($object != "." && $object != "..") {
          if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
        }
      }
      reset($objects);
      rmdir($dir);
    }
  }
  
?>
