#!/usr/bin/perl

BEGIN { use lib '/usr/home/cfg' ; require push_inc ; }
    
use CGI qw( :standard );
use CGI::Carp qw(fatalsToBrowser);
use LWP::Simple qw($ua get);
use Date::Calc qw(:all);
use MIME::Lite;
use Mail::Sendmail;
use File::Copy;
use File::Basename;

require cfg ;

print header;   # CGI.pm method

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

my @ARGV      = split(/\&/, $ENV{'QUERY_STRING'});
my $wb_no     = $ARGV[0] ;
my $mn_id     = $ARGV[1] ;

my ($q)                 = CGI -> new() ;
my $iaction             = $q -> param('iaction')  ;
my $iemail              = $q -> param('iemail')   ;
my $imsg                = $q -> param('imsg')   ;
my $isubject            = $q -> param('isubject')   ;

$input{manifest}        = $q -> param('manifest')   ;
$input{invoice}         = $q -> param('invoice')   ;
$input{waybillmulti}    = $q -> param('waybillmulti')   ;

my $iattach             = $q->upload('iattach') ;

# our $debug = 1 ;

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

&today ;

if ($iaction eq ''){
    &read_db ;
    &journey_attachments ;
    &screen1 ;
    }
       
if ($iaction eq 'send'){
    &read_db ;
    &send_email ;
    &screen2 ;
    }

exit;

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

sub read_db {

&db_load_airports ;

&db_min_ro('users','*',"`id`='$userid'",'','') ;
foreach my $us_id (keys %{$db{users}}) { 
	$email{$us_id} = $db{users}{$us_id}{email} ;
	}
    
&db_min_ro('waybills','*',"`WaybillNo`='$wb_no'",'','') ;
foreach my $wb_id (keys %{$db{waybills}}) { 
	$client{$wb_id} = $db{waybills}{$wb_id}{Client} ;
	# $mawb_no{$wb_id} = $db{waybills}{$wb_id}{MawbNo} ;
	
	# $origin_airp_code{$wb_id} = $airport_code{$db{waybills}{$wb_id}{OriginID}} ;
	# $dest_airp_code{$wb_id}   = $airport_code{$db{waybills}{$wb_id}{DestID}} ;
	}
    
&db_min_ro('clients','*',"`Client`='$client{$wb_no}'",'','') ;
foreach my $id (keys %{$db{clients}}) { 
	$client = $db{clients}{$id}{Client} ; 
	
	$client_id{$wb_no} = $id ; 
	
	$client_email1{$id}   = $db{clients}{$id}{Email1} ; 
	$client_phoneno{$id}  = $db{clients}{$id}{PhoneNo} ; 
	$client_contact1{$id} = $db{clients}{$id}{Contact1} ; 
	}
	
&db_min_ro('manifests','*',"`ManifestID`='$mn_id'",'','') ;
foreach my $id (keys %{$db{manifests}}) { 
	# $mawb_no{$db{manifests}{$id}{WaybillNo}} = $db{manifests}{$id}{MawbNo} ;
	$mawb_no{$mn_id}   = $db{manifests}{$id}{MawbNo} ;
	$mawb_from{$mn_id} = $db{manifests}{$id}{ManifestFrom} ;
	$mawb_to{$mn_id} = $db{manifests}{$id}{ManifestTo} ;
	}
	
# our $mawb_subj = '' ; if ($mawb_no{$wb_no}) { $mawb_subj = " : MAWB $mawb_no{$wb_no}" ; }
our $mawb_subj = '' ; if ($mawb_no{$mn_id}) { $mawb_subj = " : MAWB $mawb_no{$mn_id}" ; }
# our $airp_subj = '' ; if (($origin_airp_code{$wb_no}) and ($dest_airp_code{$wb_no})) { $airp_subj = " - $origin_airp_code{$wb_no}-$dest_airp_code{$wb_no}" ; }
our $airp_subj = '' ; if (($airport_code{$mawb_from{$mn_id}}) and ($airport_code{$mawb_to{$mn_id}})) { $airp_subj = " - $airport_code{$mawb_from{$mn_id}}-$airport_code{$mawb_to{$mn_id}}" ; }
    
# my ($inv_year,$inv_mm,$inv_dd) = split(/\-/,$inv_date{$inv_id}); 
    
# our $month_to_txt = Month_to_Text($inv_mm);

# my $client_to = $client_contact1{$client_id{$wb_no}} ; unless ($client_to) { $client_to = $client_id{$wb_no} ; }

$message = qq(Good day

Please find attached Pre-alert.

Kind Regards,

-- 

Film Freight
Johannesburg: +27 11 706 0143
Cape Town: +27 21 802 3456
Email : filmfreight\@filmfreight.co.za
Website: www.filmfreight.co.za) ;
    
} #------------------------------------------------------------------------------------------

