#!/usr/bin/perl

BEGIN { use lib '/usr/home/cfg' ; require push_inc ; }
    
require cfg ;

print "Content-type: text/html\n\n";

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

use CGI::Carp qw(fatalsToBrowser);
use DBI;
use CGI;
use Fcntl qw(:flock);
use File::Copy;
use File::Basename;
use Image::Size;

&today;

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

@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'});

our $id      	= $ARGV[0] ;
our $system_id	= $ARGV[1] ;
our $day_cnt	= $ARGV[2] ;

exit if !$id || !$system_id || !$day_cnt ;

our ($q)    = CGI -> new() ;
$iaction    = $q -> param('iaction')      || $action ;

our $dialog     = 1 ;
our $postgresql = 1 ;

our $table = 'calibration_status_report' ;

#------------------------------------------------------------------------------------------
# our $testing = 1 ;
#------------------------------------------------------------------------------------------


if (($iaction eq '') and ($id)) {
    &load_uploads_list ;
    &screen1 ;
}  

if ($iaction eq 'update') {
    &common_min_load_params ;
    &process_for_incident_uploads ;
	our $did_not_update_table = 0 ; 
    &upload_uploads ; 
	if ($did_not_update_table) {
		&load_uploads_list ;
		&screen1 ;		
	} else {
		&screen2 ;
	} 
}

if ($iaction eq 'delete') {
    &common_min_load_params ;
    &delete_uploads ;
    &load_uploads_list ;
    &screen1 ;
}
    
exit ;

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

sub load_uploads_list {
	
	&uploads_list ; 
	
} #----------------------------------------------------------------------------------------

