";
      }
    }
    // Connect to database
    mysql_connect($opts['hn'], $opts['un'], $opts['pw']);
    mysql_select_db($opts['db']);
    // Get all subscriptions
    $qry = "SELECT * FROM ".$opts['tb']." LEFT JOIN ".$opts['sv']." ";
    $qry .= "ON ".$opts['tb'].".serviceid = ".$opts['sv'].".serviceid WHERE servicename='$callchargetext'";
    $result = mysql_query($qry) or die("A fatal MySQL error occured.\n
Query: " . $qry . "
\nError: (" . mysql_errno() . ") " . mysql_error());
    // Loop through them
    while ($subscription = mysql_fetch_array($result)) {
      // Process the subscription
      $subid = $subscription['subscriptionid'];
      $custid = $subscription['customerid'];
      $description = $subscription['servicename']." ".$subscription['description'];
      $today = date("Y-m-d");
      $updated = false;
      $callcharges = $cdr[$subscription['description']];
      if($callcharges != 0) { 
        // Store the accumulated records in a related subscription
       $ins = "INSERT INTO ".$opts['in']." (customerid, subscriptionid, description, invoicelinedate, amount, charge) ";
        $ins .= "VALUES ($custid, $subid, '$description', NOW(), 1, $callcharges)";
        $insres = mysql_query($ins) or die("A fatal MySQL error occured.\n
Query: " . $ins . "
\nError: (" . mysql_errno() . ") " . mysql_error());
        $upd = "UPDATE ".$opts['tb']." SET lastinvoiced=NOW() WHERE subscriptionid=$subid";
        $updres = mysql_query($upd) or die("A fatal MySQL error occured.\n
Query: " . $upd . "
\nError: (" . mysql_errno() . ") " . mysql_error());
        echo "Invoiced $description $callcharges
";
        $totalcharged += $callcharges;
      }
      // Unset the stored data so we can check what might be left behind in the end
      unset($cdr[$subscription['description']]); 
    }
    echo "Total call charges invoiced: $callcharges
";
    if(count($cdr) > 0) {
      // Warning that not all acounts have been invoiced
      echo "Warning: Remaining records:
";
      foreach($cdr as $account => $value) echo "Account $account has not been invoiced (missed $value)
";
      echo "";
    }
    // Everything went OK, no need to show the form again.
    $showform = false;
  } else {
    echo "File upload failed (".$file['error'].")";
  }
}
if($showform) {
?>
Upload a Comma Separated CDR file. The CDR file is processed with these fields:
cid,time,from,to,account,duration,costs,destination
Account is matched to the description field of a subscription 'Call charges'
}
?>