#!/usr/bin/perl

use strict;
use CGI;

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


 
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/getBeginnerBoxesDB.tmpl',
    }
);


    my $boxId      = $input->{"boxId"};
    if(defined $boxId && $boxId>0){
        my ($title,$url,$description) = ("","","");
        my $sth=$dbh->prepare("select  title,url,description from opl_beginnerDBLk where boxId=?");
        my $rv =$sth->execute($boxId);  
        ($title,$url,$description) = $sth->fetchrow_array;
        if($url !~ m/http:\/\/|https:\/\//i){
            $url = "http://" . $url;
        }

#s/(.*)\1/$1/g
        $title =~ s/'/\'/g;
        $url =~ s/[\r\n]//g;
        $description =~ s/</&lt;/g ;
        $description =~ s/>/&gt;/g ;
        $description =~ s/\n/<br>/g;
        $sth->finish;  
        my $status = ($rv eq '0E0') ? 0 : 1;        
        $template->param(
            status      => $status,
            boxId       => $boxId,
            title       => $title,
            url         => $url,
            description => $description
        );
    }
    else{
        my $url = "";
        my $sth=$dbh->prepare("select  boxId,title,url,description from opl_beginnerDBLk order by boxId");
        my $rv =$sth->execute();
        my @boxesList; 
        while(my $l = $sth->fetchrow_hashref){
            $url = $l->{'url'};
            if($url !~ m/http:\/\/|https:\/\//i){
                $url = "http://" . $url;
            }
            $l->{'url'} = $url;
            $l->{'description'} =~ s/</&lt;/g ;
            $l->{'description'} =~ s/>/&gt;/g ;
            $l->{'description'} =~ s/\n/<br>/g;
            
            push @boxesList, $l;

        } 
 
        $template->param(boxesList =>\@boxesList);
    }


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


