#!/usr/bin/perl

use strict;
use warnings;

use lib '/home/raj/perl5/lib/perl5';

# use CGI::Carp qw(fatalsToBrowser); # use for devel
# use CGI::HTMLError (trace => 1); # don't want errs returning to browser ??

use CGI;
use Data::Dumper;
use DBIx::Simple;

use FindBin qw($RealBin); # warn $RealBin;
use lib $RealBin . '/../../lib';

use LIMS::Local::Debug; # DEBUG()
use LIMS::Local::Config;

my $q = CGI->new();
my $vars = $q->Vars(); # warn Dumper $vars;

# set $ENV{CENTRE} if required, BEFORE getting config:
if ( $vars->{service} ) { # warn $vars->{service};
    $ENV{CENTRE} = $vars->{service}; # other centres
}

my $config = LIMS::Local::Config->instance; # warn Dumper $config;
my $dbix   = DBIx::Simple->connect(@{ $config->{dbh_params} });

print $q->header();

my $tt = $vars->{tt}; # warn Dumper $tt;
exit if grep $tt =~ /$_\.tt\Z/, qw(hello user_messages); # can already see them!!

my $username = $vars->{username} || exit; # maybe not logged in

my $sql = q!
    SELECT COUNT(*)
    FROM
      user_message t1 
      JOIN users t2 ON (t1.recipient_id = t2.id)
      JOIN sessions t3 ON (t3.userid = t2.username)
    WHERE
      t1.`acknowledged` IS NULL AND
     /* t3.`time` >= DATE_SUB(NOW(), INTERVAL 10 MINUTE) AND */
      t2.`username` = ?!;
$dbix->query($sql, $username)->into(my $i); # warn Dumper $i;

if ($i) {
    my $url = $vars->{url} . '/resources/user_messages';
    printf q!:: you have %s unacknowledged message(s) :: %s!, $i,
        $q->a({href => $url}, 'view &#187;');
}
