#!/usr/bin/perl

#use utf8;
use strict;
use CGI;
use Digest::SHA qw(
    sha1_base64
    sha1_hex
);

use Opals::Context;
use Opals::Template_ajax qw(
    tmpl_read
    tmpl_write
    tmpl_preference
);
use Opals::Locale qw(
    loc_getMsgFile
    loc_write
);
use JSON;

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

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

    my $msgValMap ={};
    my $stdMsgMap            =loc_getMsgFile('/homeTab.msg',$msgValMap);
    loc_write($template,$stdMsgMap);
    my $nItemShow   = $input->{'nItemShow'};
    my $fieldsShow  = $input->{'fieldsShow'};
       $nItemShow   = (defined $nItemShow)? $nItemShow : 3;
    if ($fieldsShow eq 'title'){
        $template->param(fieldsShow1=>1);
    }
    else{
        $template->param(fieldsShow2=>1);
    }


    my $newsEventList = getNewsEvents($dbh,$nItemShow);
    my $newsevent={nItemShow     => $nItemShow,
             newsEventList=>$newsEventList};
    my $json = to_json($newsevent);
    print "Content-type: text/plain\n\n";
    print $json;

      
=item            
    $template->param(
         newsEventList=> $newsEventList,
        nItemShow     => $nItemShow,

    );

 
tmpl_write($dbh, $cgi, $cookie, $template);
=cut
################################################################################
sub getNewsEvents{
    my ($dbh,$nItemShow) = @_;
    my @newsEvent;

    my $sql=(<<_SQL_);
    select * from  opl_newsEvents where status='on' && (DATE_ADD(expDate,INTERVAL 1 DAY)> now() OR expDate is null OR expDate='0000-00-00') order by expDate desc 
_SQL_
    if($nItemShow >0){
        $sql .= " limit  $nItemShow";
    }
    my $sth = $dbh->prepare($sql);
    $sth->execute();
 
    my @newsEvent;
    while (my $rec = $sth->fetchrow_hashref) {
         push @newsEvent, $rec;
    }
    $sth->finish;
    
    return \@newsEvent;
}

