#!/usr/bin/perl

BEGIN { use lib '/usr/home/cfg' ; require push_inc ; }
    
use CGI qw( :standard );
use CGI::Carp qw(fatalsToBrowser);
use Fcntl qw(:flock);
use MIME::Parser;
use MIME::Lite;
use Mail::Sendmail;
use Text::Unidecode;
    
require cfg ;

print header;   # CGI.pm method

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

&today;

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

our ($q)                 = CGI -> new() ;
my $uniqueid             = $q -> param('uniqueid') ;
my $subject              = $q -> param('subject')  ;
my $from                 = $q -> param('from')  ;
my $iaction              = $q -> param('iaction')  ;
my $iemail               = $q -> param('iemail')   ;
my $imsg                 = $q -> param('imsg')   ;
my $suid                 = $q -> param('suid')   ;
my $responded            = $q -> param('responded')   ;

$subject  =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg; 

# our $debug = 1 ;
# &common_debug ("subject = [$subject]");

unless ($uniqueid) { print "No ticket id..." ; exit ; }

# our $ticket_dir  = "$mailpath/tickets/$uniqueid" ;

#-------- page opts --------------------------------------------------------------------------------------------------------------------------------------------------

&page_opts ;

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

if ($iaction eq 'send'){
    &send_email ;
    &screen3 ;
} else {
	&process_ticket_data;
	&screen2;
}

exit;

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

