#!/usr/bin/perl

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

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

use CGI::Carp qw(fatalsToBrowser);
use DBI;
use CGI;
use POSIX;

# unless ($username eq 'rory') { print "<<<<<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>>>>>>>" ; exit ; }

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

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

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

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

&today;

if ($iaction eq ''){
    &base_screen ;
    }

if ($iaction eq 'edit'){
    &common_load_params ;
    &get_storage_list ;
    &edit_screen ;
    &screen1;
    }

if ($iaction eq 'save'){
    &common_load_params ;
    &process_storage_for_save ;
    $savetype  = "SAVED" ;
    $viewsaved = 0 ;
    &screen2;
    }

if ($iaction eq 'update'){
    &common_load_params ;
    &check_update_storage ;
    &update_storage(1) ;
    $savetype  = "UPDATED" ;
    &screen2;
    }

if ($iaction eq 'delete'){
    &common_load_params ;
    &delete_storage ;
    $savetype  = "DELETED" ;
    $viewsaved = 1 ;
    &screen2;
    }

exit;

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

sub process_storage_for_save {

@input_array = $q -> param('input_array');

our $batchno = &db_get_max_storage_batch_no ;

foreach (@input_array) {
    $at_least_one_input = 1 ;
    if ($i{storageid}{$_}){
        &update_storage($_) ;
        }
    else
        {
        &insert_storage ; 
        }       
    }
    
unless ($at_least_one_input) { $error = qq(NOTHING SELECTED); &base_screen ; }
       
} #------------------------------------------------------------------------------------------

