#!/usr/bin/php
<?php   
/*----------------------------------------------------------------------------*/
// Copyright (C) 2009  Paul Yasi (citrusdb.org)
// This script will send einvoices to customers who have the einvoice
// as their chosen billing type on the current date.  It is set to
// only send to those in the first organization specified.  If you have multiple
// brand organizations in your configuration you will need to duplicate this
// script and set the organization_id variable for those also.
//
// This script should be copied to your citrusdb root folder and put into the cron to be run nightly
//
/*----------------------------------------------------------------------------*/

// Includes
include('./include/config.inc.php');
include('./include/database.inc.php');
include("$lang");
include('./include/billing.inc.php');
include('./include/citrus_base.php');
include('./include/support.inc.php');

// set the billing date to today
$billingdate = date("Y-m-d");

$organization_id = 1;

/*--------------------------------------------------------------------*/
// Create the billing data
/*--------------------------------------------------------------------*/
	
// determine the next available batch number
$batchid = get_nextbatchnumber($DB);
echo "BATCH: $batchid<p>\n";

// query for taxed services that are billed on the specified date
// and for a specific organization


$numtaxes = add_taxdetails($DB, $billingdate, NULL, 'einvoice', $batchid, $organization_id);
$numservices = add_servicedetails($DB, $billingdate, NULL,'einvoice', $batchid, $organization_id);

echo "taxes: $numtaxes, services: $numservices<p>";

// create billinghistory
$user = "autoeinvoice";
create_billinghistory($DB, $batchid, 'einvoice', $user);	

/*-------------------------------------------------------------------*/	
// Email the invoice
/*-------------------------------------------------------------------*/

// query the batch for the invoices to do
$query = "SELECT DISTINCT d.invoice_number, b.contact_email, b.id, b.account_number  
	FROM billing_details d 
	LEFT JOIN billing b ON b.id = d.billing_id
	WHERE d.batch = '$batchid'";
$DB->SetFetchMode(ADODB_FETCH_ASSOC);
$result = $DB->Execute($query)
  or die ("$l_queryfailed");

while ($myresult = $result->FetchRow()) {
  // get the invoice data to process now
  $invoice_number = $myresult['invoice_number'];
  $contact_email = $myresult['contact_email'];
  $invoice_account_number = $myresult['account_number'];
  $invoice_billing_id = $myresult['id'];

	emailinvoice($invoice_number,$contact_email,$invoice_billing_id);

 }

?>
