<?php
/**
 * AgileBill - Open Billing Software
 *
 * This body of work is free software; you can redistribute it and/or
 * modify it under the terms of the Open AgileBill License
 * License as published at http://www.agileco.com/agilebill/license1-4.txt
 *
 * Originally authored by Tony Landis, AgileBill LLC
 *
 * Recent modifications by Deon George
 *
 * @author Deon George <deonATleenooksDOTnet>
 * @copyright 2009 Deon George
 * @link http://osb.leenooks.net
 *
 * @link http://www.agileco.com/
 * @copyright 2004-2008 Agileco, LLC.
 * @license http://www.agileco.com/agilebill/license1-4.txt
 * @author Tony Landis <tony@agileco.com>
 * @package AgileBill
 * @subpackage Module:Campaign
 */

/**
 * The main AgileBill Campaign Class
 *
 * @package AgileBill
 * @subpackage Module:Campaign
 */

ob_start();

# Required includes:
require_once('../../config.inc.php');
require_once(PATH_ADODB.'adodb.inc.php');
require_once(PATH_CORE.'database.inc.php');
require_once(PATH_CORE.'vars.inc.php');

$C_debug = new CORE_debugger;
$C_vars = new CORE_vars;
$VAR = $C_vars->f;

if (! isset($VAR['id']))
	exit;

$db = &DB();
$result = $db->Execute(sqlSelect($db,'campaign','*',array('id'=>$VAR['id'])));

if (! $result || ! $result->RecordCount())
	exit;

if ($VAR['file']) {
	$file_no = $VAR['file'];

} else {
	# Random file:
	$last = $result->fields['last_served'];
	if (empty($last))
		$last = 1;

	$next = false;

	for ($i=1; $i<=12; $i++) {
		if (! empty($result->fields['file'.$i]) && ! $next) {
			if ($i == $last)
				$next = true;
		} elseif (! empty($result->fields['file'.$i]) && $next) {
			$file_no = $i;
			$i = 20;
		}
	}
}

if (empty($file_no))
	$file_no = '1';

$file = sprintf(PATH_FILES.'campaign_%s_%s.dat',$VAR['id'],$file_no);
$type = 'type'.$file_no;
$name = 'file'.$file_no;
$count_field= 'served'.$file_no;
$count = $result->fields[$count_field]+1;

# Open the file
if ($fh=fopen($file,'r')) {
	# Display the correct headers:
	header('Content-type: '.$result->fields[$type]);
	header('Content-Disposition: inline; filename='.$result->fields[$name]);
	header('Content-Description: PHP/INTERBASE Generated Data');
	fpassthru($fh);

	# Increment the file
	if (! isset($VAR['_log']))
		$result = $db->Execute(sqlUpdate($db,'campaign',array('last_served'=>$file_no,$count_field=>$count),array('id'=>$VAR['id'])));

	exit;
}

echo _('Sorry, the campaign or required file does not exist!');

ob_end_flush();
?>