#!/usr/bin/perl

#use utf8;
use strict;
use CGI;
use JSON;

use Opals::Context;
use POSIX qw(
    floor
    ceil
);

use Time::localtime;

use Opals::Template qw(
    tmpl_read
    tmpl_write
    tmpl_rangedPageList
);

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

my $tm = localtime;
my $todayStr = sprintf("%04d-%02d-%02d", $tm->year+1900, ($tm->mon)+1, $tm->mday);

my $cgi = CGI->new;
my $input = $cgi->Vars();
my ($permission, $cookie, $template) = tmpl_read(
    {
        dbh             => $dbh,
        cgi             => $cgi,
        tmplFile        => 'eqmnt/report/historyByRId.tmpl',
    }
);

    my $rid = $input->{'rid'};
    my $history = to_json(_getHistoryByRId($dbh,$rid),{pretty=>1});

    $template->param (
        history     => $history,
    );

tmpl_write($dbh, $cgi, $cookie, $template);
$dbh->disconnect();
    
sub _getHistoryByRId{

    my ($dbh, $rid) = @_;
    my $sql = "select logId from eq_records where rid = $rid";

    my $logId = $dbh->selectrow_array($sql);
   
    my $sth = $dbh->prepare(<<_SQL_);
select id,action,uid ,datetime, concat(u.firstname, " " ,u.lastname) as name  
from log l  inner join opl_user u using(uid)
where (l.module='eqmnt' or (l.module='library' && l.action in ('login','logout')))  
&& l.id in ($logId)
order by l.uid,l.datetime,l.action,l.sessionid
_SQL_
    
    $sth->execute();
    my @list = ();
    while (my $rec = $sth->fetchrow_hashref()){
        push @list, $rec;
    }
    return \@list;

}




