#!/usr/bin/perl
use Opals::Context;
use Time::localtime;
use Opals::Template qw(
    tmpl_read
    tmpl_write
    tmpl_preference
);
use Opals::Date qw(
    date_parse
    date_text
    date_profileList
);

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

my $cgi = CGI->new;
my $input = $cgi->Vars();
my $op = $input->{'op'};
my @dateExpList = ($cgi->param('dateExp'));
my @titleList   = ($cgi->param('title'));
my @descList    = ($cgi->param('desc'));
my $debug;
my ($permission, $cookieList, $template) = tmpl_read(
        {
            dbh             => $dbh,
            cgi             => $cgi,
            tmplFile        => 'util/newsEvent.tmpl',
            reqPermission   => 'pref_edit',
        }
);

    my $tm = localtime;
    my $dateToday = sprintf("%04d-%02d-%02d", $tm->year+1900, ($tm->mon)+1, $tm->mday);


# See User.pm for the list of permissions
if ($permission && $permission->{'pref_edit'}) {

   if($op eq  'save'){
       saveNewsEvents($dbh);
   }
   my ($newsEventList) = listnewsEvent($dbh);
   $template->param(
         newsEventList  => $newsEventList,
         newsEvent   =>1,
         today       =>$dateToday,
   );

tmpl_write($dbh, $cgi, $cookie, $template); 
}

#######################################
sub listnewsEvent{
        my ($dbh) = @_;
        
    my $sth = $dbh->prepare(<<_STH_);
    select * from  opl_newsEvents where expDate>=? order by expDate 
_STH_
    $sth->execute($dateToday);
 
        my @newsEvent;
        while (my $rec = $sth->fetchrow_hashref) {
             push @newsEvent, $rec;
        }
        $sth->finish;
        return \@newsEvent;
       $sth->finish;
}

#######################################
sub saveNewsEvents{
    my ($dbh) = @_;

    my $sth = $dbh->prepare(<<_STH_);
    delete from  opl_newsEvents where expDate>=?
_STH_
    $sth->execute($dateToday);

         $sth = $dbh->prepare(<<_STH_);
insert into opl_newsEvents
set     expDate = ?,
        title  = ?,
        description  = ?
_STH_

        for(my $i =0; $i < scalar(@dateExpList);$i++) {
            $titleList[$i]      =~ s/[\r\n]//g;
            $sth->execute($dateExpList[$i],$titleList[$i],$descList[$i]);
        }
        $sth->finish;
}

    
    