sub process_for_incident_uploads {

foreach (keys %i) {
    if (/description/) { next ; }
    unless ($i{$_}) { $ignore{$_} = 1 ; }
    if ((/iattach/) and ($i{$_})) {
        $ignore{$_} = 1 ; s/iattach//gi ; 
        # $i{$_} = $i{"iattach$_"} ; 
        my $safe_filename_characters = "a-zA-Z0-9_.-";
        my $filename = $i{"iattach$_"} ;
           $filename =~ tr/ /_/;
           $filename =~ s/[^$safe_filename_characters]//g;
        $i{$_} = $filename ; 
	}
}
    
$ignore{incidentuploads_length} = 1 ;
$ignore{iaction} = 1 ;

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

sub upload_uploads {

&db_min_ro($table,"1,id,upload_names","`event_quote_id`='$id'",'','') ; 

my %ii = %i ; 
%i = () ; 

unless ($db{$table}{1}{id}) {
	$i{id} = &db_min_get_max($table,'id') ;
	$i{event_quote_id} = $id ;
	&db_min_insert($table) ; 
	%i = () 
}

my %ignore_attach = () ; 

my %seen_upload = () ; my %seen_upload_for_this_day_and_system = () ; 

my $upload_names_str = qq~~ ;

my %upload_names = () ; 

foreach my $system_frames (split(/\|/,$db{$table}{1}{upload_names})) {
	my ($saved_system_id,$frames) = split(/\~/,$system_frames) ;
	my $saved_day_cnt = 0 ;
	foreach my $day_frames (split(/\:/,$frames)) {
		$saved_day_cnt++ ; my $saved_frames_cnt = 0 ; 
		foreach my $all_frames (split(/\;/,$day_frames)) {
			$seen_upload{$all_frames}++ if $all_frames && $saved_system_id ne $system_id && $saved_day_cnt ne $day_cnt ;
			$saved_frames_cnt++ ;
			$upload_names{$saved_system_id}{$saved_day_cnt}{$saved_frames_cnt} = $all_frames if $all_frames ; 
			$seen_upload_for_this_day_and_system{$all_frames}++ if $all_frames && $saved_system_id eq $system_id && $saved_day_cnt eq $day_cnt ;
		}
	}
}

for (1 .. 10) {	
	$ignore_attach{$_} = 1 ; 
	my $field = "iattachphoto_$_" ;
	my $processed_name = ($ii{$field}) ? &common_process_uploaded_file_names($ii{$field}) : $ii{$field} ;
	$seen_upload{$processed_name}++	if $processed_name ;
	$seen_upload_for_this_day_and_system{$processed_name}++ if $processed_name ;
	$upload_names{$system_id}{$day_cnt}{$_} = $processed_name 	if $processed_name 	&& $seen_upload_for_this_day_and_system{$processed_name} <= 1 ; 
	$upload_names{$system_id}{$day_cnt}{$_} = ""				if $ii{$field} 		&& $seen_upload_for_this_day_and_system{$processed_name} > 1 ; 
}

foreach my $saved_system_id (sort {$a <=> $b} keys %upload_names) {
	
	$i{upload_names} .= qq~$saved_system_id\~~ ;
	my $prev_day = 0 ; 

	foreach my $day_frames (sort {$a <=> $b} keys %{$upload_names{$saved_system_id}}) {

		if ($day_frames - $prev_day > 1) {
			for (1 .. $day_frames - $prev_day - 1) {
				$i{upload_names} .= qq~:~ ;
			}
		}
		$prev_day = $day_frames ;
		
		foreach my $frame_cnt (sort {$a <=> $b} keys %{$upload_names{$saved_system_id}{$day_frames}}) {

			$i{upload_names} .= qq~$upload_names{$saved_system_id}{$day_frames}{$frame_cnt};~ ; 
			if ($upload_names{$saved_system_id}{$day_frames}{$frame_cnt} && $saved_system_id eq $system_id && $day_frames eq $day_cnt && not -f "$htmlpath/uploads/calibration_status_uploads/$id/$upload_names{$saved_system_id}{$day_frames}{$frame_cnt}") {
				$ignore_attach{$frame_cnt} = 0 ; 
			}
		}
		$i{upload_names} =~ s/;+$// ;
		$i{upload_names} .= qq~:~ ;
		
	}
	
	$i{upload_names} =~ s/:+$// ;
	$i{upload_names} .= qq~|~ ;
}

$i{upload_names} =~ s/\|+$// ;

if (($i{upload_names} eq $db{$table}{1}{upload_names}) || (!$i{upload_names} && !$db{$table}{1}{upload_names})) {
	%i = %ii ;
	$did_not_update_table = 1 ; 
	$alert = &common_min_alert('warning',"PLEASE UPLOAD UNIQUE IMAGES FOR THIS DAY AND SYSTEM!",'ok') ;
	return ; 
}

&db_min_upd($table,"`event_quote_id`='$id'") ; 

%i = %ii ;

my %seen_attach = () ; 

for my $p (1 .. 10) {
	next if $ignore_attach{$p} ;
	$p = "iattachphoto_$p" ;
	my $val = $q->param($p) ;
	next if $seen_attach{$val} ;
	$seen_attach{$val} = 1 ;
	&common_upload_file($val,$p,'',"calibration_status_uploads/$id") ;
}

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

sub delete_uploads {

unless ($i{event_quote_id}) { $error = qq(NO ID) ; return ; }

&db_min_ro($table,'1,upload_names',"`event_quote_id`='$i{event_quote_id}'",'','') ;

my %ii = %i ;
%i = () ;

my %seen_upload = () ; my %seen_upload_for_this_day_and_system = () ; 

my $upload_names_str = qq~~ ;

my %upload_names = () ; 

foreach my $system_frames (split(/\|/,$db{$table}{1}{upload_names})) {
	my ($saved_system_id,$frames) = split(/\~/,$system_frames) ;
	my $saved_day_cnt = 0 ;
	foreach my $day_frames (split(/\:/,$frames)) {
		$saved_day_cnt++ ; my $saved_frames_cnt = 0 ; 
		foreach my $all_frames (split(/\;/,$day_frames)) {
			$seen_upload{$all_frames}++ if $all_frames ;
			$saved_frames_cnt++ ;
			$upload_names{$saved_system_id}{$saved_day_cnt}{$saved_frames_cnt} = $all_frames if $all_frames ; 
		}
	}
}

foreach my $saved_system_id (sort {$a <=> $b} keys %upload_names) {
	
	my $system_frames = qq~~ ; my $prev_day = 0 ; 

	foreach my $day_frames (sort {$a <=> $b} keys %{$upload_names{$saved_system_id}}) {
		
		if ($day_frames - $prev_day > 1) {
			for (1 .. $day_frames - $prev_day - 1) {
				$system_frames .= qq~:~ ;
			}
		}
		$prev_day = $day_frames ;
		
		foreach my $frame_cnt (sort {$a <=> $b} keys %{$upload_names{$saved_system_id}{$day_frames}}) {
			if ($ii{uploadid} =~ /_$frame_cnt$/ && $saved_system_id eq $system_id && $day_frames eq $day_cnt) {
				my $file_path = "$htmlpath/uploads/calibration_status_uploads/$ii{event_quote_id}/$upload_names{$saved_system_id}{$day_frames}{$frame_cnt}" ; 
				if (-f $file_path && $seen_upload{$upload_names{$saved_system_id}{$day_frames}{$frame_cnt}} == 1) {
					unlink ("$file_path") or die "unable to delete - $file_path : $!" ;
				}
				$system_frames.= qq~;~ ;
			} else {
				$system_frames .= qq~$upload_names{$saved_system_id}{$day_frames}{$frame_cnt};~ ; 
			}
		}
		$system_frames =~ s/;+$// ;
		$system_frames .= qq~:~ ;
		
	}
	
	$system_frames =~ s/:+$// ;
	
	$i{upload_names} .= qq~$saved_system_id\~$system_frames~ if $system_frames ;
	
	$i{upload_names} .= qq~|~ ;
}

$i{upload_names} =~ s/\|+$// ;

&db_min_upd($table,"event_quote_id='$ii{event_quote_id}'") ;

%i = %ii ;

# $trigger_jquery_raw .= qq~parent.location.reload();~ ;

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

sub uploads_list {

&db_min_ro($table,'1,upload_names',"`event_quote_id`='$id'") ;

$form .= &common_min_forms_start('photo_uploads') ;

my $upload_names_str = qq~~ ;

foreach my $system_frames (split(/\|/,$db{$table}{1}{upload_names})) {
	my ($saved_system_id,$frames) = split(/\~/,$system_frames) ;
	next if $saved_system_id ne $system_id ;
	my $day_cnt_saved = 0 ; 
	foreach my $day_frames (split(/\:/,$frames)) {
		$day_cnt_saved++ ;
		next if $day_cnt_saved ne $day_cnt ; 
		$upload_names_str = $day_frames ;
	}
}

my @upload_names_arr = split(/\;/,$upload_names_str) ;    

for (1 .. 10) {

    $url = '' ;

	my $field = "photo_$_" ;

	my $photo_name = "$upload_names_arr[$_ - 1]" ;

	if ($photo_name && -f "$htmlpath/uploads/calibration_status_uploads/$id/$photo_name") {
		$url = qq~/uploads/calibration_status_uploads/$id/$photo_name~ ;    
	}

    $tindex++ ;
    $link = '' ;
 
	my ($width,$height) = imgsize("$htmlpath$url");
 
	if ($height) {
		$width = 100*($width/$height) ; 
		$height = 100 ; 
	 
		if ($url) {
			$link = qq~<img src="$url" style='width:$width\px;height:$height\px;border:1px solid #ccc;margin:2px;'>~ ;
		}		
	}
	 
	my $attach_col = ($link) ? qq~<a href="$url">$link</a><input type='hidden' name='photo_uploaded_$_' value='$upload_names_arr[$_ - 1]'>~ : qq~<input type="file" name='iattach$field'>~ ;
	my $delete_butt = ($link) ? qq~<a class="btn btn-danger btn-xs" href="javascript:deleteItem('$field','$id');"><i class="glyphicon glyphicon-trash icon-white"></i></a>~ : qq~~ ;
	
    $tbody .= qq~
		<tr>
			<td>$attach_col</td>
			<td>$delete_butt</td>
		</tr>
	~ ;

}

# <table id="incidentuploads" class="table table-striped datatable">
$form .= qq~
	<div class="box-content">
		<table id="incidentuploads" class="table table-striped">
			<thead>
			<tr> 
				<th>Uploads</th> 
				<th>&nbsp;</th>
			</tr>
			</thead>
			<tbody>
				$tbody
			</tbody>
		</table>
	</div>
~	;

# $extra_form_fields .= qq~<input type="hidden" name="id" value="$id">~ ;

$form .= &common_min_forms_end('','photo_uploads','update') ;

$trigger_jquery_raw .= qq~

function deleteItem (uploadid,event_quote_id) {

	BootstrapDialog.confirm({
		title: 'Confirm Delete',
		message: 'Are you sure you want to delete <strong>'+uploadid+'</strong>?',
		type: BootstrapDialog.TYPE_WARNING,
		callback: function(result) {            
			if (result) {
				document.deleteform.event_quote_id.value = event_quote_id ;
				document.deleteform.uploadid.value = uploadid ;
				\$('#delete-form').submit();      
				// parent.location.reload();				
			}
		}
	});
}

~ ; 

# $trigger_jquery .= qq(var oTable = \$('#incidentuploads').dataTable(); oTable.fnSort( [ [1,'desc'] ] );) ;

} #------------------------------------------------------------------------------------------         
              
sub screen1 {

$useropts{'common'}{'css'} .= qq(#incidentuploads .form-control { height:25px;padding:2px 5px;font-size:12px;color:#464545; });

&common_min_alert_type ;

&common_min_footer('id','') ;

&common_min_dialog ;
      
print <<ENDOFTEXT;
$dialog{'common'}{'head'}
    
<div id="content" class="col-lg-12 col-sm-12">
    <!-- content starts -->   
             
	$alert
    $print_top
    
    <div class="row">
        <div class="box col-md-12">
            $form
        </div>
        <!--/span-->
    </div><!--/row-->
</div><!--/row-->
    
</div><!--/fluid-row-->
    
</div><!--/.fluid-container-->

<!-- external javascript -->

<style>body { font-size: 14px; }.control-label { font-size: 14px; }</style>
<link href="$useropts{'css'}/bootstrap-dialog.css" rel='stylesheet'>

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

<script>

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

$trigger_jquery_raw

</script>

<form name="deleteform" id="delete-form" action=""    method="post">
<input type="hidden" name="iaction"			value="delete">
<input type="hidden" name="event_quote_id"	value="">
<input type="hidden" name="uploadid"		value="">
</form>

</body>
</html>
ENDOFTEXT
#

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

sub screen2 {

if (($username eq 'rory') and ($testing)) { return ; }
     
print <<ENDOFTEXT;
<!DOCTYPE html>
<html lang="en">
<head>    
    <meta charset="utf-8">
    <title>Truck Assist Gateway USA</title>
    <script src="$useropts{'bower_components'}/jquery/jquery.min.js"></script>   
</head>
<body>
<script>

\$(function () {
    parent.location.reload();
    parent.BootstrapDialog.closeAll() ;
});

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

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

use db ;
use today ;
use common ;

1;