#!/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::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/getHistory.tmpl',
        #reqPermission   => 'eq_record_edit',
    }
);

my $data = $input->{'data'};
my $dateFrom = $input->{'d1'};
my $dateTo = $input->{'d2'};

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

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

sub _getHistory{

    my ($dbh) = @_;
    my $sth = $dbh->prepare(<<_STH_);
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'  && l.action not in ('search','listEditor')) ||
    (l.module='library' && l.action in ('login','logout')))  
&& datetime between ('$dateFrom 00:00:00') and ('$dateTo 23:59:59') 
order by l.uid,l.datetime,l.action,l.sessionid
_STH_

    $sth->execute();
    my @list = ();
    while (my $rec = $sth->fetchrow_hashref()){
        push @list, $rec;
    }
    return \@list;
}

