#!/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 $e_id      				= $ARGV[0] ;

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

$input{event_details}   	= $q -> param('event_details') ;

our $debug = 1 ;

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

&today ;

&db_open_ro ;
	$db_ignore_open_close = 1 ;
	
	if ($iaction eq '') {
		&read_db ;
		&screen1 ;
	}
		   
	if ($iaction eq 'send') {
		&read_db ;
		&send_email ;
		&screen2 ;
	}
		
	$db_ignore_open_close = 0 ;
&db_close_conn ;

exit;

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

sub read_db {
	
	our $message = qq~~ ; 

	if ($iaction eq 'send') {
		
		&create_event_email_table($e_id) ; 
		
		my %seen_email = () ; our $emails = qq~~ ; 
		
		foreach (split(",",$iotheremailaddress)) {	
			next if $seen_email{$_} ; 
			$seen_email{$_} = 1 ;
			$emails .= qq~$_,~ ;			
		}
		
		$emails .= qq~$iemail~ if not $seen_email{$iemail} and $iemail ; 
		chop $emails if $seen_email{$iemail} or not $iemail ;
		
		our %operator_email = () ; our %operator_name = () ; our %operator_email_to_id = () ;
		$seen_email{$db{users}{$db{event_quotes}{1}{user_id}}{email}}  = 1; 
		foreach (sort {$db{users}{$a}{email} cmp $db{users}{$b}{email}} keys %{$db{users}}) {			
			$operator_name{$db{users}{$_}{email}} = $db{users}{$_}{name} ;
			if (substr($db{users}{$_}{user_type},0,6) eq 'casual') {
				$operator_email{$db{users}{$_}{email}} = 1 ;
				$operator_email_to_id{$db{users}{$_}{email}} = $_ ; 
			}
			
		}
		
	} elsif ($iaction eq '') {	
		
		&db_min_ro('event_quotes','1,operator_ids,user_id,ref,date_from',"`id`='$e_id'",'','') ;
		
		foreach (split(",",$db{event_quotes}{1}{operator_ids})) {
			$selected{email_other}{$_} = 'SELECTED' ;
		}
		# $selected{email_other}{$userid} = 'SELECTED' ;
		
		# &db_min_ro('users','id,email',"`user_type` LIKE 'casual%' OR `user_type` = 'schools_manager' OR `id` = '$userid'",'','') ;
		&db_min_ro('users','id,email,user_type,name',"",'','') ; # `user_type` LIKE 'casual%' OR `id` = '$db{event_quotes}{1}{user_id}'
		
		my %seen_email = () ; 
		$seen_email{$db{users}{$db{event_quotes}{1}{user_id}}{email}}  = 1; 
		foreach (sort {$db{users}{$a}{email} cmp $db{users}{$b}{email}} keys %{$db{users}}) {			
			next if $seen_email{$db{users}{$_}{email}} ; 
			$seen_email{$db{users}{$_}{email}} = 1 ;
			if (substr($db{users}{$_}{user_type},0,6) eq 'casual') {
				$operator_email{$db{users}{$_}{email}} = 1 ;
				$opts{email_other} .= qq~<option value="$db{users}{$_}{email}" $selected{email_other}{$_}>$db{users}{$_}{email}</option>~ if $db{event_quotes}{1}{user_id} ne $_ ; 
			}
			
		}
		$message = qq~Good day

Please find attached event details.
~ ;

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

sub send_email {
	
	&common_debug("\n iemail : $emails") ;
	
	my $bcc = "$email_events{1};$email_events{2}" ;

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

	if ($username eq 'rory')   { $bcc = $email_it_1   ; }	
	if ($username eq 'handre') { $bcc = $email_it_2 ; }

	my $attachpath = "$pdfpath/event_details" ;  $attachfile = "Event_Details-$e_id.pdf" ;
	
	if (not -f "$attachpath/$attachfile" || not $input{event_details}) { 
		$attachpath = '' ; $attachfile = '' ; 
	} 

	$imsg =~ s/\n/<br>/g;
	
	# my @email_adds = split(/\,/,$emails) ;
	# my $email_adds = join(";",@email_adds) ;
	
	# &common_debug("\n iemail : $emails") ;
	# exit ;
	
	# &common_send_smtp_mail('',$email_adds,'',$bcc,$isubject,$imsg,$table_message,1,'',$attachpath,$attachfile,'',$iattach) ;
	
	# $imsg =~ s/:/<\/td><td>:/g;
	# $imsg = qq~<td>$imsg</td>~ ; 
	# &common_send_smtp_mail('',$iemail,'',$bcc,$isubject,$imsg,1,'',$attachpath,$attachfile,'') ;
	
	my $message_operator = qq~~ ; my $emailed_operators = qq~~ ; 
	
	my $attach_flyer = 0 ; 
	$attach_flyer = 1 if $usertype eq 'schools_manager' or $username eq 'handre' ; 
	
	foreach (split(",",$emails)) {
		
		if ($operator_email{$_}) {
			$emailed_operators .= qq~$operator_email_to_id{$_};~ ; 
		}
		
		
		if ($operator_email{$_} || $_ eq $email_it_2 || $_ eq $email_it_1) {
	
			my @cat_details = split('\|;\|',$db{event_quotes_min}{1}{category_details}) ; 
			
			my $time_from = substr($db{event_quotes}{1}{date_from},11,5) ;
			
			$sports = uc $sports ; 

			my $cat_1 = qq~~ ; my $cat_2 = qq~~ ; my $cat_1_sub = qq~~ ; my $cat_2_sub = qq~~ ;
			
			$cat_1 = qq~CAT1: $db{event_quotes_categories}{$db{event_quotes}{1}{category_id_1}}{category}~ if $db{event_quotes_categories}{$db{event_quotes}{1}{category_id_1}}{category} ;
			$cat_1_sub = qq~SUB1: $cat_details[0]~ if $cat_details[0] ;
			# $cat_1 .= qq~<br>~ if $cat_1 and not $cat_1_sub ;
			$cat_2 = qq~CAT2: $db{event_quotes_categories}{$db{event_quotes}{1}{category_id_2}}{category}~ if $db{event_quotes_categories}{$db{event_quotes}{1}{category_id_2}}{category} ;
			$cat_2_sub = qq~SUB2: $cat_details[1]~ if $cat_details[1] ;
			# Hi $operator_name{$_}

# <b>$db{event_quotes}{1}{ref} @$time_from</b>

# $sports

# $cat_1
# $cat_1_sub
# $cat_2
# $cat_2_sub
			$message_operator = qq~Hi $operator_name{$_}		
			
$db{event_quotes}{1}{ref} AT $time_from 

$sports

$cat_1
$cat_1_sub
$cat_2
$cat_2_sub

Please let me know if you need anything. 

Thanks,
$db{users}{$userid}{name}~ ; 

# +27 82 439 6656
# Brandon Scullard
			$message_operator =~ s/\n/<br>/g ;
			&common_send_smtp_mail('',$_,'',$bcc,$isubject,$message_operator,'',1,'',$attachpath,$attachfile,'',$iattach,$attach_flyer) ;
			
		} else {
			&common_send_smtp_mail('',$_,'',$bcc,$isubject,$imsg,$table_message,1,'',$attachpath,$attachfile,'',$iattach,$attach_flyer) ;
		}
		
	}
	
	chop $emailed_operators if $emailed_operators ; 
	
	%i = () ; 
	$i{emailed_op_ids} = $emailed_operators ;
	&db_min_upd('event_quotes',"`id`='$e_id'") ;
	
	
} #-------------------------------------------------------------------------------

sub add_attachments {

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

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

	my $attachdoc = $pdfpath . '/' . $path . '/' . $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 check_attachments {

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

	my $docpath = $pdfpath . '/' . $path ;
	
	&common_debug("check_attachments : $attachfile") ;

	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) ;
			&common_debug("check_attachments : $file.$type") ;
			unless (lc $type eq 'pdf') { next ; }
			my ($prefix,$doc_nr,$invtxt,$date) = split(/\-/,$file) ;
			&common_debug("check_attachments : $prefix,$doc_nr,$invtxt,$date [$doc_nr eq $doc_id]") ;			
			unless ($doc_nr eq $doc_id) { next ; }
			$attachfile = $folder ;
			}
		}

	closedir(DIR) ;

	return($attachfile);

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

sub screen1 {

&common_min_dialog ;

# https://itvadmin.co.za/cgi-bin/scripts/pdf/event_details_pdf_test.pl?5136&&
	  
$attach_pdf .= qq(&nbsp;<input name='event_details' type='checkbox' CHECKED value='1'>&nbsp;<a class="btn btn-primary btn-xs" target="_blank" href="$useropts{scripts}/pdf/event_details_pdf.pl?$e_id" title="" style="padding-bottom:0;">Event Details PDF</a>);   
$attach_pdf .= qq(&nbsp;<iframe src="$useropts{scripts}/pdf/event_details_pdf.pl?$e_id" width='1px' height='1px' frameborder='0' style="display:none;"></iframe>);   

$lcol = 3 ; $fcol = 8 ;
$multiple{email_other} = 1 ;
$preferred_title{email_other} = "Operators Email Addresses" ;
$print_box_content_rows .= &common_min_form_select('email_other','') ; 

my $date_from  = $db{event_quotes}{1}{date_from} ;
my $event_from = Date_to_Text(substr($date_from,0,4),substr($date_from,5,2),substr($date_from,8,2));

# &common_debug("year : " . substr($date_from,0,4)) ;
# &common_debug("month : " . substr($date_from,5,2)) ;
# &common_debug("day : " . substr($date_from,8,2)) ;

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="?$e_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-8'>
							<div class='control-group'>
								<div class='controls'> 
									<input type='text' name='iemail' class='form-control' id='inputEmail' placeholder='Email Address' value="$db{users}{$db{event_quotes}{1}{user_id}}{email}" tabindex="1" data-validation="required">
								</div>
							</div>
						</div>
					</div>	
					$print_box_content_rows
					<input type="hidden" name="iotheremailaddress" id="other-email-address" value="">
					<div class='row'>
						<div class='fieldname col-md-3'>
							<label class='control-label' for='docInputFile'>Attach </label>
						</div>
						<div class='col-md-8'>
							<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-8'>
							<div class='control-group'>
								<div class='controls'>                                
									<input type='text' name='isubject' class='form-control' id='inputSubject' placeholder='Subject' value="$useropts{short} Event : $db{event_quotes}{1}{ref} - $event_from" 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-8'>
							<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-11">	
							<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();

	let emails = \$("#selectEmail_other").chosen().val() ;
	\$('#other-email-address').val(emails) ;

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

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

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

sub screen2 {
	
my $jquery_raw = qq~parent.BootstrapDialog.closeAll() ;~ unless $username eq 'rory' ;
     
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.noty({text:"Successfully Sent",layout:"center",type:"success",timeout:5000}) ;
		$jquery_raw
	});

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

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

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

1;
