#!/usr/bin/perl

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

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

use CGI::Carp qw(fatalsToBrowser);
use CGI;
use Mail::Sendmail;
use Fcntl qw(:flock);
use File::Copy;
use File::Basename;
use Date::Calc qw(:all);
use Excel::Writer::XLSX;

&today;

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

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

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

# our $debug = 1 ;
our $double_box_layout = 1 ; # box on the right layout included

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

&page_opts ;

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

print "Content-type: text/html\n\n";
	
our $srchscr   = 0 ;
our $fnsortcol = 0 ;
our $redirtype = 'search' ;
    
&common_min_action;

exit;

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

sub validate {

# called from common_min_action

# my $exists   = '' ;

# &db_min_ro($table,'*',"name='$i{name}'",'','') ;

# foreach my $id (keys %{$db{$table}}) {
    # if ($db{$table}{$id}{name} eq $i{name}) {
		# $exists = 1 ;
		# }
	# }
	
# if ($exists) {
    # $alert = &common_min_alert('warning',"NAME ALREADY EXISTS!",'ok') ;
	# %col_name = ();
    # # &add_screen;
    # # &screen1;
	# &common_min_add_screen;
    # &common_min_screen1;
    # }

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

sub insert {

&add_db_fields ;

$i{last_edited_by} = $userid ; 
$i{user_id} = $userid ;

$i{id} = &db_min_get_max($table,'id') ;

&val_check ;

$i{date_time}    = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ;
$i{last_updated} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ;

&common_upload_files("documents/$i{id}") ;
&process_upload_ifields;

&db_min_insert($table) ;

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

sub update {

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

&edit_db_fields ;

if ($userid) { $i{last_edited_by} = $userid ; }

&val_check ;

$i{last_updated} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ;

&common_upload_files("documents/$i{id}") ;
&process_upload_ifields;

&db_min_upd($table,"id='$i{id}'") ;

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

sub val_check {
	
unless ($i{quote_id})  { $i{quote_id} = '0' ; }
	
} #------------------------------------------------------------------------------------------

sub report_ifields {
	
# &db_open_ro ;
    # our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it
	# &load_search_vars ;
	# $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it
# &db_close_conn ;
	
# if ($i{document_id}) {
    # push @report_sql, "(`id` = '$i{document_id}')" ;
    # push @report_results, "document = $document_name{$i{document_id}}" ;
    # $xlsreportname .= '-' . $i{document_id} ;
	# our $acc_id_sql_where = "`document_id`='$i{document_id}'"
	# }
	
if ($i{date_added_from} and $i{date_added_to}) { # check dates
    my $date_added_from_check = $i{date_added_from} ;
       $date_added_from_check =~ s/\-//g ;
    my $date_added_to_check = $i{date_added_to} ;
       $date_added_to_check =~ s/\-//g ;
    if ($date_added_from_check > $date_added_to_check) { $error = qq(DOCUMENTS FROM ($i{date_added_from}) > DOCUMENTS TO ($i{date_added_to})); &report_screen; }
    }
    
if ($i{date_added_from}) {
    push @report_sql, "(`date_time` >= '$i{date_added_from} 00:00:00')" ;
    push @report_results, "date_time >= $i{date_added_from}" ;
    }

if ($i{date_added_to}) {
    push @report_sql, "(`date_time` <= '$i{date_added_to} 23:59:59')" ;
    push @report_results, "date_time <= $i{date_added_to}" ;
    }
	
$report_results_msg = uc join(', ', @report_results) ;

unless ($report_results_msg) { $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER); &report_screen; } else { $isaved = qq(SELECT WHERE $report_results_msg) ; }
 
} #------------------------------------------------------------------------------------------

sub load_search_vars {

# &db_min_ro('document','id,name','','','') ;
# foreach my $id (keys %{$db{document}}) { $document_name{$id} = $db{document}{$id}{name} ; }

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

sub process_upload_ifields {

foreach (keys %uploads_file) { $i{$_} = $uploads_file{$_} ; $ignore{$_} = '' ; }

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

sub list_screen {

my $srch_where_sql = join(' AND ', @report_sql) ;
    
our @sql_col_display = ("id","date_time","notes","quote_id","client_id","last_edited_by","last_updated","") ;

&report_xls_export_header("Documents$xlsreportname",'documents') ;

&db_open_ro ;
    our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it
	&load_list_vars($srch_where_sql) ;
	$db_ignore_open_close = 0 ; # do one open and one close instead of repeating it
&db_close_conn ;

foreach my $id (sort {$b <=> $a} keys %{$db{$table}}) {
    
	# if (($i{active} == 1) and ($document_id_in_use_for_devices{$id} < 1)) { next ; } # Active with devices
	# if (($i{active} == 2) and ($document_id_in_use_for_devices{$id} > 0)) { next ; } # Active without devices
	
	$print_tbody .= qq(<tr>) ;
	
	$xlscol=0;
	
	foreach (@sql_col_display) { 
		unless ($_) { next ; } # blank for the buttons column
        my $val = $db{$table}{$id}{$_} ;
		my $align = '' ;
		
		# my $format = '' ; 
		
		if ($_ eq 'last_edited_by') { $val = $user_name{$val}      ; }
		if ($_ eq 'client_id')      { $val = $customers_name{$val} ; }
		if ($_ eq 'quote_id')       { $val = $val ? $val : '' ; }
		
        &report_xls_export_process_cell('','',$val) ; # ------------------------------------------------------------------------- HTML AFTER
		$xlscol++; 
		
		# my $green_tick  = qq~<span style="display:none;">2</span><span class="label label-success"><i class="glyphicon glyphicon-ok"></i></span>~ ;
		# my $orange_tick = qq~<span style="display:none;">1</span><span class="label label-warning"><i class="glyphicon glyphicon-ok"></i></span>~ ;
		# my $red_tick    = qq~<span style="display:none;">0</span><span class="label label-danger"><i class="glyphicon glyphicon-ok"></i></span>~ ;
		my $center = qq~ class="dt-center"~ ;
		
		# if ($_ eq 'active') { if ($val == 1) { $val = &set_tick('green', '') ; } else { $val = &set_tick('red', '') ; } $align = $center ; }
		
		$print_tbody .= qq(<td $align>$val</td>) ;  
        }
	
	my $delete_butt = '' ; my $edit_butt = '' ;	
	
	if ($useropts{boss}{$username} or $useropts{super}{$username}) {
		$edit_butt   = qq(<a class="btn btn-info btn-xs" href="javascript:editMinItem('$id');"><i class="glyphicon glyphicon-edit icon-white"></i></a>) ;
		# $delete_butt = qq(<a class="btn btn-danger btn-xs" href="javascript:deleteMinItem('$db{$table}{$id}{document_nr}','$id')"><i class="glyphicon glyphicon-trash icon-white"></i></a>) ;
		}
        
    # &common_debug("$id : $document_id_in_use_for_devices{$id}");
        
    # if ($document_id_in_use_for_devices{$id}) { $delete_butt = '' ; }
		
	$print_tbody .= qq(<td nowrap>&nbsp;$edit_butt&nbsp;$delete_butt</td></tr>) ;
    $xlsrow++ ;
	}
	
&report_xls_export_footer('L',15,'documents') ;
	
$fnsortcol = 8 ; # order by ol devices col

$print_more_boxes .= qq(<br><button type="button" class="btn btn-default" onclick="history.go(-1);">Back</button>) ;
	
&common_min_extra_crumb("search-$lcpage\s","Search Screen") ;
	
} #------------------------------------------------------------------------------------------

sub set_tick {
	
my ($color,$tooltip) = @_ ;
	
$tick{green}  = qq~<span style="display:none;">2</span><span class="label label-success"><i $tooltip class="glyphicon glyphicon-ok"></i></span>~ ;
$tick{orange} = qq~<span style="display:none;">1</span><span class="label label-warning"><i $tooltip class="glyphicon glyphicon-ok"></i></span>~ ;
$tick{red}    = qq~<span style="display:none;">0</span><span class="label label-danger"><i $tooltip class="glyphicon glyphicon-ok"></i></span>~ ;

return ($tick{$color}) ;
		
} #------------------------------------------------------------------------------------------

sub load_list_vars {
	
my ($where) = @_ ;
	
&db_min_ro('users','*','','','') ;
foreach my $id (keys %{$db{users}}) { $user_name{$id} = $db{users}{$id}{name} ; }

&db_min_ro('customers','*','','','') ;
foreach my $id (keys %{$db{customers}}) { $customers_name{$id} = $db{customers}{$id}{name} ; }

# &db_min_ro('device_type','*','','','') ;
# foreach my $id (keys %{$db{device_type}}) { 
	# $is_mdvr{$id} = $db{device_type}{$id}{mdvr} ;
	# $device_name{$id} = $db{device_type}{$id}{name} ; 
	# }
	
# &db_min_ro('risk_profile_types','*','','','') ;
# foreach my $id (keys %{$db{risk_profile_types}}) { $risk_profile_type{$id} = $db{risk_profile_types}{$id}{name} ; }  # document hash

# &db_min_ro('protocol_actions','*',$acc_id_sql_where,'','') ;
# foreach my $id (keys %{$db{protocol_actions}}) { 
	# my $acc_id   = $db{protocol_actions}{$id}{document_id} ;
	# my $max      = $db{protocol_actions}{$id}{max} ;
	# my $show_max = '' ; if ($max) { $show_max = " > $max" ; }
	
	# $protocol_action{$acc_id} .= "$risk_profile_type{$db{protocol_actions}{$id}{risk_profile_type_id}}$show_max<br>" ; 
	# }

# &db_min_ro('device','id,document_id,online,type_id',$acc_id_sql_where,'','') ;
# foreach my $id (keys %{$db{device}}) { 
	# $document_id_in_use_for_devices{$db{device}{$id}{document_id}}++ ; 
	
	# if ($db{device}{$id}{online}==1) {
		# $document_online_devices{$db{device}{$id}{document_id}}++ ; 
		# }
		
	# my $dev_nam = $device_name{$db{device}{$id}{type_id}} ;
	
	# $cnt_dev_typ{$db{device}{$id}{document_id}}{$dev_nam}++ ;		
	# }
	
&db_min_ro($table,'*',$where,'','') ;

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

sub thead {

&common_min_thead ;
    
} #-------------------------------------------------------------------------------

sub sort_fields {

$sort_field{1}  = 'title' ; 
$sort_field{2}  = 'client_id' ; 
$sort_field{3}  = 'quote_id' ; 
$sort_field{4}  = 'notes' ;

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

sub hidden_db_fields {

$ignore{iaction} = 1 ;

for (1 .. 10) { $ignore{"document_$_"} = 1 ; $ignore{"iattachdocument_$_"} = 1 ; }

$rquired{title} = 1 ;
$textarea{notes} = 1 ; $textarea_height{notes} = 250 ;

$hidden{last_updated} = 2 ;
$hidden{last_edited_by} = 2 ;
$hidden{date_time} = 2 ;
$hidden{user_id} = 2 ;

&sort_fields;

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

sub add_db_fields {

&hidden_db_fields ;

$hidden{id} = 2 ;

# $required{document_nr} = 1 ;
# $textarea{notes} = 1 ;

# $datepicker{date_time} = 1 ;
# $datepicker{date_delivered} = 1 ;

if ($iaction eq 'add'){ &build_boxes_add ; } # can't be in add_screen, only works if here

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

sub edit_db_fields {

&hidden_db_fields ;

$ignore{date_time} = 1 ;
$ignore{user_id} = 1 ;
# $ignore{document_nr} = 1 ;
$ignore{last_updated} = 1 ;

# $info_glyph_tooltip{object_recognition} = qq(<i style="margin-top:-3px" data-toggle="tooltip" data-placement="right" data-title="Set to 'Yes' to enable Object Recognition for this client!" class="glyphicons glyphicons-info-sign blue"></i>) ;
$hidden{id} = 1 ; # 1 = bypass for db update

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

sub select_opts {

my ($id) = @_ ;

&db_open_ro ;
    our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it
	&common_min_select_opts('client_id','customers','name',$db{$table}{$id}{client_id},1) ;
	&common_min_select_opts('quote_id','quotes','heading',$db{$table}{$id}{quote_id},'') ;
	$db_ignore_open_close = 0 ; # do one open and one close instead of repeating it
&db_close_conn ;

# $trigger_jquery_raw .= qq(
    # //gallery delete
    # \$('.thumbnails').on('click', '.gallery-delete', function (e) {
        # e.preventDefault();
        # // alert(\$(this).parents('.thumbnail').attr('id'));
        # var imgid = \$(this).parents('.thumbnail').attr('id') ;
        # var thumb = \$(this).parents('.thumbnail');
        # BootstrapDialog.confirm({
        # title: 'Confirm Delete',
        # message: 'Are you sure you want to delete it?',
        # type: BootstrapDialog.TYPE_WARNING,
        # callback: function(result) {            
            # if(result) {
                # var url = "$useropts{scripts}/get/get_db_delete_upload_common.pl?$i{id}&documents/$i{id}&document&"+imgid ; 
                # // alert(url);
                # \$.get(url);
                # thumb.fadeOut();
                # location.reload();
                # }
            # }
        # });
        
    # });
    
    # //gallery edit
    # \$('.thumbnails').on('click', '.gallery-edit', function (e) {
        # e.preventDefault();
        # //get image id
        # alert('Delete document and re-upload!');
        # //alert(\$(this).parents('.thumbnail').attr('id'));
        # //dlgMdl('/scripts/dialog/uploads.pl?$i{id}&document&'+\$(this).parents('.thumbnail').attr('id'),'Document Uploads','','medium-dialog');
    # });
    # );

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

sub add_screen {

# called from common_add_screen

# if ($user_type eq 'track_users') {	
	# $db{$table}{''}{document_id} = $client_id ; # set for input box
    # }

&select_opts('') ;

# &build_boxes_add ; # can't do this here

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

sub build_boxes_add {

$print_box_content_rows .= &common_min_forms_start($table) ;

$print_box_content_rows .= qq(<div class='row'><div class='col-md-6'>) ;
$print_box_content_rows .= &common_min_box_top('user',"&nbsp;&nbsp;Document",$box_main_bg) ;  
# $print_box_content_rows .= &common_add_form($table,'',3,9,1,1) ;
$print_box_content_rows .= &common_min_add_form($table,'save',3,9,1,1) ;
$print_box_content_rows .= &common_min_box_foot ;
$print_box_content_rows .= qq(</div><div class='col-md-6'>) ;

&build_boxes_right;

$print_box_content_rows .= qq(</div></div>) ;

$print_box_content_rows .= &common_min_forms_end('',$table,'save') ;

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

sub edit_screen {

our ($lcol,$fcol) = &common_min_columns($label_col,$field_col) ;

# $selected{warranty_period}{$db{$table}{$id}{warranty_period}} = 'SELECTED';

&select_opts($i{id}) ;

&build_boxes_edit($i{id}) ;   

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

sub build_boxes_edit {

my ($id) = @_ ;

$print_box_content_rows  .= &common_min_forms_start($table) ;
$print_box_content_rows  .= qq(<div class='row'><div class='col-md-6'>) ;
$print_box_content_rows  .= &common_min_box_top('user',"&nbsp;&nbsp;Document : $db{$table}{$id}{id}",$box_main_bg) ;  
# $print_box_content_rows .= &common_edit_form($id,$table,'',3,9,1,1) ;
$print_box_content_rows  .= &common_min_edit_form($i{id},$table,'update',3,9,1,1) ;
$print_box_content_rows  .= &common_min_box_foot ;
$print_box_content_rows  .= qq(</div><div class='col-md-6'>) ;   

&build_boxes_right($id);

$print_box_content_rows  .= qq(</div></div>) ;

$print_box_content_rows  .= &common_min_forms_end($id,$table,'update',$skip) ;

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

sub build_boxes_right {

my ($id) = @_ ;

my $box_icon = '' ;

$print_box_content_rows .= &common_min_box_top('picture','Document Upload',$box_right_bg,$box_icon) ;

$print_box_content_rows .= qq(<div class="row"><div class="col-md-12">&nbsp;</div></div><div class="row">);

for (1 .. 10) {
	# $document_uploads = &get_uploads($id,"document_$_") ;
	$document_uploads = &common_get_field_uploads($id,"document_$_",'client_id') ;
	if ($document_uploads) {
		$print_box_content_rows .= qq~<div class="col-md-6" id="documents">$document_uploads</div>~; 
		}
	else
		{
		$print_box_content_rows .= qq~
			<div class="col-md-6">
				<div class="form-group">
					<label for="imageInputFile">Attach Document $_</label>
					<input type="file" id="imageInputFile" name='iattachdocument_$_' tabindex='$tindex'>
					<p class="help-block">Upload file from PC.</p>
				</div>
			</div>
			~;		
		}
	}	

$print_box_content_rows .= qq~</div>~;
    
$print_box_content_rows .= &common_min_box_foot ;
                          
} #----------------------------------------------------------------------------------------

# sub get_uploads {

# my ($id,$type) = @_ ;

# unless ($id and $type) { return() ; }

# my $gallery = '' ; my %gallery = () ;

# my $field = $type ;
# if ($db{$table}{$id}{$field}){
    # $tooltip = qq(data-toggle="tooltip" data-placement="top" title="$type" data-original-title="$type") ;
    # $gallery{$type} .= qq(<li id="$type-$db{$table}{$id}{$field}" class="thumbnail" $tooltip>
            # <a style="background:url(/uploads/documents/$db{$table}{$id}{client_id}/$db{$table}{$id}{$field})" title="$type" href="/uploads/documents/$db{$table}{$id}{client_id}/$db{$table}{$id}{$field}"><img class="grayscale" src="/uploads/documents/$db{$table}{$id}{client_id}/$db{$table}{$id}{$field}" alt="$type" style="position:relative;max-height:100%;"></a>
        # </li>) ;
    # }

# if ($gallery{$type}) { $gallery = '<ul class="thumbnails gallery">' . $gallery{$type} . '</ul>' ; }

# return ($gallery) ;

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

sub page_opts {

our $glyphicon = 'list' ;
our $lcpage    = 'document' ;

&common_page_name ;
   
our $table     = 'documents' ;

$page_title    = 'Document' ;

&common_min_add_extras ;

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

sub report_screen {

our $lcol = 3 ;
our $fcol = 5 ;

my ($set_year,$set_month,$set_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,-42); # 6 weeks back

$set_month  = sprintf("%02s", $set_month) ;
$set_day    = sprintf("%02s", $set_day) ;

# my $set_ccyy_dd_mm = $set_year . '-' . $set_month . '-' . $set_day ;

$print_box_content_rows .= &common_min_forms_start('report') ;

&db_open_ro ;
    our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it
	# &common_min_select_opts('document_id','documents','name',$i{document_id},'') ;
	&common_min_select_opts('client_id','customers','name','','') ;
	&common_min_select_opts('quote_id','quotes','heading','','') ;
	$db_ignore_open_close = 0 ; # do one open and one close instead of repeating it
&db_close_conn ;

# $print_box_content_rows .= &common_min_form_select('document_id',$i{document_id}) ; 
$print_box_content_rows .= &common_min_form_select('client_id',$i{client_id}) ; 
$print_box_content_rows .= &common_min_form_datepicker('date_added_from','') ;
$print_box_content_rows .= &common_min_form_datepicker('date_added_to','') ;
	
# $print_box_content_rows .= &common_min_form_input('active',$i{active}) ;

# $opts{active} = qq(<option value=""></option>
# <option $selected{active}{active} value="active">Active</option>
# <option $selected{active}{inactive} value="inactive">Inactive</option>) ; 
# $print_box_content_rows .= &common_min_form_select('active','','',1,'') ; 
 
$print_box_content_rows .= &common_min_forms_end('','','report') ;

&common_min_search_screen ;

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

# sub send_email {
	
# my ($email_subject,$email_msg) = @_ ;

# unless ($email_msg) { return ; }

# my %mail = () ;

# my $to  = 'duvan@kre8it.co.za' ;
# my $cc  = 'rory@kre8it.co.za' ;
        
# %mail = (
         # smtp    => 'localhost',
         # From    => 'TruckAssist IT <it@truckassist.co.za>',
         # To      => $to,
		 # Cc      => $cc,
         # Subject => $email_subject
         # );

# $mail{body} = <<END_OF_BODY;

# $email_msg

# END_OF_BODY

# sendmail(%mail) ;

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

use common ;
use report ;
use xlsxcreator ;
use today ;

1;