#!/usr/bin/perl

# before anything else, the script needs to find out its own name
#
# some servers (notably IIS on windows) don't set the cwd to the script's
# directory before executing it.  So we get that information
# from $0 (the full name & path of the script).
BEGIN{($_=$0)=~s![\\/][^\\/]+$!!;push@INC,$_}

$name = $0;
$name =~ s/.+\/.+\///;  # for unix
$name =~ s/.+\\.+\\//;  # for windows
$path = $0;
$path =~ s/(.+\/).+/$1/g;  # for unix
$path =~ s/(.+\\).+/$1/g;  # for windows

if ($path ne "")
{
  chdir $path;
  push @INC,$path;
}
# check for required modules.

my $module_found=0;
foreach $temp_path (@INC)
{
  if (-e "$temp_path/CGI")
    {$module_found=1;}
}

if ($module_found == 0)
{
  $fatal_error=1;
  $error_info .= "unable to locate required module <b>CGI</b>!\n";
}
else
  {use CGI;}


$module_found=0;
foreach $temp_path (@INC)
{
  if (-e "$temp_path/CGI/Carp.pm")
    {$module_found=1;}
}

if ($module_found == 0)
{
  $fatal_error=1;
  $error_info .= "unable to locate required module <b>CGI::Carp</b>!\n";
}
else
  {use CGI::Carp qw/fatalsToBrowser/;}

$module_found=0;
foreach $temp_path (@INC)
{
  if (-e "$temp_path/Time")
    {$module_found=1;}
}

if ($module_found == 0)
{
  $fatal_error=1;
  $error_info .= "unable to locate required module <b>Time.pm</b>!\n";
}
else
  {use Time::Local;}

$module_found=0;
foreach $temp_path (@INC)
{
  if (-e "$temp_path/IO.pm")
    {$module_found=1;}
}
if ($module_found == 0)
{
  $fatal_error=1;
  $error_info .= "unable to locate required module <b>IO.pm</b>!\n";
}
else
  {use IO::Socket;}

if ($fatal_error == 1)  # print error and bail out
{
  &fatal_error();
}

$module_found=0;
foreach $temp_path (@INC)
{
  if (-e "$temp_path/plans_config.pl")
    {$module_found=1;}
}
if ($module_found == 0)
{
  $fatal_error=1;
  $error_info .= "Unable to locate <b>plans_config.pl</b>!  It should be in the same directory as plans.cgi!\n";
}
else {require "plans_config.pl";}

$module_found=0;
foreach $temp_path (@INC)
{
  if (-r "$temp_path/plans_lib.pl")
    {$module_found=1;}
}
if ($module_found == 0)
{
  $fatal_error=1;
  $error_info .= "Unable to locate <b>plans_lib.pl</b>!  It should be in the same directory as plans.cgi!\n";
}
else {require "plans_lib.pl";}

# get the language file, if one is defined

if (defined $options{language_file})
{
  $module_found=0;
  foreach $temp_path (@INC)
  {
    if (-r "$temp_path/$options{language_file}")
      {$module_found=1;}
  }
  if ($module_found == 0)
  {
    $fatal_error=1;
    $error_info .= "Unable to locate language file <b>$options{language_file}</b>!  It should be in the same directory as plans.cgi!\n";
  }
  else {require $options{language_file};}
}
else
{
  $fatal_error=1;
  $error_info .= "No language file defined in plans.config!\n";
}

# check for perl version
local $perl_version = (sprintf ("%vd",$^V));
my $temp = substr($perl_version,0,3);
if ($temp < 5.6) {
  $fatal_error=1;
  $error_info .= "Your version of perl ($perl_version) is too old!  Plans requires perl version 5.6 or better.\n";
}


if (!(-e "$temp_path/$config_file"))
{
  $fatal_error=1;
  $error_info .= "Unable to locate email reminders data file <b>$options{email_reminders_datafile}</b>!  It should be in the same directory as email_reminders.cgi!\n";
}

if ($fatal_error == 1)  # print error and bail out
{
  &fatal_error();
}

