#!/usr/bin/perl

#use utf8;
use strict;

use Encode;
use LWP::UserAgent;
use HTTP::Request::Common;

use CGI;
use JSON;

use Opals::Context;
use Opals::Constant;
use Time::localtime;
use Opals::Equipment qw(

    eq_record_findByRId


);
use Opals::Eq_Search qw(
      
    eq_category_getList
    eq_category_getListById

);

use Opals::Template qw(
    tmpl_read
    tmpl_write
);

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

my $cgi = CGI->new;
my $input = $cgi->Vars();

my ($permission, $cookieList, $template) = tmpl_read(
    {
        dbh             => $dbh,
        cgi             => $cgi,
        tmplFile        => 'eqmnt/ajax/report/getHistoryByRId.tmpl',
        #reqPermission   => 'eq_record_edit',
    }
);

       
my $rid = $input->{'rid'};

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

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


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;
    }
    $sth->finish;
    return \@list;

}


