#!/usr/bin/perl
#
#  LMS version 1.10.2 Roham
#
#  Copyright (C) 2001-2007 LMS Developers
#
#  Please, see the doc/AUTHORS for more information about authors!
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License Version 2 as
#  published by the Free Software Foundation.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
#  USA.
#
#  $Id: lms-sendinvoices,v 1.34.2.1 2007/08/17 13:14:49 alec Exp $

use strict;
use DBI;
use Config::IniFiles;
use Getopt::Long;
use vars qw($configfile $help $version $quiet $fakedate);
use POSIX qw(strftime);
use LWP::UserAgent;
use MIME::Entity;
use Time::Local;
use MIME::QuotedPrint;
use Text::Iconv;

my $_version = '1.10.2 Roham';

my %options = (
	"--config-file|C=s"     =>      \$configfile,
	"--quiet|q"     	=>      \$quiet,
	"--help|h"              =>      \$help,
	"--version|v"           =>      \$version,
	"--fakedate|f=s"	=>	\$fakedate,
);

Getopt::Long::config("no_ignore_case");
GetOptions(%options);

if($help)
{
	print STDERR <<EOF;
lms-sendinvoices, version $_version
(C) 2001-2007 LMS Developers

-C, --config-file=/etc/lms/lms.ini    alternate config file 
			    (default: /etc/lms/lms.ini);
-q, --quiet		    suppress any output, except errors;
-h, --help		    print this help and exit;
-v, --version		    print version info and exit;
-f, --fakedate=YYYY/MM/DD   override system date;

EOF
	exit 0;
}							

if($version)
{
	print STDERR <<EOF;
lms-sendinvoices, version $_version
(C) 2001-2007 LMS Developers

EOF
	exit 0;
}

if(!$configfile)
{
	$configfile = "/etc/lms/lms.ini";
}

if(! -r $configfile)
{
	print STDERR "Fatal error: Unable to read configuration file $configfile, exiting.\n";
	exit 1;
}

if(!$quiet)
{
	print STDOUT "lms-sendinvoices, version $_version\n";
	print STDOUT "(C) 2001-2007 LMS Developers\n";
	print STDOUT "Using file $configfile as config.\n";
}

my $ini = new Config::IniFiles -file => $configfile;
print @Config::IniFiles::errors;

my $dbtype = $ini->val('database', 'type') || 'mysql';
my $dbhost = $ini->val('database', 'host') || 'localhost';
my $dbuser = $ini->val('database', 'user') || 'root';
my $dbpasswd = $ini->val('database', 'password') || '';
my $dbname = $ini->val('database', 'database') || 'lms';
my $dbencoding = $ini->val('database', 'server_encoding') || 'UTF-8';

my $filetype = $ini->val('invoices', 'type') || '';

my $lms_url = $ini->val('sendinvoices', 'lms_url') || 'http://localhost/lms/';
my $lms_user = $ini->val('sendinvoices', 'lms_user') || '';
my $lms_password = $ini->val('sendinvoices', 'lms_password') || '';
my $debug_email = $ini->val('sendinvoices', 'debug_email') || '';
my $sender_name = $ini->val('sendinvoices', 'sender_name') || '';
my $sender_email = $ini->val('sendinvoices', 'sender_email') || '';
my $mail_subject = $ini->val('sendinvoices', 'mail_subject') || 'Invoice No. %invoice';
my $mail_body = $ini->val('sendinvoices', 'mail_body') || 'Attached file with Invoice No. %invoice';
my $customergroups = $ini->val('sendinvoices', 'customergroups') || '';

if(!$sender_name)
{
	print STDERR "Fatal error: sender_name unset! Can't continue, exiting.\n";
	exit 1;
}

if(!$sender_email)
{
	print STDERR "Fatal error: sender_email unset! Can't continue, exiting.\n";
	exit 1;
}

my $dbase;
my $utsfmt;

if($dbtype =~ /mysql/)
{
	$dbase = DBI->connect("DBI:mysql:database=$dbname;host=$dbhost","$dbuser","$dbpasswd", { RaiseError => 1 });
	$dbase->do("SET NAMES utf8");
	$utsfmt = "UNIX_TIMESTAMP()";
}
elsif($dbtype eq "postgres")
{
	$dbase = DBI->connect("DBI:Pg:dbname=$dbname;host=$dbhost","$dbuser","$dbpasswd", { RaiseError => 1 });
	$utsfmt = "EXTRACT(EPOCH FROM CURRENT_TIMESTAMP(0))";
}
else
{
	print STDERR "Fatal error: unsupported database type: $dbtype, exiting.\n";
	exit 1;
}

