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

  $query = "SELECT kontobewegungen.pkey AS pkey, beschreibung 
  FROM kontobewegungen, users
  WHERE kontobewegungen.userId = users.userId
  AND wert < 0
  AND beschreibung LIKE 'Bestellung der Prämie%'";

  $result = mysql_query(utf8_decode($query));
  if (mysql_num_rows($result) <= 1) {
    print "Fehler: Keine Praemienbestellungen gefunden: $query\n";
  }
  
  while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $kontoid = $row['pkey'];
    $beschreibung = $row['beschreibung'];
    $match = preg_match(utf8_decode("/.*der Prämie:\s?(.*)$/"), $beschreibung , $matches);
    if (!$match) {
        $match = preg_match(utf8_decode("/.*der Prämie\s?(.*)$/"), $beschreibung , $matches);
        if (!$match) {
#            print $row['pkey'] . ", " . utf8_encode($row['beschreibung']) . "\n";
        }
    }
    if ($match) {
      $praemienname = $matches[1];
      $subquery = "SELECT * FROM praemien
                   WHERE name LIKE '$praemienname'";
      $subresult = mysql_query($subquery);
      if (mysql_num_rows($subresult) <= 0) {
#        print "Praemie '$praemienname' nicht gefunden\n";
      } else {
        $row = mysql_fetch_array($subresult, MYSQL_ASSOC);
        $praemienId = $row['id'];
        print "$praemienId: " . $row['name'] . "\n";
        
        $updatequery = "UPDATE kontobewegungen SET praemienid = '$praemienId' WHERE pkey = '$kontoid'";
        mysql_query($updatequery) or error(mysql_error());
      }
    }
  }
  
?>
