#!/usr/bin/perl

# Copyright 2011 Koustubha Kale, Anant Corporation, Thane, India
#
# This file is part of Koha.
#
# Koha is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# Koha 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 Koha; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

=head1 NAME

advance_notices.pl - cron script to put item due reminders into message queue

=head1 SYNOPSIS

./warn_account_expiry.pl -c

or, in crontab:
0 1 * * * warn_account_expiry.pl -c

=head1 DESCRIPTION

This script prepares account expiry reminders to be sent to
patrons. It queues them in the message queue, which is processed by
the process_message_queue.pl cronjob. 

=cut

use strict;
use warnings;
use Getopt::Long;
use Data::Dumper;
BEGIN {
    # find Koha's Perl modules
    # test carefully before changing this
    use FindBin;
    eval { require "$FindBin::Bin/../kohalib.pl" };
}
use C4::Context;
use C4::Letters;
use C4::Members;
use C4::Members::Messaging;
use C4::Dates qw/format_date/;


# These are defaults for command line options.
my $confirm;                                                        # -c: Confirm that the user has read and configured this script.
# my $confirm     = 1;                                                # -c: Confirm that the user has read and configured this script.
my $nomail;                                                         # -n: No mail. Will not send any emails.
my $mindays     = 0;                                                # -m: Maximum number of days in advance to send notices
my $maxdays     = 30;                                               # -e: the End of the time period
my $fromaddress = C4::Context->preference('KohaAdminEmailAddress'); # -f: From address for the emails
my $verbose     = 0;                                                # -v: verbose

GetOptions( 'c'              => \$confirm,
            'n'              => \$nomail,
            'm:i'            => \$maxdays,
            'f:s'            => \$fromaddress,
            'v'              => \$verbose,
       );
my $usage = << 'ENDUSAGE';

This script prepares account expiry reminders to be sent to
patrons. It queues them in the message queue, which is processed by
the process_message_queue.pl cronjob.
It needs a notice to be created with code EXP. It can handle  
borrowers.borrowernumber, borrowers.title, borrowers.firstname, 
borrowers.surname, borrowers.dateexpiry fields in the notice.
See the comments in the script for directions on changing the script.
This script has the following parameters :
	-c Confirm and remove this help & warning
        -m maximum number of days in advance to send advance notices.
        -f from address for the emails. Defaults to KohaAdminEmailAddress system preference
	-n send No mail. Instead, all mail messages are printed on screen. Usefull for testing purposes.
        -v verbose
ENDUSAGE

##TODO  create syspref for sending these reminders, and setting the days in advance.
# Since advance notice options are not visible in the web-interface
# unless EnhancedMessagingPreferences is on, let the user know that
# this script probably isn't going to do much
##if ( ! C4::Context->preference('EnhancedMessagingPreferences') ) {
##    warn <<'END_WARN';
##
##The "EnhancedMessagingPreferences" syspref is off.
##Therefore, it is unlikely that this script will actually produce any messages to be sent.
##To change this, edit the "EnhancedMessagingPreferences" syspref.
##
##END_WARN
##}

unless ($confirm) {
    print $usage;
    print "Do you wish to continue? (y/n)";
    chomp($_ = <STDIN>);
    exit unless (/^y/i);
	
}

warn 'getting members nearing account expiry' if $verbose;
my $dbh = C4::Context->dbh();
my $sth = $dbh->prepare(<<'END_SQL');
SELECT borrowers.borrowernumber, borrowers.title, borrowers.firstname, borrowers.surname, borrowers.dateexpiry
  FROM borrowers
  WHERE ( TO_DAYS( dateexpiry ) - TO_DAYS( NOW() ) ) < ?
  AND  TO_DAYS( dateexpiry ) > TO_DAYS( NOW() ) 
END_SQL
$sth->execute( $maxdays );
my $mem_exp = $sth->fetchall_arrayref({});
$sth->finish;
warn 'found ' . scalar( @$mem_exp ) . ' members nearing account expiry' if $verbose;


UPCOMINGITEM: foreach my $upcoming ( @$mem_exp ) {
    warn 'examining borrower number ' . $upcoming->{'borrowernumber'} if $verbose;
    # warn( Data::Dumper->Dump( [ $upcoming ], [ 'borrowernumber' ] ) );

    my $letter;
    #my $borrower_preferences;
    
    #$borrower_preferences = C4::Members::Messaging::GetMessagingPreferences( { borrowernumber => $upcoming->{'borrowernumber'},                                                                                   message_name   => 'item due' } );
        # warn( Data::Dumper->Dump( [ $borrower_preferences ], [ 'borrower_preferences' ] ) );
     #next DUEITEM unless $borrower_preferences;
        
        my $letter_type = 'EXP';
            $letter = C4::Letters::getletter( 'members', $letter_type );
            die "no letter of type '$letter_type' found. Please see sample_notices.sql" unless $letter;
            
            $letter = parse_letter( { letter         => $letter,
                                      borrowernumber => $upcoming->{'borrowernumber'},
                                      title     => $upcoming->{'title'},
                                      firstname   => $upcoming->{'firstname'},
				      surname   => $upcoming->{'surname'},
				      dateexpiry   => $upcoming->{'dateexpiry'}
                                    } );
  
    # If we have prepared a letter, send it.
    if ($letter) {
      if ($nomail) {
        local $, = "\f";
        print $letter->{'content'};
      }
      else {
#        foreach my $transport ( @{$borrower_preferences->{'transports'}} ) {
            C4::Letters::EnqueueLetter( { letter                 => $letter,
                                          borrowernumber         => $upcoming->{'borrowernumber'},
					  message_transport_type => 'email' } );
#                                          message_transport_type => $transport } );
#        }
      }
    }
}


=head1 METHODS

=head2 parse_letter



=cut

sub parse_letter {
    my $params = shift;
    foreach my $required ( qw( letter borrowernumber ) ) {
        return unless exists $params->{$required};
    }

    

    C4::Letters::parseletter( $params->{'letter'}, 'borrowers',   $params->{'borrowernumber'} );

    if ( $params->{'title'} ) {
        C4::Letters::parseletter( $params->{'letter'}, 'borrowers',    $params->{'title'} );
    }
    
    if ( $params->{'firstname'} ) {
        C4::Letters::parseletter( $params->{'letter'}, 'borrowers',    $params->{'firstname'} );
    }

    if ( $params->{'surname'} ) {
        C4::Letters::parseletter( $params->{'letter'}, 'borrowers',    $params->{'surname'} );
    }

    if ( $params->{'dateexpiry'} ) {
        C4::Letters::parseletter( $params->{'letter'}, 'borrowers',    $params->{'dateexpiry'} );
    }

    return $params->{'letter'};
}

1;

__END__
