#!/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 Opals::MarcXml qw(
    mxml_delete
);
use Opals::Date qw(
    date_parse
    date_today
    date_text
    date_f005
);
use Opals::Template qw(
    tmpl_read
    tmpl_write
    tmpl_rangedPageList
);


use Textbook::Search qw(
    search_student
    search_teacher
    search_course
    search_homeroom
);

use Textbook::Books qw(
    bookList_forCourse
    bookList_forTeacher
    bookList_forStudent
    bookList_forHomeroom
    book_getByIsbn
);
use Textbook::Students qw(
    student_findById
    student_getListByCourse
);

use Textbook::Preparation qw(
    getPreparation_byId
);

use Textbook::Teachers qw(
    teacher_findById
);


use Textbook::Course qw(
    course_findById
    course_find
);


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

my $pid          = $input->{'pid'};       # preparation ID
my $sListOpt     = $input->{'sListOpt'};  # print student list if $sListOpt =1
my $schoolYearId = 1;
my $dateToday    = date_f005();
   $dateToday    =~ s/([\d]{4})([\d]{2})([\d]{2})[\d]+\.(0|1)/$1-$2-$3/;
my ($preparationType,$teacher,$student,$course);
my ($params,$courseId,$courseCode,$sectionId,$nStudents);  
my @courseList;
my $hBList;
my $hBookInfo;
   
