#!/usr/bin/perl

use strict;
use warnings;

BEGIN {
	use FindBin qw($RealBin); # warn $RealBin;
	use lib (
		'/home/raj/perl5/lib/perl5',
        $RealBin . '/../../lib',
	);
	
	# 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 LIMS::Local::Debug; # DEBUG()
use LIMS::Local::Config;

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

my $q = CGI->new();
print $q->header();

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

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` = ?!;
my $i = $dbix->query($sql, $username)->list || exit; # warn Dumper $i;

my $msg = sprintf q!you have %s new / unacknowledged message%s!,
    $i, $i > 1 ? 's' : '';

my $url = $vars->{url} . '/resources/user_messages';

print $q->span({style => 'color: #f00'}, $msg )
    . '  :: ' . $q->a({href => $url}, 'view &#187;');
