#!/usr/bin/perl

#use utf8;
use strict;
use CGI;

use Opals::Context;
use Opals::Template qw(
    tmpl_read
    tmpl_write
);

use Opals::User qw(
    user_isUserBc
    user_addQuick_1
);

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

my $cgi      = CGI->new;
my $input    = $cgi->Vars();



my ($status,$errorCode,$errorMsg)    ;
my ($permission, $cookie, $template) = tmpl_read(
    {
        dbh             => $dbh,
        cgi             => $cgi,
        tmplFile        => 'ajax/user/getAvailUserGrp.tmpl',
        reqPermission   => 'circ_rsrv_self|circ_rsrv',
    }
);
if ($permission && ($permission->{'circ_rsrv_self'}|| $permission->{'circ_rsrv'})) 
{
    my $teacherList =getTeacherList($dbh);
    my $homeroomList=getHomeroomList($dbh);
    my $gradeList   =getGradeList($dbh);
    my $buildingList=getBuildingList($dbh);


    $template->param( 
            teacherList=>$teacherList,
            homeroomList=>$homeroomList,
            gradeList=>$gradeList,
            buildingList=>$buildingList
            );
}

#------------------------------------------------------------------------------
sub getTeacherList(){
    my ($dbh)=@_;
    my @teacherList=();
    my $sth=$dbh->prepare("select distinct teacher from opl_user where teacher<>'' && teacher is not null order by teacher");
    $sth->execute();
    while( my ($teacher)=$sth->fetchrow_array){
        push @teacherList,{teacher=>$teacher};
    }
    return \@teacherList;
}
#------------------------------------------------------------------------------
sub getHomeroomList(){
    my ($dbh)=@_;
    my @homeroomList=();
    my $sth=$dbh->prepare("select distinct homeroom from opl_user where homeroom<>'' && homeroom is not null order by homeroom");
    $sth->execute();
    while( my ($homeroom)=$sth->fetchrow_array){
        push @homeroomList,{homeroom=>$homeroom};
    }
    return \@homeroomList;
}
#------------------------------------------------------------------------------
sub getGradeList(){
    my ($dbh)=@_;
    my @gradeList=();
    my $sth=$dbh->prepare("select distinct grade from opl_user where grade<>'' && grade is not null order by grade");
    $sth->execute();
    while( my ($grade)=$sth->fetchrow_array){
        push @gradeList,{grade=>$grade};
    }
    return \@gradeList;
}
#------------------------------------------------------------------------------
sub getBuildingList(){
    my ($dbh)=@_;
    my @buildingList=();
    my $sth=$dbh->prepare("select distinct buildingcode from opl_user where buildingcode<>'' && buildingcode is not null order by buildingcode");
    $sth->execute();
    while( my ($building)=$sth->fetchrow_array){
        push @buildingList,{building=>$building};
    }
    return \@buildingList;
}


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