#!/usr/bin/perl

BEGIN { use lib '/usr/home/cfg' ; require push_inc ; }

use CGI::Carp qw(fatalsToBrowser);
use Date::Calc qw(:all);
use DBI;

 # /usr/lib/cgi-bin/aisa/scripts/cron/remove_expired_sessions_mysql.pl 1
 
#-------------------------------------------------------------------------------

our $debug    = $ARGV[0] ;
our $username = 'rory' ;

#------------------------------------------------------------------------------------------

&today ;
&set_delete_date ;

&db_open_upd ;
	our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it
	&delete_sessions ;
	&set_expired_event_quotes_status ;
	$db_ignore_open_close = 0 ;
&db_close_conn ;

print "Done." if $debug ;

exit;

#------------------------------------------------------------------------------------------

sub delete_sessions {

	my $sql = qq(SELECT * FROM `sessions`) ;

	&common_debug($sql) ;

	my $sth = $dbh->prepare($sql) ;

	$sth -> execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!";
	$id_array_ref = $sth->fetchall_arrayref();
	$sth->finish();


	foreach my $row (@$id_array_ref) {
		my $id         = @$row[0] ;
		my $a_session  = @$row[1] ;
		my @a_session = split(/\,/,$a_session) ;
		foreach (@a_session) {
			my ($param,$val) = split(/=>/) ;
			if ($param =~ /timestamp/) {
				my $date_ccyy_mm_dd = substr($val,2,10);
				my ($sccyy,$smm,$sdd) = split(/\-/,$date_ccyy_mm_dd);
				my $sdate = $sccyy . $smm . $sdd ;
				if ($sdate < $delete_date) {
					# print "<br>($sdate < $delete_date)" ;
					# &common_debug("$param,$val [$sdate < $delete_date] [$id]") ;
					&delete_session($id) ;
				}
			}
		}
	}

} #-------------------------------------------------------------------------------

sub set_expired_event_quotes_status {

	%i = () ; 
	$i{quote_completed} = 1 ; 
	&db_min_upd('event_quotes',"date_to < '$now_year-$now_mm-$now_dd 00:00:00' AND quote_to <> '5' AND quote_completed = '0' AND quote_accepted = '1'") ; # Everyone except SuperSport Schools 
	
	%i = () ; 
	$i{quote_rejected} = 1 ; 
	&db_min_upd('event_quotes',"date_to < '$now_year-$now_mm-$now_dd 00:00:00' AND quote_to <> '5' AND quote_completed = '0' AND quote_accepted = '0' AND quote_pending = '1'") ; # Everyone except SuperSport Schools 

} #-------------------------------------------------------------------------------

sub set_delete_date {

	my ($ayear,$amonth,$aday) = Add_Delta_Days($now_year,$now_mm,$now_dd,-2) ;

	$amonth      = sprintf("%02s", $amonth) ;
	$aday        = sprintf("%02s", $aday) ;

	$delete_date = $ayear . $amonth . $aday ;

} #-------------------------------------------------------------------------------

sub delete_session {

	my ($id) = @_ ;
	
	&db_min_delete('sessions',"id='$id'") ;

} #------------------------------------------------------------------------------------------

use db ;
use today ;
use common ;
use common_min ;
