#!/usr/bin/perl -Tw
#
# LMS version 1.2-cvs
#
#  (C) 2001-2004 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-payments,v 1.20.2.1 2004/02/18 12:47:17 lukasz Exp $

use strict;
use DBI;
use Config::IniFiles;
use Getopt::Long;
use vars qw($configfile $quiet $help $version);
use POSIX qw(strftime);
use POSIX qw(mktime);

my $_version = '1.2-cvs';

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

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

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

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

EOF
	exit 0;
}

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

EOF
	exit 0;
}

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

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

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

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

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 $payday = sprintf("%d",strftime("%e",localtime()));

my $dbase;
my $utsfmt;

if($dbtype eq "mysql")
{
	$dbase = DBI->connect("DBI:mysql:database=$dbname;host=$dbhost","$dbuser","$dbpasswd", { RaiseError => 1 });
	$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;
}

my $month = sprintf("%d",strftime("%m",localtime()));
my $day = strftime("%e",localtime());
my $year = strftime("%Y",localtime());
my $weekday = strftime("%u",localtime());
my $yearday = strftime("%j",localtime());
my $quarter;
if($month==1 || $month==4 || $month==7 || $month==10) {
	$quarter = $day;
} elsif ($month==2 || $month==5 || $month==8 || $month==11) {
	$quarter = $day + 100;
} else {
	$quarter = $day + 200;
}
my %txts;

$txts{0} = "Abonament tygodniowy \"%\" (za okres ".strftime("%Y/%m/%d", 0, 0, 12, $day, $month - 1, $year - 1900)." - ".strftime("%Y/%m/%d", 0, 0, 12, $day + 7, $month - 1, $year - 1900).")";
$txts{1} = "Abonament miesiczny \"%\" (za okres ".strftime("%Y/%m/%d", 0, 0, 12, $day, $month - 1, $year - 1900)." - ".strftime("%Y/%m/%d", 0, 0, 12, $day - 1, $month, $year - 1900).")";
$txts{2} = "Abonament kwartalny \"%\" (za okres ".strftime("%Y/%m/%d", 0, 0, 12, $day, $month - 1, $year - 1900)." - ".strftime("%Y/%m/%d", 0, 0, 12, $day - 1, $month + 2, $year - 1900).")";
$txts{3} = "Abonament roczny \"%\" (za okres ".strftime("%Y/%m/%d", 0, 0, 12, $day, $month - 1, $year - 1900)." - ".strftime("%Y/%m/%d", 0, 0, 12, $day - 1, $month - 1, $year - 1900 + 1).")";

my $yearstart = strftime("%s", 0, 0, 0, 1, 0, $year - 1900);
my $yearend = strftime("%s", 59, 59, 23, 31, 11, $year - 1900);

my $dbq = $dbase->prepare("SELECT MAX(number) AS number FROM invoices WHERE cdate >= $yearstart AND cdate <= $yearend");
$dbq->execute();
my $row = $dbq->fetchrow_hashref();
my $number = $row->{'number'} || 0;
my %gotinv;
my $time = strftime("%s",localtime());
my $icdbq;

# dobra, query wybiera *WSZYSTKIE* moliwe assigmenty na dany dzie.

$dbq = $dbase->prepare("SELECT assignments.id AS id, tariffid, userid, period, at, value, taxvalue, pkwiu, uprate, downrate, tariffs.name AS name, invoice FROM assignments, tariffs, users WHERE tariffs.id = tariffid AND userid = users.id AND status = 3 AND deleted = 0 AND ((period = 0 AND at = $weekday) OR (period = 1 AND at = $day) OR (period = 2 AND at = $quarter) OR (period = 3 AND at = $yearday))");
$dbq->execute();

print "UID:\tKwota:\tZa:\n";

while(my $assign = $dbq->fetchrow_hashref())
{
	my $uid = $assign->{'userid'};
	my $txt = $txts{$assign->{'period'}};
	$txt =~ s/\%/$assign->{'name'}/g;
	$gotinv{$uid} = 0 if not defined $gotinv{$uid};
	if($assign->{'value'})
	{
		if($assign->{'invoice'})
		{
			if($gotinv{$uid} eq 0)
			{
				$number++;
				my $udbq = $dbase->prepare("SELECT * FROM users WHERE id=$uid");
				$udbq->execute();
				my $urow = $udbq->fetchrow_hashref();
				my $idbq = $dbase->prepare("INSERT INTO invoices (number, customerid, name, address, zip, city, phone, nip, pesel, cdate, paytime, paytype, finished) VALUES ($number, $uid, '$urow->{'lastname'} $urow->{'name'}', '$urow->{'address'}', '$urow->{'zip'}', '$urow->{'city'}', '$urow->{'phone1'}', '$urow->{'nip'}', '$urow->{'pesel'}', $time, 14, 'PRZELEW', 1)");
				$idbq->execute();
				$idbq = $dbase->prepare("SELECT id FROM invoices WHERE number=$number AND cdate=$time AND finished=1 AND customerid=$uid");
				$idbq->execute();
				my $irow = $idbq->fetchrow_hashref();
				$gotinv{$uid} = $irow->{'id'};
			}
			
			my $icdbq = $dbase->prepare("SELECT * FROM invoicecontents WHERE tariffid=$assign->{'tariffid'} AND invoiceid=$gotinv{$uid} AND description='$txt'");
			$icdbq->execute();
			if(my $icrow = $icdbq->fetchrow_hashref())
			{
				$icdbq = $dbase->prepare("UPDATE invoicecontents SET count=count+1 WHERE tariffid=$assign->{'tariffid'} AND invoiceid=$gotinv{$uid} AND description='$txt'");
				$icdbq->execute();
			}
			else
			{
				$icdbq = $dbase->prepare("INSERT INTO invoicecontents (invoiceid, value, taxvalue, pkwiu, content, count, description, tariffid) VALUES ($gotinv{$uid}, $assign->{'value'}, $assign->{'taxvalue'}, '$assign->{'pkwiu'}', 'szt', 1, '$txt', $assign->{'tariffid'})");
				$icdbq->execute();
			}
		}
		my $sdbq = $dbase->prepare("INSERT INTO cash (time, adminid, type, value, userid, comment, invoiceid) VALUES ($time, 0, 4, $assign->{'value'}, $uid, '$txt', $gotinv{$uid})");
		$sdbq->execute();
		print "$uid\t$assign->{'value'}\t$txt\n";
	}
}	

# opaty stae
$dbq = $dbase->prepare("SELECT * FROM payments WHERE value <> 0 AND ((period = 0 AND at=$weekday) OR (period = 1 AND at=$day) OR (period = 2 AND at = $quarter) OR (period = 3 AND at = $yearday))");
$dbq->execute();

while(my $assign = $dbq->fetchrow_hashref())
{
	my $sdbq = $dbase->prepare("INSERT INTO cash (time, adminid, type, value, userid, comment, invoiceid) VALUES ($time, 0, 2, $assign->{'value'}, 0, '$assign->{'name'}/$assign->{'creditor'}', 0)");
	$sdbq->execute();
	print "0\t$assign->{'value'}\t$assign->{'name'}/$assign->{'creditor'}\n";
}

$dbq = $dbase->prepare("DELETE FROM timestamps WHERE tablename = 'cash' OR tablename = '_global'");
$dbq->execute();
$dbq = $dbase->prepare("INSERT INTO timestamps (tablename,time) VALUES ('cash',$utsfmt)");
$dbq->execute();
$dbq = $dbase->prepare("INSERT INTO timestamps (tablename,time) VALUES ('_global',$utsfmt)");
$dbq->execute();
$dbase->disconnect();