if($pid){
    my $p = getPreparation_byId($dbh,$pid,$schoolYearId);
    $preparationType = $p->{"type"};
    
    
    if($preparationType eq 'teacher'){
        my $bList=$p->{'book2Prepare'};
        $teacher = teacher_findById($dbh, @$bList[0]->{'teacherId'});
        foreach my $b(@$bList){
            $hBookInfo->{$b->{'ISBN'}} = book_getByIsbn($dbh,$b->{'ISBN'});
            $b->{'title'}=$hBookInfo->{$b->{'ISBN'}}->{'title'};
        }
        @courseList = getCourseListInfo($dbh,$bList);

        my @bookList;
        foreach my $isbn(keys %{$hBList}){
            push @bookList, {ISBN=> $isbn, title =>$hBookInfo->{$isbn}->{'title'} , 
                             pubName =>$hBookInfo->{$isbn}{'pubName'},
                             pubDate =>$hBookInfo->{$isbn}{'pubDate'},
                             author =>$hBookInfo->{$isbn}{'author'},
                             total=>$hBList->{$isbn}} ;
        }
        $template->param(
            teacherId        => $teacher->{'teacherId'}, 
            lastName         => $teacher->{'lastName'}, 
            firstName        => $teacher->{'firstName'}, 
            teachers         => 1, 
            preparationDate  => $p->{'preparedDate'} ,
            expectedDate     => $p->{'expectedReadiness'} ,
            courseList       => \@courseList,
            bookList         => \@bookList,
        );
    }
    elsif ($preparationType eq 'student'){

        my $bList=$p->{'book2Prepare'};
        $student = student_findById($dbh, @$bList[0]->{'studentId'} );

        my @bookList;
        my $tmpBookList;
        my $isbn;
        my $total;
        my $cList;
   
        foreach my $b(@$bList){
            $isbn   = $b->{'ISBN'};
            $total  = $b->{'total'};
            if(!$tmpBookList->{$isbn}){
                my $bookInfo = book_getByIsbn($dbh, $isbn);
                $tmpBookList->{$isbn}= {   ISBN    =>  $isbn, 
                                    title   =>  $bookInfo->{'title'},
                                    pubName =>  $bookInfo->{'pubName'},
                                    pubDate =>  $bookInfo->{'pubDate'},
                                    author  =>  $bookInfo->{'author'},
                                    total   =>  $total
                                    };
                push   @bookList, $tmpBookList->{$isbn};                                 
            }
            my $course = course_findById($dbh,$b->{'courseId'});
            if(!$cList->{$b->{'courseId'}}){
                $cList->{$b->{'courseId'}}= {   
                                            courseCode =>$course->{'courseCode'},
                                            courseName =>$course->{'courseName'},
                                            sectionId  =>$b->{'sectionId'},
                                            };
                }
                push @{$cList->{$b->{'courseId'}}->{'bookList'}},$tmpBookList->{$b->{'ISBN'}};
        }
        foreach my $c (keys %{$cList}){
            push @courseList,$cList->{$c};
        }
        $template->param(
            studentId        => $student->{'studentId'}, 
            lastName         => $student->{'lastName'}, 
            firstName        => $student->{'firstName'}, 
            students         => 1, 
            preparationDate  => $p->{'preparedDate'} ,
            expectedDate     => $p->{'expectedReadiness'} ,
            courseList       => \@courseList,
            bookList         => \@bookList,
        );
     }
    elsif ($preparationType eq 'course') {
        my $bList = $p->{'book2Prepare'};
        
        my @bookList;
        my $isbn;
        my $total;
        my $sectionId;
        my @sectionList;
        foreach my $b(@$bList){
            $hBookInfo->{$b->{'ISBN'}} = book_getByIsbn($dbh,$b->{'ISBN'});
            $b->{'title'}=$hBookInfo->{$b->{'ISBN'}}->{'title'};
        }

        $course = course_findById($dbh, @$bList[0]->{'courseId'});
        @sectionList = getSectionListInfo($dbh,$bList);

        foreach my $isbn(keys %{$hBList}) {
            my $bookInfo = book_getByIsbn($dbh, $isbn);

            push @bookList, {
                        ISBN    => $isbn,
                        title   => $hBookInfo->{$isbn}{'title'},
                        pubName => $hBookInfo->{$isbn}{'pubName'},
                        pubDate => $hBookInfo->{$isbn}{'pubDate'},
                        author  => $hBookInfo->{$isbn}{'author'},
                        total   => $hBList->{$isbn}, };
            }

         $template->param(
            courseCode      => $course->{'courseCode'},
            courseName      => $course->{'courseName'},
            courses         =>  1,
            preparationDate => $p->{'preparedDate'},
            expectedDate    => $p->{'expectedReadiness'},
            bookList        => \@bookList,
            sections        => \@sectionList,
            );

    }
    elsif ($preparationType eq 'homeroom'){

        my $bList=$p->{'book2Prepare'};
        my $homeroomVal;
        foreach my $b(@$bList){
            $homeroomVal = $b->{'homeroom'};
            $hBookInfo->{$b->{'ISBN'}} = book_getByIsbn($dbh,$b->{'ISBN'});
            $b->{'title'}=$hBookInfo->{$b->{'ISBN'}}->{'title'};
        }
        @courseList = getCourseListInfo($dbh,$bList);

        my @bookList;
        foreach my $isbn(keys %{$hBList}){
            push @bookList, {ISBN=> $isbn, title =>$hBookInfo->{$isbn}->{'title'} , 
                             pubName =>$hBookInfo->{$isbn}{'pubName'},
                             pubDate =>$hBookInfo->{$isbn}{'pubDate'},
                             author =>$hBookInfo->{$isbn}{'author'},
                             total=>$hBList->{$isbn}} ;
        }
        $template->param(
            homeroom         => 1, 
            homeroomVal      => $homeroomVal,
            preparationDate  => $p->{'preparedDate'} ,
            expectedDate     => $p->{'expectedReadiness'} ,
            courseList       => \@courseList,
            bookList         => \@bookList,
        );
    }
    $template->param(
        sListOpt        => $sListOpt,
    );
}
###################################################################################
sub getCourseListInfo{
     my ($dbh,$bList) = @_;
         my $tmp;
         my $allocationTypeTmp;
        foreach my $b(@$bList){
           if (!$tmp->{$b->{'courseId'}}){
               my $course=course_findById($dbh,$b->{'courseId'});
               $tmp->{$b->{'courseId'}}=$course;
           }
           
           if (!$tmp->{$b->{'courseId'}}->{'sections'}->{$b->{'sectionId'}}){
               $tmp->{$b->{'courseId'}}->{'sections'}->{$b->{'sectionId'}}->{'sectionId'}=$b->{'sectionId'};
               $tmp->{$b->{'courseId'}}->{'sections'}->{$b->{'sectionId'}}->{'nStudents'}=$b->{'nStudents'};
           }
           
                     
           if($b->{'allocationType'} eq 'perStudent'){
                $allocationTypeTmp = 'Book per student';
           }
           elsif($b->{'allocationType'} eq 'perClass'){
               $allocationTypeTmp = 'Book per class';
           }
           else{
               $allocationTypeTmp = 'Book per section';
           }
           push @{$tmp->{$b->{'courseId'}}->{'sections'}->{$b->{'sectionId'}}->{'books'}},
                {   ISBN                 => $b->{'ISBN'},
                    title                => $b->{'title'},
                    allocationType       => $allocationTypeTmp ,
                    nCopiesPerAllocation => $b->{'nCopiesPerAllocation'},
                    total                => $b->{'total'},
                    recipient            => $b->{'recipient'}
                };
          
            if(!$hBList->{$b->{'ISBN'}}){
                $hBList->{$b->{'ISBN'}} = $b->{'total'};
            }
            else{
                $hBList->{$b->{'ISBN'}} +=$b->{'total'};

            }
        }
        my $i=0;
        my $n=0;
        my @courseList;
        foreach my $k(keys %{$tmp}){
            my $params={courseCode  => $tmp->{$k}->{'courseCode'}, 
                        schoolYear  => $schoolYearId};

            my $studentList =student_getListByCourse($dbh,$params);
            push @courseList,{order     => ++$n,
                              courseId  => $k,
                              courseCode=> $tmp->{$k}->{'courseCode'},
                              courseName=> $tmp->{$k}->{'courseName'}
                              };

            foreach my $s(keys %{$tmp->{$k}->{'sections'}}){  
                my $tmpSection=  $tmp->{$k}->{'sections'}->{$s};
                $tmpSection->{'studentList'}=  $studentList->{$s};
                push @{$courseList[$i]->{'sections'}},$tmpSection;
            }
         
            $i++;
        }
        return @courseList;
}
 