sub delete_storage {

unless ($i{storageid}) { return ; }

&db_open_upd ;

$sql = qq(DELETE FROM storage WHERE ID = "$i{storageid}" AND HAWB = "$i{hawb}") ;

&common_debug($sql) ;

$sth = $dbh -> do ($sql) or die "could not execute :<BR>$sql<BR>$!" ;

&db_close_conn ;

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

sub check_update_storage {

$input = $q -> param('input_array');

unless ($input) { $error = qq(NOTHING SELECTED); &base_screen ; return ; }

$viewsaved = 0 ;

if (($i{dateout}{1}) and ($i{storageid}{1}) and ($i{waybillno}{1})) { $viewsaved = 1 ; }
    
} #------------------------------------------------------------------------------------------

sub update_storage {

my ($field) = @_ ;

unless ($i{storageid}{$field}) { return ; }

&db_open_upd ;

$sql = qq(UPDATE storage SET
DateOut = "$i{dateout}{$field}",
Remarks = "$i{remarks}{$field}"
WHERE ID = "$i{storageid}{$field}" AND HAWB = "$i{waybillno}{$field}") ;

&common_debug($sql) ;

$sth = $dbh -> do ($sql) or die "could not execute :<BR>$sql<BR>$!" ;

&db_close_conn ;

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

sub insert_storage {

&db_open_upd ;

$sql = qq(INSERT INTO storage (ID,BatchNo,DateCreated,HAWB,DateOut,Remarks) 
VALUES ("","$batchno","$now_ccyy_mm_dd","$i{waybillno}{$_}","$i{dateout}{$_}","$i{remarks}{$_}");) ;
          
&common_debug($sql) ;

$sth = $dbh -> do ($sql) or die "could not execute :<BR>$sql<BR>$!" ;

&db_close_conn ;

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

sub db_get_max_storage_batch_no {

&db_open_ro ;

my $sql = qq(SELECT BatchNo FROM storage ORDER BY BatchNo DESC LIMIT 1) ;

my $sth = $dbh->prepare($sql) ;

$sth -> execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!";
my $max_batch_no_array_ref = $sth->fetchall_arrayref();

$sth->finish();

&db_close_conn ;

my $new_batchno = 1 ;

foreach $row (@$max_batch_no_array_ref) {    
    $batchno     = @$row[0] ;  
    $new_batchno = $batchno ;    
    $new_batchno++ ;
    }
    
return ($new_batchno) ;
    
} #------------------------------------------------------------------------------------------

sub get_storage_list {

if ($iall) { 
    &db_load_all_parcels ;
    &get_db_storage_list(1) ;
    }
elsif ($iboth) { 
    &db_load_all_parcels ;
    &get_db_storage_list(3) ;
    &get_db_waybill_storage_list ;
    }
else
    {
    &db_load_all_parcels ;
    &get_db_storage_list(2) ;
    &get_db_waybill_storage_list ;
    } 

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

sub get_db_waybill_storage_list {

&db_open_ro ;

my $sql = qq(SELECT * FROM waybills WHERE OthSvc1 = 'Storage') ;
# my $sql = qq(SELECT * FROM waybills WHERE OthSvc1 = 'Packaging') ;

my $sth = $dbh->prepare($sql) ;

$sth -> execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!";
my $id_array_ref = $sth->fetchall_arrayref();

$sth->finish();

&db_close_conn ;

foreach $row (@$id_array_ref) { 
    &db_waybills_fields ;
    
    if ($storage{$wb{waybillno}}{$wb{storageno}}) { next ; }
    
    my $checked = '' ;
    
    if ($i{hawb}) { unless ($i{hawb} eq $wb{waybillno}) { next ; } $checked = 'CHECKED' ; }
            
    $r++ ;
    
    if ($i{id}{$wb{waybillno}}) { $hidden_fields_edit = qq(<input type='hidden' name='storageid_$r' value="$i{id}{$wb{waybillno}}">) ; } else { $hidden_fields_edit = '' ; }
                
    my $invno = sprintf("%.0f",($wb{'invno'})) ;
    
    $print_contents = '' ;
    
    if ($contents{$wb{waybillno}}){ &db_package_parcels($wb{waybillno}) ; }
    if ($wb{volmass} > $wb{actmass}) { $chgmass = ceil($wb{volmass}); } else { $chgmass = ceil($wb{actmass}); }    
        
    my $view_wb_link = qq(dlgMdl('$useropts{scripts}/dialog/view_waybill.pl?$wb{waybillno}','HAWB $wb{waybillno} : $wb{client} : $wb{coldate}','','max-dialog');) ;
    $tbody .= qq(<tr><td nowrap>$wb{coldate}</td><td><a href="javascript:$view_wb_link">$wb{waybillno}</a></td><td>$wb{origin}</td><td>$wb{client}</td><td>$print_contents</td><td>$wb{pcs}</td><td>$chgmass</td>) ;
    my $dateout = qq(<div class="input-group controls input-append date dateout" data-date=""><input class='form-control' name="dateout_$r" value="$i{dateout}{$wb{waybillno}}" READONLY><span class="input-group-addon add-on"><span class="glyphicon glyphicon-calendar"></span></span></div>) ;
    $tbody .= qq(<td>$dateout</td><td class="dt-center">$invno</td><td><input type='text' name='remarks_$r' class="form-control" placeholder='Remarks' value="$i{remarks}{$wb{waybillno}}"></td><td><input type="checkbox" name="input_array" $checked value="$r"><input type='hidden' name='waybillno_$r' value='$wb{'waybillno'}'><input type='hidden' name='client_$r' value='$wb{client}'>$hidden_fields_edit</td>) ;
    } 

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

sub get_db_storage_list {

my ($type) = @_ ;

&db_open_ro ;

my $sql = qq(SELECT storage.*,waybills.client,waybills.invno,waybills.coldate,waybills.origin,waybills.pcs,waybills.volmass,waybills.actmass,waybills.othsvc1 FROM storage,waybills WHERE waybills.waybillno = storage.hawb LIMIT 1000) ;

my $sth = $dbh->prepare($sql) ;

$sth -> execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!";
my $id_array_ref = $sth->fetchall_arrayref();

$sth->finish();

&db_close_conn ;

foreach $row (@$id_array_ref) { 
    &db_storage_fields ;
    
    $wb{client}      = @$row[6] ;
    $wb{invno}       = @$row[7] ;
    $wb{coldate}     = @$row[8] ;
    $wb{origin}      = @$row[9] ;
    $wb{pcs}         = @$row[10] ;
    $wb{volmass}     = @$row[11] ;
    $wb{actmass}     = @$row[12] ;
    $wb{othsvc1}     = @$row[13] ;
    
    if (&edit_ifields($st{hawb}))            { next ; }
    if (($i{hawb}) and ($iaction eq 'edit')) { next ; }
    
    if ($type == 2) { $storage{$st{hawb}}{$st{othsvc1}} = 1 ; next ; }
    if ($type == 3) { next ; }
    
    my $invno       = sprintf("%.0f",($wb{invno})) ;
    
    $print_contents = '' ;
    
    if ($contents{$wb{waybillno}}){ &db_package_parcels($wb{waybillno}) ; }
    if ($wb{volmass} > $wb{actmass}) { $chgmass = ceil($wb{volmass}); } else { $chgmass = ceil($wb{actmass}); } 

    my $view_wb_link = qq(dlgMdl('$useropts{scripts}/dialog/view_waybill.pl?$st{hawb}','HAWB $st{hawb} : $wb{client} : $wb{coldate}','','max-dialog');) ;
    $tbody .= qq(<tr><td nowrap>$wb{coldate}</td><td><a href="javascript:$view_wb_link">$st{hawb}</a></td><td>$wb{origin}</td><td>$wb{client}</td><td>$print_contents</td><td class="dt-center">$wb{pcs}</td><td class="dt-center">$chgmass</td>) ;
    $tbody .= qq(<td>$st{dateout}</td><td class="dt-center">$invno</td><td>$st{remarks}</td><td><a class="btn btn-danger btn-xs" href="javascript:deleteStorage('$st{id}','$st{hawb}');"><i class="glyphicon glyphicon-trash icon-white"></i></a></td>) ;
    
    # <a class="btn btn-info btn-xs" href="javascript:editStorage('$st{id}','$st{hawb}');"><i class="glyphicon glyphicon-edit icon-white"></i></a>&nbsp;    
    } 

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

sub edit_ifields {

my ($hawb) = @_ ;

$i{id}{$hawb}                = $st{id}               ;
$i{batchno}{$hawb}           = $st{batchno}          ;
$i{dateout}{$hawb}           = $st{dateout}          ;
$i{remarks}{$hawb}           = $st{remarks}          ; ;

my $incomplete = '' ;

foreach my $p (keys %i) {
    $i{$p}{$hawb} =~ s/0000-00-00//g ;
    unless ($i{$p}{$hawb}) { $incomplete = 1 ;}
    }
    
return($incomplete) ;

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

sub base_screen {

&get_storage_list; 
&save_screen; 
&screen1;

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

sub save_screen {

$hidden_action = 'save' ;

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

sub edit_screen {

$hidden_action = 'update' ;

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

sub screen1 {

if ($error)  { $alert = qq(<div class="alert alert-danger" role="alert"><i class='glyphicon glyphicon-exclamation-sign'></i> $error !</div>) ; }
if ($isaved) { $alert = qq(<div class="alert alert-success" role="alert"><i class="glyphicon glyphicon-ok"></i> STORAGE SUCCESSFULLY <strong>$isaved</strong> !</div>) ; }

my $allbutt = qq(<a class="btn btn-default btn-xs" href="javascript:showBoth();"><i class="glyphicon glyphicon-zoom-in"></i>&nbsp;All</a>) ;
my $incbutt = qq(<a class="btn btn-default btn-xs" href="/storage"><i class="glyphicon glyphicon-zoom-in"></i>&nbsp;Incomplete</a>) ;
my $combutt = qq(<a class="btn btn-default btn-xs" href="javascript:showAll();"><i class="glyphicon glyphicon-zoom-in"></i>&nbsp;Completed</a>) ;

if ($iall) { 
    $table_title = qq(: Complete) ; 
    $view_butt = qq($incbutt&nbsp;$allbutt); 
    } 
elsif ($iboth) { 
    $table_title = qq(: All) ; 
    $view_butt = qq($combutt&nbsp;$incbutt); 
    } 
elsif ($iaction eq 'edit') { 
    $table_title = qq(: Edit) ; 
    $view_butt = qq($combutt&nbsp;$incbutt); 
    } 
else 
    { 
    $table_title = qq(: Incomplete); 
    $view_butt = qq($combutt&nbsp;$allbutt); 
    }

$print_buttons = qq(<div class="row"><div class="col-md-12"><button type="submit" class="btn btn-primary">Save</button>&nbsp;<button type="button" class="btn btn-default" onclick="history.go(-1);">Back</button></div></div><div class="row"><div class="col-md-12">&nbsp;</div></div>) ;

$trigger_jquery_raw .= qq(\$('#storagelist').dataTable({
        "iDisplayLength": -1,
        "aLengthMenu": [[25, 50, 100, -1], [25, 50, 100, "All"]],
        "sDom": "<'row'<'col-md-6'l><'col-md-6'f>r>t<'row'<'col-md-12'i><'col-md-12 center-block'p>>",
        "sPaginationType": "bootstrap",
        "oLanguage": {
            "sLengthMenu": "_MENU_ records per page"
        }
    });
    ) ;
    
require st_list ;
exit ;

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

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>

\$(document).ready(function(){ \$('#storage-form').submit(); })

</script>
</body>

<form role="form" name="storageform" id="storage-form" method="post" action="/storage">
<input type="hidden" name="iaction"          value="">
<input type="hidden" name="iall"             value="$viewsaved">
<input type="hidden" name="isaved"           value="$savetype">
</form>

</html>
ENDOFTEXT
#

exit ;

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

use db ;
use today ;
use common ;

1;