#!/usr/bin/perl

use strict;
use CGI;

use Opals::Context;
use Opals::Template qw(
    tmpl_read
    tmpl_write
);
use Opals::User qw(
    user_currentUser
);

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

my $cgi = CGI->new;
# $cgi->param('aaa') returns an array of aaa
my $input = $cgi->Vars();
#my $op = $input->{'op'};
my ($permission, $cookieList, $template) = tmpl_read(
    {
        dbh             => $dbh,
        cgi             => $cgi,
        tmplFile        => 'ajax/ill/request.tmpl',
#        reqPermission   => 'reqPermission1|reqPermission2|etc.',
#        op              => $op,
    }
);

# See User.pm for the list of permissions
#if ($permission && $permission->{'reqPermission1'}) {

my ($errCode, $ck, $user) = user_currentUser($dbh, $cgi);
if ($user && $user->{'uid'}) {
    my $sql = <<_SQL_;
insert into opl_studentILL
set     uid = ?,
        zid = ?,
        rid = ?,
        title = ?,
        author = ?,
        pubDate = ?,
        description = ?,
        dRequest = now(),
        dExpiry = now() + interval 4 week,
        responderList = ?
_SQL_

    my @param = (
        $user->{'uid'},
        $input->{'zid'},
        $input->{'rid'},
        $input->{'title'},
        $input->{'author'},
        $input->{'pubDate'},
        $input->{'description'},
        join(',', $cgi->param('responder_lid'))
    );
    $dbh->do($sql, undef, @param);

    $template->param(
        uid         => $user->{'uid'},
#        requestID   => 1,
#        rid         => $input->{'rid'},
    );
}

#}
#else { # input for login form
#    ##########################
#    # Method one: not recommended
#    $template->param(
#        input => [
#            {name => '', value => $,},
#            {name => '', value => $,},
#        ],
#    );
#
#    ##########################
#    # Method two: recommended
#    my @form_input;
#    foreach my $param (keys %{$input}) {
#        push @form_input, {name =>"$param",value => "$input->{$param}"};
#    }
#    $template->param(
#        input=>\@form_input,
#    );
#}

tmpl_write($dbh, $cgi, $cookieList, $template);