# get/set invoice file type
my $dbq = $dbase->prepare("SELECT value FROM uiconfig WHERE section='invoices' AND var='type' AND disabled=0");
$dbq->execute();
if(my $row = $dbq->fetchrow_hashref())
{
	$filetype = $row->{'value'};
}

my $fencoding = 'quoted-printable';
my $ftype = 'text/html';
my $fext = 'html';

if($filetype eq 'pdf')
{
	$ftype = 'application/octetstream';
	$fencoding = '';
	$fext = 'pdf';
}

sub localtime2()
{
	if($fakedate)
	{
		my @fakedate = split(/\//, $fakedate);
		return localtime(timelocal(0,0,0,$fakedate[2],$fakedate[1]-1,$fakedate[0]));
	}
	else
	{
		return localtime();
	}
}

my $converter = Text::Iconv->new($dbencoding, "UTF-8");

$sender_name = '=?UTF-8?Q?'.encode_qp($sender_name, '').'?=';

my $month = sprintf("%d",strftime("%m",localtime2()));
my $day = strftime("%e",localtime2());
my $year = strftime("%Y",localtime2());
my $daystart = strftime("%s", 0, 0, 0, $day, $month - 1, $year - 1900);
my $dayend = strftime("%s", 59, 59, 23, $day, $month - 1, $year - 1900);

my $groupwhere = '';
my $groupjoin = '';
if($customergroups)
{
	$customergroups = "UPPER('$customergroups')";
	$customergroups =~ s/[ \t]+/\'\),UPPER\(\'/g;
	$groupwhere = " AND UPPER(customergroups.name) IN ($customergroups)";  
	$groupjoin = "LEFT JOIN customerassignments ON (documents.customerid = customerassignments.customerid) 
			LEFT JOIN customergroups ON (customerassignments.customergroupid = customergroups.id) ";
}

$dbq = $dbase->prepare("SELECT documents.id AS id, number, cdate, email, documents.name AS name, 
				documents.customerid AS customerid, template
			FROM documents 
			LEFT JOIN customers ON customers.id = documents.customerid 
			LEFT JOIN numberplans ON numberplanid = numberplans.id
			$groupjoin
			WHERE deleted = 0 AND type = 1 AND email != '' 
				AND cdate >= $daystart AND cdate <= $dayend
				$groupwhere");
$dbq->execute();
while(my $row = $dbq->fetchrow_hashref())
{
	my $ua = LWP::UserAgent->new;
	$ua->timeout(240);
	my $response = $ua->get($lms_url.'/?m=invoice&fetchsingle=1&override=1&id='.$row->{'id'}.'&loginform[login]='.$lms_user.'&loginform[pwd]='.$lms_password);
	if ($response->is_success)
	{
		my $custemail = $debug_email || $row->{'email'};
		my $invoice_number = $row->{'template'} || '%N/LMS/%Y';
		my $body = $mail_body;
		my $subject = $mail_subject;
		
		$invoice_number =~ s/%(\d*)N/sprintf"%0${1}d",$row->{'number'}/e;
		$invoice_number = strftime($invoice_number, localtime($row->{'cdate'}));
		$body =~ s/%invoice/$invoice_number/g;
		$subject =~ s/%invoice/$invoice_number/g;
		
		if(!$quiet)
		{
			print "Invoice No. $invoice_number for $row->{'name'} <$custemail>\n";
		}

		my $mail = build MIME::Entity Type=>"multipart/mixed";
		$mail->head->add('To', '"=?UTF-8?Q?'.encode_qp($converter->convert($row->{'name'}), '').'?="'.' <'.$custemail.'>');
		$mail->head->add('From', '"'.$sender_name.'"'.' <'.$sender_email.'>');
		$mail->head->add('Reply-To', '"'.$sender_name.'"'.' <'.$sender_email.'>');
		$mail->head->add('Subject', '=?UTF-8?Q?'.encode_qp($subject, '').'?=');
		$mail->head->add('Message-ID', '<lms.sendinvoice.'.$row->{'id'}.'.'.$row->{'customerid'}.'@lms>');
		$mail->head->add('Return-path', '<'.$sender_email.'>');
		$mail->attach(
			Type => 'text/plain',
			Charset => 'UTF-8',
			Encoding => 'quoted-printable',
			Data => [ "$body\n" ],
		);
		$mail->attach(
			Type => $ftype,
			Charset => 'UTF-8',
			Encoding => $fencoding,
			Filename => 'invoice_'.$row->{'id'}.'.'.$fext,
			Data => [ $response->content ],
		);
		$mail->smtpsend('MailFrom' => $sender_email, 'To' => $custemail, 'Return-path' => $sender_email);
		
	}
}

$dbq->finish();
$dbase->disconnect();
