<?
include('../functions.php');
require_once('Mail.php');
require_once('Mail/mime.php');
require_once('Spreadsheet/Excel/Writer.php');

$sender = 'script@healthmiles.de';
$subject = 'Healthmiles: Kinder, die das fuente Lebensjahr erreichen';

$headers = array('From' => $sender,
        'Subject' => $subject,
        );

$mime = new Mail_mime("\n");
$mime->setTXTBody("Kinder, die im naechsten Monat das fuenfte Lebensjahr erreichen.\r\n");


$today = date('Y-m-d',time());
List($year,$month,$day) = explode('-',$today);
$day = 1;
$timestamp5yearsago = strtotime("5 years ago", strtotime("$year-$month-$day"));
$date5yearsago = date('Y-m-d', $timestamp5yearsago);

$month++;
if ($month > 12) {
  $month = 1;
  $year++;
}
$timestamp5yearsagoplus1month = strtotime("5 years ago", strtotime("$year-$month-$day"));
$date5yearsagoplus1month = date('Y-m-d', $timestamp5yearsagoplus1month);

$sql = "SELECT distinct(userId) AS userId 
        FROM users 
        WHERE geburtsdatum > '$date5yearsago'
        AND geburtsdatum < '$date5yearsagoplus1month'";

$result = mysql_query($sql) or error ("Cannot select from Kinder");
$anzahlgesamt = mysql_num_rows($result);

$progress = new Progress($anzahlgesamt);
$i=0;
$output = '';
$data = Array();
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
  $myrow = Array();
  $user = new user(0,$row['userId']);
  array_push($myrow, $user->versnummer);
  array_push($myrow, $user->rechtskreis);
  array_push($myrow, $user->vorname);
  array_push($myrow, $user->name);
  array_push($myrow, $user->geburtsdatum);
  array_push($data, $myrow);
  $i++;
}
$monthname = date('M',time());
$filename="/tmp/fuenfjahreskinder_$monthname.xls";
$filesuffix = 'xls';
$fields = array('Versnummer','Rechtskreis','Vorname','Nachname','Geburtsdatum');
$spreadsheet = new Excelexport($filename,$filesuffix,$fields,$data);
$spreadsheet->create();

if (!$mime->addAttachment( $filename,'application/vnd.ms-excel',"KinderUnterFuenf_$monthname.xls",true,'base64')) {
  print "Could not create attachement\n";
  exit;
}

$body = $mime->get();
$hdrs = $mime->headers($headers);
$mail = Mail::factory('mail');
print "Sending Mail...\n";
$mail->send('sabine.krause@securvita-bkk.de,securvita@frankschuessler.de',$hdrs,$body);
Print "Deleting $filename\n";
unlink($filename);

?>
