#!/usr/bin/perl

#use utf8;
use strict;
use CGI;

use Opals::Context;
use Opals::Template qw(
    tmpl_read
    tmpl_write
);
use Opals::User qw(
    user_update
    user_balance
    user_getInformationById
    user_LoadCategory
    user_list
    user_list_ext
    user_browse_ext

    user_permission
    user_listPermission
    user_StrPermission
    user_currentUser
);
use Opals::Circulation qw(
    circ_userListLoan
);
use Opals::Search qw(
    srch_searchRecord
);
use Opals::Date qw(
    date_parse
    date_today
    date_text
);

use Opals::Constant;

my $dbh   = Opals::Context->dbh();
END { $dbh->disconnect(); }

my $cgi = CGI->new;
my ($permission, $cookie, $template) = tmpl_read(
        {
            dbh             => $dbh,
            cgi             => $cgi,
            tmplFile        => 'user/info.tmpl',
            reqPermission   => 'user_edit',
        }
);

my $input = $cgi->Vars();
my $quickEntry = $input->{'qk'} ;

my $errUser = 0;
my ($userInfo, $guardian);

#----- Get uid
my @cookieList = (@$cookie);
my $FromCookie = 0;

my $uInput = $cgi->param('uInput');
my $uid = -1;
if ($quickEntry && $quickEntry eq '1') {
    $template->param(quickBorrowerEntry => 1);
}

if($quickEntry && $quickEntry eq '1'){   
    # Tue, Nov 11, 2008 @ 14:31:04 EST
    $errUser = 1;
    my @uList;
    if ($uInput eq '*' || $uInput eq '' ) {
        @uList = user_browse_ext($dbh, '',1); # Tue, Nov 18, 2008 @ 09:33:48 EST
    }
    else{
        @uList = user_list_ext($dbh, $uInput,'',1);
        $template->param(quickBorrowerEntry => 0); # Force go to edit user page instead of quick entry page
    }    
    if (scalar(@uList) == 0) { # no user has this name/barcode
        $template->param(userNotMatch  => 1, uInput => $uInput );
    }
    else { # list of users 
        $template->param(uList => \@uList);
    }
}
else{
    if ($uInput) {
        $errUser = 1;
        my @uList;
        @uList = user_list($dbh, $uInput);
        if (scalar(@uList) == 1) { # get only one user having this name
            $uid = $uList[0]->{'uid'};
            push @cookieList, $cgi->cookie(
                    -name       => 'borrower',
                    -value      => $uid,
            );
            $errUser = 0;
        }
        elsif (scalar(@uList) == 0) { # no user has this name/barcode
            $template->param(userNotMatch  => 1, uInput => $uInput );
        }
        else { # list of users 
            $template->param(uList => \@uList);
        }

    }
    else{
        # get user from selected item in list or from cookie
        if ($input->{'InputFromList'}) {
            $uid = $input->{'InputFromList'};
            push @cookieList, $cgi->cookie(
                    -name       => 'borrower',
                    -value      => $uid,
            );
        }
        else {
            if ($input->{'hiddenid'}) {
                $uid = $input->{'hiddenid'};
            }
            elsif(!$quickEntry) {
                $uid = $cgi->cookie('borrower');
                $FromCookie = 1;
            }
        }            
    }

}


if ($uid>=0 && !$errUser) {
    ($userInfo, $guardian) = user_getInformationById($dbh, $uid);

    # if any input from user cause an invalid uid, it is an error
    if (!$userInfo->{'uid'}) {
        if ( !$FromCookie ) { $template->param(InvalidUser => 1); }
        $errUser = 1;
    }
}
#----- End get uid

my %posOf = user_listPermission();
    