sub process_ticket_data {
	
	my $table = 'tickets' ;
		
	&db_min_ro($table,'*',"unique_id='$uniqueid' OR suid='$suid' OR unique_id='$suid'",'','') ;

	foreach my $tid (sort {$b <=> $a} keys %{$db{$table}}) {
		my $uid   = $db{$table}{$tid}{unique_id} ;
		my $tdir  = "$mailpath/tickets/$uid" ;
		&read_ticket_dir($tdir) ;
		&create_message($tdir) ;
		&create_attachment($uid) ;
	}

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

sub read_ticket_dir {
	
	my ($ticket_dir) = @_ ;

	our $found_msg = 'n' ; our $msgfile = '' ;
	
	our @attachment_array = () ;

	&common_debug ("read_ticket_dir = [$ticket_dir]");

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

	while(defined($folder = readdir(DIR))) {
		if (length $folder < 3) { next ; }
			
		&common_debug ("folder = [$folder]");

		if (substr($folder,0,4)  eq 'msg-' && substr($folder,-4,4) eq '.txt') {
			$msgfile   = $folder ;
			$found_msg = 'y' ;
			&common_debug ("msgfile = [$msgfile]");
		} else {
			push @attachment_array, $folder ;
		}
	}

	closedir(DIR) ;

	# IF NO TXT FILE FOUND, REPEAT, LOOKING FOR HTML MSG

	if ($found_msg eq 'n') {
		opendir(DIR, $ticket_dir) or die "cant open directory : $ticket_dir : $!\n";
		while(defined($folder = readdir(DIR))) {

			if (length $folder < 3) { next ; }
			if (substr($folder,0,4)  eq 'msg-' && substr($folder,-5,5) eq '.html') {
				$msgfile   = $folder ;
				$found_msg = 'y' ;
			}
		}
		closedir(DIR) ;
	}

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

sub create_message {
	
	my ($ticket_dir) = @_ ;
	
	my $print_message = '' ;

	if ($found_msg eq 'y') {

		$messagefile = "$ticket_dir/$msgfile" ;
		
		&common_debug ("messagefile = [$messagefile]");

		use open qw(:std :utf8);

		open  (M1FILE, "$messagefile")   or die "can't open $messagefile: $!" ;
		flock (M1FILE, LOCK_SH)          or die "can't lock $messagefile: $!" ;

			while (<M1FILE>) {
				$print_message .= $_ ;
			}

		close   (M1FILE);

		$print_message =~ s/\n/<BR>/g;

		# These next two put in to bodge LTS emails coming in
		$print_message =~ s/&nbsp;/ /g;
		$print_message =~ s/font-size: 12pt;/font-size: 12px;/g;

	} else {
		$print_message = "No message";
	}
		
	$print_box_content_rows .= qq~<blockquote><p>$print_message</p><small>---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------</small>~ if $print_message ;
	
} #------------------------------------------------------------------------------------------

sub create_attachment {
	
	my ($unique_id) = @_ ;
	
	my $print_attachments = '' ; my $acnt = 0 ;

	foreach $attachment (@attachment_array) {
		# $print_attachments .= qq~<a href="$useropts{'mail'}/tickets/$unique_id/$attachment">$attachment</a><font color=black> | </font>~;
		$acnt++;
		$print_attachments .= qq~<font color=black> | </font>~ if $acnt > 1 ;		
		$print_attachments .= qq~<a href="$useropts{'scripts'}/pdf/mail_attach.pl?$unique_id/$attachment">$attachment</a>~;
	}
		
	$print_box_content_rows .= $print_attachments ;

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

sub page_opts {

	our $glyphicon = 'envelope' ;

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

sub send_email {

# # my $bcc = 'accounts@kre8it.co.za;rory@mathew.za.net' ;

# $msg = MIME::Lite -> new(
    # # From    => "ITV Support <tickets\@aisport.africa>",
    # # From    => "ITV Support <itv.k\@re8it.com>",
    # From    => "ITV Support <tickets\@interactivetvafrica.com>",
    # To      => $iemail,
    # Bcc     => $bcc,
    # Subject => "$subject",
    # Type    => 'multipart/mixed'
# );

# $msg -> attach(
    # Type     => 'TEXT',
    # Data     => $imsg);

# # &check_attachments ;
# # &add_attachments ;
    
# $msg -> send ('smtp','localhost', Debug=>0 );

# &common_send_mail($iemail,'','','html','',"$imsg","$subject") ;
&common_send_mail($iemail,'','','','',"$imsg","$subject") ;

$i{responded} = 1 ;
$i{suid}      = $suid if $suid ;

&db_min_upd('tickets',"unique_id='$uniqueid'") ;

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

sub screen2 {

&common_min_alert_type ;

&common_min_dialog ;

# &common_debug ("screen2 [suid=$suid]");

# my $resubject  = "$subject #$uniqueid" ;
my $resubject  = ($subject =~ /Re:/iog) ? '' : 'Re: ' ;
my $resubject .= "$subject ##$suid##" ;

# unless ($suid) {
unless ($responded) {
	$reply_section = qq~<div class="row">
        <div class="box col-md-12">
            <form role="form" name="form_events" id="reply-form" action="" method="post">
			<div class='row'>
				<div class='fieldname col-md-2'>
					<label class='control-label' for='inputSubject'>Subject <i class="glyphicon glyphicon-asterisk yellow"></i></label>
				</div>
				<div class='col-md-8'>
					<div class='control-group'>
						<div class='controls'> 
							<input type='text' name='subject' class='form-control' id='inputSubject' READONLY placeholder='Subject' value="$resubject" data-validation="required" tabindex="1">
						</div>
					</div>
				</div>
			</div>
            <div class='row'>
				<div class='fieldname col-md-2'>
					<label class='control-label' for='inputEmail'>Email <i class="glyphicon glyphicon-asterisk yellow"></i></label>
				</div>
				<div class='col-md-8'>
					<div class='control-group'>
						<div class='controls'> 
							<input type='text' name='iemail' class='form-control' id='inputEmail' placeholder='Email Address' value="$from" data-validation="email" tabindex="2">
						</div>
					</div>
				</div>
			</div>
            <div class='row'>
				<div class='fieldname col-md-2'>
					<label class='control-label' for='inputMessage'>Message <i class="glyphicon glyphicon-asterisk yellow"></i></label>
				</div>
				<div class='col-md-8'>
					<div class='control-group'>
						<div class='controls'> 
							<textarea name='imsg' class='form-control' id='inputMessage' value="" style="width:100%;height:200px;" data-validation="required" tabindex="3">$message</textarea>
						</div>
					</div>
				</div>
			</div>
            <input type="hidden" name="iaction" id="action" value="send">
            <input type="hidden" name="uniqueid"            value="$uniqueid">
            <input type="hidden" name="subject"             value="$subject">
            <input type="hidden" name="suid"                value="$suid">
            <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="submit" class="btn btn-primary">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>
            </form>
        </div>
    </div>~ ;
}
      
print <<ENDOFTEXT;
$dialog{'common'}{'head'}
    
<div id="content" class="col-lg-12 col-sm-12">
    <!-- content starts -->   
	
	$alert
	
	$reply_section
    
    <div class="row">
        <div class="box col-md-12">
            <div class="box-inner">
                <div class="box-header well" data-original-title="">
                    <h2><i class="glyphicon glyphicon-envelope"></i> Emails Correspondance</h2>                    
                </div>
                <div class="box-content">
                    $print_box_content_rows</blockquote>
                </div>
            </div>
        </div>
    </div><!--/row--> 
	
</div><!--/row-->
    
</div><!--/fluid-row-->
    
</div><!--/.fluid-container-->

<!-- external javascript -->

<style>body { font-size: 14px; }.control-label { font-size: 14px; }</style>

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

<script>

\$.validate(); 

\$(document).ready(function () { 
    $trigger_jquery
});

$trigger_jquery_raw

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

</script>

$print_footer_jscript
$print_footer_forms
</body>
</html>
ENDOFTEXT
#

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

sub screen3 {
     
print <<ENDOFTEXT;
<!DOCTYPE html>
<html lang="en">
<head>    
    <meta charset="utf-8">
    <title>$useropts{title}</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.\$("#$uniqueid").hide();
    parent.BootstrapDialog.closeAll() ;
});

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

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

use db ;
use common ;
use today ;

1;