#!/usr/bin/perl

use strict;
use CGI;

use Opals::Context;
use Opals::Template qw(
    tmpl_read
    tmpl_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        => 'txtbk/addSchoolYear.tmpl',
    }
);

my $schoolYear  = $input->{'schoolYear'};
my $firstDate   = $input->{'firstDate'};
my $lastDate    = $input->{'lastDate'};
if ($schoolYear ne "" && $firstDate ne "" && $lastDate ne ""){

    if (insertSchoolYearInfo($dbh, $schoolYear , $firstDate , $lastDate )){
        $template->param(status => 'OK');
    }
    else {
          $template->param(status       => 'fail',
                         errorCode    => 2,
                         errorMsg     => 'School year cannot be saved. Please try again later.'
                        );
        }
}

########################################################################################

sub insertSchoolYearInfo {
    my ($dbh, $schoolYear , $firstDate , $lastDate ) = @_;
    my $sql = "insert into opl_schoolYear (schoolYear, firstDate , lastDate) values(? , ? , ?) ";
    my $sth = $dbh->prepare($sql);
    $sth->execute($schoolYear , $firstDate , $lastDate);
    my $rId = $dbh->{'mysql_insertid'};
    $sth->finish;
    return $rId;

}

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