sub send_email {

my $bcc = 'vivian@filmfreight.co.za' ;

if ($email{$userid}) { $bcc = $email{$userid} ; }

if ($username eq 'rory') { $bcc = 'rory@kre8it.co.za' ; }

# Subject => "Film Freight Pre-alert$mawb_subj$airp_subj",

$msg = MIME::Lite -> new(
    From    => "Film Freight <filmfreight\@filmfreight.co.za>",
    To      => $iemail,
    Bcc     => $bcc,
    Subject => $isubject,
    Type    => 'multipart/mixed'
);
    
$msg->attach(
    Encoding => 'base64',
    Type     => 'image/png',
    Path     => "$htmlpath/img/email_logo.jpg",
    Id       => 'logo'
    # Disposition => 'inline',
);

$msg -> attach(
    Type     => 'TEXT',
    Data     => $imsg);
    
# my $texto = "<html><body><img src='cid:logo'/><br><br>$imsg </body></html>";
    
# $msg->attach(
    # Type => 'text/html',
    # Data => $texto,
    # Encoding => 'quoted-printable'
# );

if ($input{manifest}){    
    $attachfile = &check_attachments('manifest',$mn_id) ;
    &add_attachments('manifest',$attachfile,'pdf') ;
    }
    
if ($input{invoice}){    
    $attachfile = &check_attachments('invoice',$client_id{$wb_no}) ;
    &add_attachments('invoice',$attachfile,'pdf') ;
    }
    
if ($input{waybillmulti}){    
    $attachfile = &check_attachments('waybillmulti',$client_id{$wb_no}) ;
    &add_attachments('waybillmulti',$attachfile,'pdf') ;
    }
	
for my $jcnt (0 .. 5) {
	my $j = $q -> param("journeys_$jcnt") ;
	# &common_debug("send_email : attach_journey [$j]");
	if ($j) { $attach_journey{$j} = 1 ; }
	}
	
&attach_journey_mawbs;

# exit;
    
# if ($input{journeys}){    
    # &attach_journey_mawbs;
    # }
  
if ($iattach) {

$msg -> attach (
Type        => 'AUTO',
FH          => $iattach,
Filename    => $iattach,
Disposition => 'attachment'
) or die "Error adding : $attachdoc $!\n";

}
    
$msg -> send ('smtp','localhost', Debug=>0 );

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

sub add_attachments {

my ($type,$attachfile,$path) = @_ ;

unless ($attachfile) { print "no file to attach!" ; exit ; }

my $attachdoc = $htmlpath . '/' . $path . '/' . $type . '/' . $attachfile ;

unless (-e $attachdoc) { print "no file to attach : $attachdoc!" ; exit ; }

$msg -> attach (
Type        => 'AUTO',
Path        => $attachdoc,
Filename    => $attachfile,
Disposition => 'attachment'
) or die "Error adding : $attachdoc $!\n";
	
} #-------------------------------------------------------------------------------

sub attach_journey_mawbs {

&db_load_hawb_journeys_detail($wb_no) ;

foreach my $wb (keys %journeys) {
    foreach my $jnid (sort {$a <=> $b} keys %{$journeys{$wb}}) {
        %uploads_list = ();
        
        &common_get_uploads("journeys/$jnid") ;
		
		if ($uploads_list{'mawb'}) {
			my @files = split(/\|/,$uploads_list{'mawb'}) ;
			
			foreach my $file (@files) {
				# &common_debug("attach_journey_mawbs : add_attachments [$attach_journey{$file}] $file");
				unless ($attach_journey{$file}) { next ; } # skip if checkbox not selected
				&add_attachments("journeys/$jnid",$file,'uploads') ;
				}
			}
		}
    }

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

sub check_attachments {

my ($type,$doc_id) = @_ ;

my $docpath = $pdfpath . '/' . $type ;

my $attachfile = '' ;

opendir(DIR, "$docpath") or die "cant open directory: $invoicepath - $!\n";

while(defined($folder = readdir(DIR))) {
    if (length $folder > 2) {
        my ($file,$type) = split(/\./,$folder) ;
        unless (lc $type eq 'pdf') { next ; }
        my ($prefix,$doc_nr,$invtxt,$date) = split(/\-/,$file) ;		
        unless ($doc_nr eq $doc_id) { next ; }
        $attachfile = $folder ;
        }
    }

closedir(DIR) ;

return($attachfile);

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

sub journey_attachments {

our @journeys = () ; our $jn_wb_list = '' ;

&db_load_hawb_journeys($wb_no) ;

foreach my $jn (@journeys) {
	my ($wb_no,$jn_id) = split(/\:/,$jn);
	
	unless ($done_jn{$jn_id}) { 
		&common_get_uploads("journeys/$jn_id") ;
		&db_load_journey($jn_id,'') ; 
		$done_jn{$jn_id} = 1 ; 
		foreach my $wb (@hawbs) {
			unless ($done_wb{$wb}) { $jn_wb_list .= $wb . '|' ; $done_wb{$wb} = 1 ; }
			}
		}
	}

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

sub screen1 {

unless ($jn_wb_list) { $jn_wb_list = $wb_no ; }

&common_min_dialog ;
	  
$attach_pdf .= qq(&nbsp;<input name='invoice' type='checkbox' CHECKED value='1'>&nbsp;<a class="btn btn-primary btn-xs" target="_blank" href="$useropts{scripts}/pdf/inv_pdf.pl?$client_id{$wb_no}&$jn_wb_list" title="" style="padding-bottom:0;">Invoice PDF</a>);   
$attach_pdf .= qq(&nbsp;<iframe src="$useropts{scripts}/pdf/inv_pdf.pl?$client_id{$wb_no}&$jn_wb_list" width='1px' height='1px' frameborder='0' style="display:none;"></iframe>);   
$attach_pdf .= qq(&nbsp;<input name='waybillmulti' type='checkbox' CHECKED value='1'>&nbsp;<a class="btn btn-primary btn-xs" target="_blank" href="$useropts{scripts}/pdf/waybill_pdf_multi.pl?$client_id{$wb_no}&$jn_wb_list" title="" style="padding-bottom:0;">Waybill PDF</a>);   
$attach_pdf .= qq(&nbsp;<iframe src="$useropts{scripts}/pdf/waybill_pdf_multi.pl?$client_id{$wb_no}&$jn_wb_list" width='1px' height='1px' frameborder='0' style="display:none;"></iframe>);

if ($mn_id) { 
    $attach_pdf .= qq(&nbsp;<input name='manifest' type='checkbox' CHECKED value='1'>&nbsp;<a class="btn btn-primary btn-xs" target="_blank" href="$useropts{scripts}/pdf/manifest_pdf.pl?$mn_id" title="" style="padding-bottom:0;">Manifest PDF</a>);   
    $attach_pdf .= qq(&nbsp;<iframe src="$useropts{scripts}/pdf/manifest_pdf.pl?$mn_id" width='1px' height='1px' frameborder='0' style="display:none;"></iframe>);   
    }
	
my @mawb_links   = split(/\|/,$attach_link_split{'mawb'})  ; my $mawb_cnt = 0 ;
my @mawb_uploads = split(/\|/,$uploads_list{'mawb'}) ;

foreach my $mawb_pdf (@mawb_links) {
	$attach_pdf .= "&nbsp;<input name='journeys_$mawb_cnt' type='checkbox' CHECKED value='$mawb_uploads[$mawb_cnt]'>&nbsp;" . $mawb_pdf ;
	$mawb_cnt++;
	}

# if ($attach_link{'mawb'}) { $attach_pdf .= "&nbsp;<input name='journeys' type='checkbox' CHECKED value='1'>&nbsp;" . $attach_link{'mawb'} ; }
    
print <<ENDOFTEXT;
$dialog{'common'}{'head'}
    
<div id="content" class="col-lg-12 col-sm-12">
    <!-- content starts --> 
    <form role="form" name="form_events" id="events-form" action="?$wb_no&$mn_id" method="post" enctype="multipart/form-data">
        <div class="row"><div class="box col-md-12">Attach : $attach_pdf</div></div>
        <div class="row">
            <div class="box col-md-12">
                <div class='row'>
                    <div class='fieldname col-md-3'>
                        <label class='control-label' for='inputEmail'>Email Address <i class="glyphicon glyphicon-asterisk yellow"></i></label>
                    </div>
                    <div class='col-md-9'>
                        <div class='control-group'>
                            <div class='controls'> 
                                <input type='text' name='iemail' class='form-control' id='inputEmail' placeholder='Email Address' value="" tabindex="1" data-validation="required">
                            </div>
                        </div>
                    </div>
                </div>
                <div class='row'>
                    <div class='fieldname col-md-3'>
                        <label class='control-label' for='docInputFile'>Attach </label>
                    </div>
                    <div class='col-md-9'>
                        <div class='control-group'>
                            <div class='controls'> 
                                <input type="file" id="docInputFile" name='iattach' placeholder='Manually attach doc' tabindex='2'>
                            </div>
                        </div>
                    </div>
                </div>
                <div class='row'>
                    <div class='fieldname col-md-3'>
                        <label class='control-label' for='inputSubject'>Subject <i class="glyphicon glyphicon-asterisk yellow"></i></label>
                    </div>
                    <div class='col-md-9'>
                        <div class='control-group'>
                            <div class='controls'>                                
								<input type='text' name='isubject' class='form-control' id='inputSubject' placeholder='Subject' value="Film Freight Pre-alert$mawb_subj$airp_subj" tabindex="3" data-validation="required">
                            </div>
                        </div>
                    </div>
                </div>
                <div class='row'>
                    <div class='fieldname col-md-3'>
                        <label class='control-label' for='inputMessage'>Message <i class="glyphicon glyphicon-asterisk yellow"></i></label>
                    </div>
                    <div class='col-md-9'>
                        <div class='control-group'>
                            <div class='controls'> 
                                <textarea name='imsg' class='form-control' id='inputMessage' value="" tabindex="4" style="width:100%;height:250px;" data-validation="required">$message</textarea>
                            </div>
                        </div>
                    </div>
                </div>
                <input type="hidden" name="iaction" id="action" value="send">
                <div class="row"><div class="col-md-12">&nbsp;</div></div>
                <div class="row">
                    <div class="col-md-12">	
                        <button type="button" class="btn btn-primary" id="sendbutt">Send</button>&nbsp;
                        <button type="button" class="btn btn-default" onclick="parent.BootstrapDialog.closeAll();">Close</button>
                    </div>
                </div>
                <div class="row"><div class="col-md-12">&nbsp;</div></div>
            </div>
        </div>
    </form>
</div> 
</div><!--/fluid-row-->   
</div><!--/.fluid-container-->

<!-- external javascript -->

<style>body { font-size: 14px; }.control-label { font-size: 14px; }</style>
<script src="$useropts{'js'}/jquery.form-validator.min.js"></script>

$dialog{'common'}{'js'}

<script>

\$.validate();

\$("#sendbutt").click(function() {    
    \$('#action').val('send');
    \$('#events-form').submit();
});

</script>
</body>
</html>
ENDOFTEXT
#         

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

sub screen2 {
     
print <<ENDOFTEXT;
<!DOCTYPE html>
<html lang="en">
<head>    
    <meta charset="utf-8">
    <title>Film Freight Admin</title>
    <script src="$useropts{'bower_components'}/jquery/jquery.min.js"></script>  
</head>
<body>
<script>

\$(function () {
    parent.\$("#alertbar").html("<div class='alert alert-success' id='alertmsg' role='alert'><i class='glyphicon glyphicon-ok'></i> EMAIL SENT TO $iemail</div>");
    parent.BootstrapDialog.closeAll() ;
});

</script>
</body>
</html>
ENDOFTEXT
#

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

use today ;
use common ;
use common_min ;
use db_min ;

1;
