<?php

include('../include/functions.php');

if (!isset($_SERVER['PHP_AUTH_USER'])) {
    authenticate();
}

$user = $_SERVER['PHP_AUTH_USER'];
$password = $_SERVER['PHP_AUTH_PW'];

function authenticate() {
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Kein Zugriff.';
    exit;
}
if (! ($user = 'kontoauszug' && $password == 'az74Of;')) {
    authenticate();
}

if (!isset($_REQUEST['startdatum']) or !isset($_REQUEST['enddatum'])) {
?>
<html>
<body>
    Bitte geben Start- und Enddatum in der URL an.<br>
    Beispiel: <a href="https://<?php echo $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ?>?startdatum=2012-01-01&enddatum=2012-12-31">https://<?php echo $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ?>?startdatum=2012-01-01&enddatum=2012-12-31</a><br/>
</body>
</html>
<?php
    exit;
}

$startdatum = $_REQUEST['startdatum'];
$enddatum = $_REQUEST['enddatum'];

header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="healthmiles_kontoauszuege_'.$startdatum . '-' . $enddatum . '.csv');

list($startyear, $startmonth, $startday) = explode('-',$startdatum);
list($endyear, $endmonth, $endday) = explode('-',$enddatum);

$delimiter = ";";

$startdatum = mktime(0,0,0,$startmonth,$startday,$startyear);
$enddatum = mktime(0,0,0,$endmonth,$endday,$endyear);

$result = getKontobewegungen($startdatum, $enddatum);
$firstrow = true;
while ($row = dbFetchRow($result, MYSQL_ASSOC))
{
    if ($firstrow)  {
        foreach (array_keys($row) as $key) {
            if ($key == 'pkey') $key = 'buchungsid';
            if ($key == 'datum') $key = 'buchungsdatum';
            if ($key == 'passwort') continue;
            print $key . $delimiter;
        }
        print "\n";
        $firstrow = false;
    }
    $firstcol = true;
    foreach (array_keys($row) as $key) {
        if ($key == 'passwort') continue;
        if (!$firstcol) {
            print $delimiter;
        } else {
            $firstcol = false;
        }
        $value = $row[$key];
        $value =str_replace('"','""',
            str_replace("\n",' ',
                    str_replace("\r",' ',$value)
                    )
                );
        if ($key == 'datum') $value = date('Y-m-d', $row[$key]);
        if ($key == 'erstellungsdatum') $value = date('Y-m-d', $row[$key]);
        if ($key == 'aenderungsdatum') $value = date('Y-m-d', $row[$key]);
        print '"' . $value . '"';
    }
    print "\n";
}


function getKontobewegungen($startdatum , $enddatum)
{    
    $users = array();

    $query = "SELECT *
        FROM users, kontobewegungen
        WHERE users.userId = kontobewegungen.userId
        AND datum >= $startdatum
        AND datum < $enddatum
        AND geburtsdatum > '1900-01-01'
        AND wert != 0
        ORDER BY datum ASC
        ";
    $result = dbQuery($query)
        or die (dbError());

    return $result;
    return $kontobewegungen;
}