if ($uid>=0 && !$errUser) {
    $input->{'uid'} = $uid;
    
    if ($input->{'op'} eq 'save') {
        my ($errCode, $myCookie, $user) = user_currentUser($dbh, $cgi);
        my $editPerm = user_permission($dbh, $userInfo->{'uid'});
        my $authorPerm = user_permission($dbh, $user->{'uid'});

        my $bCanDoSave = 1;
        my $userPerm = user_StrPermission($input->{'permission'});

        foreach my $perm (keys %posOf) {
            # Check if author try to edit a permission he don't have
            if (($userPerm->{$perm} ne $editPerm->{$perm}) && 
                !$authorPerm->{$perm}) { 
                    $bCanDoSave = 0; 
                } 
        }

        if ($bCanDoSave) {
            if (!$authorPerm->{'pref_edit'}) {
                if ($editPerm->{'pref_edit'}) {
                    # Don't allow a regular user try to delete admin
                    if ($input->{'status'} == USER_INACTIVE) {
                        $bCanDoSave = 0;
                    }

                    # Don't allow a regular user change admin's permission
                    foreach my $perm (keys %posOf) {
                        if ($userPerm->{$perm} ne $editPerm->{$perm}) {
                            $bCanDoSave = 0;
                        }
                    }
                }
            }
        }
        
        if ($bCanDoSave) {
            my $bCanNotInact = 0;
            if ($userInfo->{'status'} != USER_INACTIVE && 
                $input->{'status'} == USER_INACTIVE) {
                my $loanList = 
                    GetItemsLoaned($template, $userInfo->{'uid'});

                my $balance = user_balance($dbh, $userInfo->{'uid'});
                $bCanNotInact = ( @$loanList || $balance >0 );
                $template->param(CanNotDelete => $bCanNotInact);
                if ($bCanNotInact) {
                    $template->param(balance => $balance);
                    $template->param(BooksAndFine => @$loanList && $balance);
                }
            }

            if (!$bCanNotInact) {
                if (user_update($dbh, $input,$cgi)) {
                    $template->param(successEdit => 1);
                }
                else {
                    $template->param(errorUpdate => 1);
                }
            }
            else {
                $template->param(hiddenid => $uid);
                $template->param($userInfo);
                for (my $i = 0; $i < 3; $i++) {
                    $guardian->[$i]{'order'} = $i;
                    $guardian->[$i]{'tab'} = $i + 40;
                }
                $template->param(guardian => $guardian);
                if ($userInfo->{'status'} == 0) {
                    $template->param( inactive => 1 );
                }
                elsif ($userInfo->{'status'} == 1) {
                    $template->param( active => 1 );
                }
                elsif ($userInfo->{'status'} == 2) {
                    $template->param( block => 2 );
                }
          }
        }
        else {
            $template->param(errorPermission => 1);
        }
        
        # Not real error, but to turn on the dialog enter username
        $template->param(errUser => 1);
    }
    else {
        #--- Get guardian's information
        if ($userInfo->{'status'} == 0) {
            $template->param( inactive => 1 );
        }
        elsif ($userInfo->{'status'} == 1) {
            $template->param( active => 1 );
        }
        elsif ($userInfo->{'status'} == 2) {
            $template->param( block => 2 );
        }
    
        $template->param($userInfo);

        for (my $i = 0; $i < 3; $i++) {
            $guardian->[$i]{'order'} = $i;
            $guardian->[$i]{'tab'} = $i + 40;
        }
        
        $template->param(guardian => $guardian);
        
        # Load borrower types
        my @brwrtype = user_LoadCategory($dbh);
        my $arrSize = @brwrtype;
         
        for (my $i=0; $i < $arrSize; $i++) {
            my %hash = $brwrtype[$i];
            $brwrtype[$i]->{'VarSel'} = ($userInfo->{'categorycode'} == $brwrtype[$i]->{'catid'} ? 1 : 0)
        }
        $template->param( category => \@brwrtype );

        # Load borrower permissions
        my ($errCode, $myCookie, $user) = user_currentUser($dbh, $cgi);
        my $authorPerm = user_permission($dbh, $user->{'uid'});
        my $editPerm = user_permission($dbh, $userInfo->{'uid'});

        foreach my $perm (keys %posOf) {
            if ($authorPerm->{$perm} && !$editPerm->{'pref_edit'}) {
                $template->param($perm => 1);
            }
        }
        
        $template->param(hiddenid => $uid);
    }

    my $country = Opals::Context->preference('country');
    if ($country =~ m/us/i) {
        $template->param(country_us => 1);
    }   # currently, only USA/Canadian address supported.
}
else {
    $template->param(errUser => 1);
}

if ($template->param('hiddenid')) { 
    $template->param(checkid => 1); 
}

$template->param(userEdit => 1);
tmpl_write($dbh, $cgi, \@cookieList, $template);


#-------------------------------------------------------
sub GetItemsLoaned {
    my ($template, $uid) = @_;
        
    # Get books in loan from user
    my $loanList = circ_userListLoan($dbh, $uid);
    my $bZebraServerDown = 0;
    foreach my $loan (@$loanList) {
        $loan->{'dateLoan'} = date_text($loan->{'dateLoan'}, 0);
        $loan->{'dateDue'}  = date_text($loan->{'dateDue'}, 0);

        my $pqf = "\@attr 1=5000 $loan->{'barcode'}";
        my ($resultSize, $result) = srch_searchRecord($dbh, 0, 'b', $pqf, $ENV{'Z_INDEX_BASE'}, 1);
        if ($result) {
            $loan->{'rid'}     = $result->[0]->{'rid'};
            $loan->{'title'}   = $result->[0]->{'title'};
            $loan->{'author'}  = $result->[0]->{'author'};
            $loan->{'pubName'} = $result->[0]->{'pubName'};
            $loan->{'pubDate'} = $result->[0]->{'pubDate'};
        }
        else {
            $bZebraServerDown = 1;            
        }
   }

   $template->param(zebraServerDown => $bZebraServerDown);
   $template->param(LoanList => \@$loanList);
   $template->param(NumOfBooks => scalar(@$loanList));

   return \@$loanList;
}