###################################################################################
sub getSectionListInfo{
 
    my ($dbh, $bList) = @_;
    my @sectionList;
    my $tmp;
    my $tmpDetail;
    my $allocationTypeTmp;
    my $isbn;
    my $sectionId;
    my $i;
    $i = 0;

    foreach my $b(@$bList) {
        
        $sectionId = $b->{'sectionId'};

        if (!$tmp->{$sectionId}){
            $tmp->{$sectionId}->{'sectionId'}=$b->{'sectionId'};
            $tmp->{$sectionId}->{'nStudents'}=$b->{'nStudents'};
        }

             
        if($b->{'allocationType'} eq 'perStudent'){
            $allocationTypeTmp = 'Book per student';
        } 
        elsif($b->{'allocationType'} eq 'perClass'){
            $allocationTypeTmp = 'Book per class';
        }
        else{
            $allocationTypeTmp = 'Book per section';
        }

        push @{$tmp->{$sectionId}->{'books'}},
                {   ISBN                 => $b->{'ISBN'},
                    title                => $b->{'title'},
                    allocationType       => $allocationTypeTmp ,
                    nCopiesPerAllocation => $b->{'nCopiesPerAllocation'},
                    total                => $b->{'total'},
                    recipient            => $b->{'recipient'}
                };
 

   
        ### get total books for each ISBN
        $isbn       = $b->{'ISBN'};

        if (!$hBList->{$isbn}){
            $hBList->{$isbn} = $b->{'total'};
        }
        else{
            $hBList->{$isbn} += $b->{'total'};
        }
    }
    
    foreach my $s (keys %{$tmp}){
        
        push @sectionList, { 
                    sectionId   =>   $tmp->{$s}->{'sectionId'},
                    nStudents   =>   $tmp->{$s}->{'nStudents'},
                    books       =>   $tmp->{$s}->{'books'}   
        };
    }
    return @sectionList;
}

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