# init cgi stuff
#$q = new CGI;
#$script_url = $q->url(-path_info>=1);
#$script_url =~ /(.*)\//;          # remove trailing / and all text after
#$script_url = $1;                 # remove trailing / and all text after

my $new_lines = "";

&load_calendars();

  
# load upcoming event data
open (FH, "$options{email_reminders_datafile}") || ($debug_info .="\nUnable to open file $options{email_reminders_datafile}");
flock FH,2;
my @lines=<FH>;
close datafile;

foreach $line (@lines)
{
  if ($line !~ /\w/) {next};  # skip blank spaces 
  

  my $temp_line = $line;
  $temp_line =~ s/<\/?email_reminder>//g;
  my ($evt_id) = &xml_quick_extract($temp_line, "evt_id");
  my ($before) = &xml_quick_extract($temp_line, "before");
  my ($script_url) = &xml_quick_extract($temp_line, "script_url");
  $script_url = &decode($script_url);
  my ($extra_text) = &xml_quick_extract($temp_line, "extra_text");
  $extra_text = &decode($extra_text);
  my ($to_address) = &xml_quick_extract($temp_line, "email_address");
  $to_address = &decode($to_address);


  &load_event($evt_id);
  my $current_cal_id = $events{$evt_id}{cal_ids}[0];
  %current_calendar = %{$calendars{$current_cal_id}};
  &load_event($evt_id);
  %current_event = %{$events{$evt_id}};
  
  $rightnow = time() + 3600 * $current_calendar{gmtime_diff};
  
  my $event_timestamp = $current_event{start};
  
  $date_string = &nice_date_range_format($current_event{start}, $current_event{end}, " - ");

  my $event_time = "";
  if ($current_event{all_day_event} ne "1")
  {
    $event_time = &nice_time_range_format($current_event{start}, $current_event{end});
  }

  my $reminder_text = $lang{email_reminder_text};

  $reminder_text =~ s/###time###/$event_time/g;
  $reminder_text =~ s/###title###/$current_event{title}/g;
  $reminder_text =~ s/###date###/$date_string/g;
  $reminder_text =~ s/###details###/$current_event{details}/g;
  $reminder_text =~ s/###extra text###/$extra_text/g;
  $reminder_text =~ s/###link###/$script_url?view_event=1&evt_id=$current_event{id}/g;
  
  if (($event_timestamp - $rightnow) < $before)
  {
    $test_reminder_results = &send_email_reminder(\%current_event, $to_address, $reminder_text);
    if ($test_reminder_results eq "1")
    {
      $results .= "Reminder for event $evt_id ($events{$evt_id}{title}) sent successfully to <i>$to_address</i>!\n";
      #$results .= "$reminder_text\n";
    }
    else
    {
      $results .= "Reminder not sent to <i>$to_address</i>:<br/><br/>($test_reminder_results)\n";
    }
  }
  else
  {
    $new_lines .= $line;
  }
}

open (FH, ">$options{email_reminders_datafile}") || ($debug_info .="\nUnable to open file $options{email_reminders_datafile} for writing!");
flock FH,2;
print FH $new_lines;
close datafile;

$results =~ s/\n/<br\/>\n/g;
$debug_info =~ s/\n/<br\/>\n/g;

print <<p1;
Cache-control: no-cache,no-store,private
Content-Type: text/html; charset=iso-8859-1\n
<html>
<body>
$results
$debug_info
</html>
</body>
p1

sub fatal_error()
{
  $error_info =~ s/\n/<br>/g;

  $html_output .=<<p1;
Cache-control: no-cache,no-store,private
Content-Type: text/html; charset=iso-8859-1\n
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Plans error!</title>
</head>
<body>

<b>Plans error:</b><br>
$error_info
p1
  if ($debug_info ne "")
  {
    $debug_info =~ s/\n/<br>/g;
    $html_output .=<<p1;
<hr>
Debug info:<br>
$debug_info
p1

  }

  $html_output .=<<p1;
</body>
</html>
p1

  print $html_output;
  exit(0);
}


