<?php
include('../functions.php');
$year = date('Y');
$month = date('m');
$day = date('d');
print "$year-$month-$day\n";

$ts18 = strtotime('+18 years ago', time());
$date18 = date("Y-m-d",$ts18) . "\n";

$query = "SELECT * FROM users WHERE geburtsdatum > '$date18'";
$result = dbQuery($query);
$num = dbNumRows($result);
print "Checking $num children\n";
$progress = new Progress($num);
$found = 0;
$orphans = 0;
$i=0;
while($row = dbFetchRow($result,MYSQL_ASSOC)) {
    $userId = $row['userId'];
    $name = $row['name'];
    $vorname = $row['vorname'];
    $strasse = $row['strasse'];
    $versnummer = $row['versnummer'];
    $rechtskreis = $row['rechtskreis'];
    $ort = $row['ort'];
    $geburtsdatum = $row['geburtsdatum'];
    $subquery = "SELECT * FROM familienversicherte WHERE userId = $userId";
    $subresult = dbQuery($subquery);
    $famiIds = array();
    if (dbNumRows($subresult) > 0) {
        while( $subrow = dbFetchRow($subresult, MYSQL_ASSOC)) {
            array_push($famiIds, $subrow['parentId']);
        }
    }
    # Find Parents
    $subquery = "SELECT * FROM users 
        WHERE 
            name = '" . escape($name) . "'
        AND strasse = '" . escape($strasse) . "'
        AND ort = '" . escape($ort) . "'
        AND userId != $userId
        AND geburtsdatum < '$date18'";

    $subresult = dbQuery($subquery) or die("Cannot perform query '$subquery'\n"); 
    $kidshown = 0;
    if (dbNumRows($subresult) > 0) {
        while ($subrow = dbFetchRow($subresult,MYSQL_ASSOC)) {
            $parentId = $subrow['userId'];
            if (! in_array($parentId,$famiIds)) {
                if (!$kidshown) {
#                    print "Kind: $vorname $name $strasse $ort $geburtsdatum\n";
                    $kidshown = 1;
                }
                $parentvorname = $subrow['vorname'];
                $parentname = $subrow['name'];
                $parentgeburtsdatum = $subrow['geburtsdatum'];
#                print "$parentvorname $parentname $strasse $ort $parentgeburtsdatum\n";
                $fami = new familienversicherte();
                $fami->parentId = $parentId;
                $fami->versnummer = $versnummer;
                $fami->rechtskreis = $rechtskreis;
                $fami->typ = 1;
                if (!$fami->insert()) {
#                   print "Already inserted\n";
                }
                $found++;
            } else {
#                print "Parent found!\n";
            }

        } 
    } else {
      $orphans++;
    }
    $i++;
    $progress->show($i);
}
print "Parents found: $found\n";
print "Waisen: $orphans\n";
