#!/usr/bin/perl

#use utf8;
use strict;
use CGI;
use POSIX qw(
    ceil
);

use Opals::Context;
use Date::Calc qw(Day_of_Week Week_Number Day_of_Year);

use Opals::User qw(
    user_getInformation
);

use Time::localtime;
use Opals::Date qw(
    date_parse
    date_today
    date_text
    date_f005
);
use Opals::Template qw(
    tmpl_read
    tmpl_write
    tmpl_rangedPageList
);

use Textbook::Students qw(
    student_getListByCourse
);
use Textbook::SchoolYear qw(
    schoolyear_getCurrent
);

use Textbook::Books qw(
    bookList_forCourse
);

use Textbook::Course qw(
    course_findById
);

use Textbook::Teachers qw(
    teacher_findById
    teacher_findByCourseSectionId
);
use Textbook::Preparation qw(
    getPreparation_byId
);


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        => 'textbook/prep_studentListPrt.tmpl',
            reqPermission   => 'report', #textbook
        }
);

my $tm = localtime;
my $todayStr = sprintf("%04d-%02d-%02d", $tm->year+1900, ($tm->mon)+1, $tm->mday);
my $schoolYearId;
my $schoolYear=schoolyear_getCurrent($dbh);
if ($schoolYear){
    $schoolYearId=$schoolYear->{'id'};
}

#my $actionOpt = $input->{'actionOpt'};
#my $optReport = $input->{'optReport'};
#my $rType     = $input->{'rType'};

my (@cResultList,$params);
my ($pid,$courseId,$courseCode,$courseName,$sectionId,$teacherId);
    $pid         = $input->{'pid'};
    $courseId    = $input->{'courseId'};
    $sectionId   = $input->{'sectionId'};
    $teacherId   = $input->{'teacherId'};

    my $prepInfo = getPreparation_byId($dbh,$pid,$schoolYearId);
    my $courseList = getPrepByCourse($prepInfo,$courseId,$sectionId);


    my $courseInfo = course_findById($dbh,$courseId);
       $courseCode = $courseInfo->{'courseCode'};
       $courseName = $courseInfo->{'courseName'};
    $params = {courseCode=>$courseCode, sectionId=>$sectionId,schoolYear=>$schoolYearId};
    my $tmpList =student_getListByCourse($dbh,$params);
    my $teacherInfo; 
    if(!$teacherId || $teacherId eq ""){
         my $params = {courseCode=>$courseCode, sectionId=>$sectionId, schoolYear=>$schoolYearId};
        my $t = teacher_findByCourseSectionId($dbh, $params);
        $teacherId=$t->{'teacherId'};
    }
    $teacherInfo = teacher_findById($dbh,$teacherId);
    

    $params = {courseCode=>$courseCode};
    my @bookList = bookList_forCourse($dbh,$params);
    my $nBooks = scalar @bookList;
    my $order = 'even';
    if( $tmpList->{$sectionId}){
        my $sList = $tmpList->{$sectionId};
        my $nStudents = scalar @$sList;
        for (my $i=0 ;$i<$nStudents ;$i++ ){
            @{$sList}[$i]->{'bookList'} = \@bookList;
            @{$sList}[$i]->{'nBooks'} = $nBooks;
            @{$sList}[$i]->{'order'} =$order;
            $order  = ($order eq 'odd')?  'even' : 'odd';
        }
        $template->param(
                todayStr    => $todayStr,
                courseList  => $courseList,
                studentList => $sList,
                teacherId   => $teacherId,
                courseCode  => $courseCode,
                courseName  => $courseName,
                sectionId   => $sectionId,
                t_firstName => $teacherInfo->{'firstName'},
                t_lastName  => $teacherInfo->{'lastName'},
                order       => $order
         );
       
    }

################################################################                 
sub getPrepByCourse{
    my ($p,$courseId,$sectionId)   = @_;
    my @retVal;

    my $tmp;
    my $bList=$p->{'book2Prepare'};

    foreach my $b(@$bList){

       if ($b->{'courseId'} eq $courseId && !$tmp->{$b->{'courseId'}}){
           my $course=course_findById($dbh,$b->{'courseId'});
           $tmp->{$b->{'courseId'}}=$course;
       }
       if ($b->{'courseId'} eq $courseId && $b->{'sectionId'} eq $sectionId && 
            !$tmp->{$b->{'courseId'}}->{'sections'}->{$b->{'sectionId'}}){
           $tmp->{$b->{'courseId'}}->{'sections'}->{$b->{'sectionId'}}->{'nStudents'}=$b->{'nStudents'};
       }
       my $aType= $b->{'allocationType'};
       if($aType eq 'perStudent'){
           $aType = 'Book per student';
       }
       elsif($aType eq 'perSection'){
           $aType = 'Book(s) for section';
       }
       elsif($aType eq 'perClass'){
           $aType = 'Book(s) for class';
       }

       if($b->{'courseId'} eq $courseId && $b->{'sectionId'} eq $sectionId ){
           push @{$tmp->{$b->{'courseId'}}->{'sections'}->{$b->{'sectionId'}}->{'books'}},
                {ISBN=>$b->{'ISBN'},allocationType=>$aType,
                nCopiesPerAllocation=>$b->{'nCopiesPerAllocation'},total=>$b->{'total'},
                nDistributed =>$b->{'nDistributed'},recipient => $b->{'recipient'}};
      }
        
    }

    my $i=0;
    my @courseList;
    foreach my $k(keys %{$tmp}){
        push @courseList,{courseId=>$k,
                          courseCode=>$tmp->{$k}->{'courseCode'},
                          courseName=>$tmp->{$k}->{'courseName'}
                          };
        foreach my $s(keys %{$tmp->{$k}->{'sections'}}){
            push @{$courseList[$i]->{'sections'}},$tmp->{$k}->{'sections'}->{$s};
            
              }
        $i++;
        

    }


    return \@courseList;
}

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

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