#!/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::SchoolYear qw(
    schoolyear_getCurrent
);

use Textbook::Course qw(
    course_findById
);

use Textbook::Teachers qw(
    teacher_findById
    teacher_findByCourseSectionId
);

use Textbook::Students qw(
    student_getListByCourse
    student_findById
);

use Textbook::Books qw(
    bookList_forCourse
    book_getByIsbn
);

use Textbook::Search qw(
    search_course
    search_teacher
  
    search_prep_teacher
    search_prep_student
    search_prep_course
    search_prep_homeroom

    search_dist_teacher
    search_dist_student
    search_dist_course
    search_dist_homeroom

    search_coll_teacher
    search_coll_student
    search_coll_course
    search_coll_homeroom
);

use Textbook::Preparation qw(
    getPreparation_teacher
    getPreparation_student
    getPreparation_course
    getPreparation_homeroom
);
use Textbook::Distribution qw(
    countBookDistByISBN
    
    getDistribution_teacher
    getDistribution_student
    getDistribution_course
    getDistribution_homeroom
    
    getDistributions2ReceiverByType  
 
);

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/report.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'};
if($rType     eq "") {$rType = "teacher"};
if($actionOpt eq "") {$actionOpt = "search"};
if($optReport eq "") {$optReport = "p"};

my (@resultList,$num, $rs);
my $order;
my $tmpRs;
my $params;

if($actionOpt eq "search"){
    $params = {};
    if($optReport eq "p" ){
      $rs = searchPreparations($dbh,$params,$rType);  
    }
    elsif($optReport eq "d"){
      $rs = searchDistributions($dbh,$params,$rType);  
    }
    elsif($optReport eq "c"){
      $params={bookWasCollected => 1}; 
      $rs = searchCollections($dbh,$params,$rType);  
    }
    
    ($num,@resultList) = getSearchResult($rs);
    #my $numOfRs =  scalar(@resultList);
    if($num >0){
        $template->param( numOfRs  => $num);
    }
    $template->param(  search       => 1,
                       resultList   => @resultList);

}

elsif($actionOpt eq "detail"){
    my $selVal     = $input->{'selVal'};
    if($optReport eq "p"){
          @resultList = getDetailPreparations($dbh,$selVal);
    }
    elsif($optReport eq "d"){
       @resultList = getDetailDistributions($dbh,$selVal);
    }
    elsif($optReport eq "c"){
      @resultList = getDetailCollections($dbh,$selVal);  
    }
    $template->param(  detail      => 1,
                       resultList  => @resultList );
    my $numOfRs =  scalar(@resultList);
    if($numOfRs >0){
        $template->param( numOfRs  => $numOfRs);
    }

}



    $template->param( optReport        => $optReport,
                      rType            => $rType,
                      actionOpt        => $actionOpt,
                      todayStr         => date_text($todayStr) );

  

    if($optReport eq "p"){
        $template->param(reportHeader => "Preparation",
                         preparation  => 1);
    }
    elsif($optReport eq "d"){
        $template->param(reportHeader => "Distribution",
                         distribution => 1);
    }
    elsif($optReport eq "c"){
        $template->param(reportHeader => "Collection",
                         collection   => 1);
    }
################################################################################
sub  getDetailCollections{
    my ($dbh,$selVal) = @_;
    my @tmpRsList;
    if($rType eq "teacher"){
        my $teacherInfo = teacher_findById($dbh,$selVal);
        my $params ={receiverType     => "teachers",
                     receiverId       => $selVal,
                     schoolYearId     => $schoolYearId,
                     bookWasCollected => 1};
        $tmpRs = getDistributions2ReceiverByType($dbh,$params);
        my $prepOrder=0;
        foreach my $d( @{$tmpRs}){
            my $td= distributedConversion($d);
            $td->{'prepOrder'} =$prepOrder++;
            $td->{'pid'} =  $d->{'pid'};
            push   @tmpRsList,  $td;  
        }
        $template->param( 
                          teacher      => 1,
                          teacherId    => $teacherInfo->{'teacherId'},
                          firstName    => $teacherInfo->{'firstName'},
                          lastName     => $teacherInfo->{'lastName'},
                          todayStr     => $todayStr );

    }
    elsif($rType eq "student"){
        my $studentInfo = student_findById($dbh,$selVal);
        my $params ={receiverType     => "students",
                     receiverId       => $selVal,
                     schoolYearId     => $schoolYearId,
                     bookWasCollected => 1};
        $tmpRs = getDistributions2ReceiverByType($dbh,$params);
        my $prepOrder=0;
        foreach my $d( @{$tmpRs}){
            my $td= distributedConversion($d);
            $td->{'prepOrder'} =$prepOrder++;
            $td->{'pid'} =  $d->{'pid'};
            push   @tmpRsList,  $td;  
        }
        $template->param( 
                          student      => 1,
                          studentId    => $teacherInfo->{'studentId'},
                          firstName    => $teacherInfo->{'firstName'},
                          lastName     => $teacherInfo->{'lastName'},
                          todayStr     => $todayStr );

    }
    
    return(\@tmpRsList);

}
################################################################################
sub  getDetailDistributions{
    my ($dbh,$selVal) = @_;
    my @tmpRsList;
    
    if($rType eq "teacher"){
        my $teacherInfo = teacher_findById($dbh,$selVal);
        $tmpRs =getDistribution_teacher($dbh,{teacherId        => $selVal,
                                             schoolYearId      => $schoolYearId,
                                             recipient         => 'teacher',
                                             expectedReadiness => $todayStr });
        my $prepOrder=0;
        foreach my $p( @{$tmpRs}){
            my $tp= teacherPrepConversion($p);
            $tp->{'prepOrder'} =$prepOrder++;
            push   @tmpRsList,  $tp;        
        }
        my $numOfPrep = scalar(@tmpRsList);
        $template->param( 
                          teacher      => 1,
                          teacherId    => $teacherInfo->{'teacherId'},
                          firstName    => $teacherInfo->{'firstName'},
                          lastName     => $teacherInfo->{'lastName'},
                          todayStr     => $todayStr );

    
    }
    elsif($rType eq "student"){
       my $studentInfo = student_findById($dbh,$selVal);
        $tmpRs =getDistribution_student($dbh,{studentId       => $selVal,
                                            schoolYearId      => $schoolYearId,
                                            recipient         => 'student',
                                            expectedReadiness => $todayStr });

        my $prepOrder=0;
        foreach my $p( @{$tmpRs}){
            my $tp= studentPrepConversion($p,$selVal);
            $tp->{'prepOrder'} =$prepOrder++;
            push   @tmpRsList,  $tp; 
        }
        my $numOfPrep = scalar(@tmpRsList);
        $template->param(
                  student      => 1,
                  studentId    => $studentInfo->{'studentId'},
                  firstName    => $studentInfo->{'firstName'},
                  lastName     => $studentInfo->{'lastName'},
                  todayStr     => $todayStr );
    }
    elsif($rType eq "course"){

    }
    elsif($rType eq "homeroom"){
    }

    return(\@tmpRsList);

}


################################################################################
sub  getDetailPreparations{
    my ($dbh,$selVal) = @_;
    my @tmpRsList;
   
    if($rType eq "teacher"){
        my $teacherInfo = teacher_findById($dbh,$selVal);
        $tmpRs =getPreparation_teacher($dbh,{teacherId         => $selVal,
                                             schoolYearId      => $schoolYearId,
                                             recipient         => 'teacher',
                                             expectedReadiness => $todayStr });
        my $prepOrder=0;
        foreach my $p( @{$tmpRs}){
            my $tp= teacherPrepConversion($p);
            $tp->{'prepOrder'} =$prepOrder++;
            push   @tmpRsList,  $tp;        
        }
        my $numOfPrep = scalar(@tmpRsList);  
       

        $template->param( 
                          teacher     => 1,
                          teacherId    => $teacherInfo->{'teacherId'},
                          firstName    => $teacherInfo->{'firstName'},
                          lastName     => $teacherInfo->{'lastName'},
                          todayStr     => $todayStr );
    }
    elsif($rType eq "student"){
       my $studentInfo = student_findById($dbh,$selVal);
        $tmpRs =getPreparation_student($dbh,{studentId        => $selVal,
                                            schoolYearId      => $schoolYearId,
                                            recipient         => 'student',
                                            expectedReadiness => $todayStr });

        my $prepOrder=0;
        foreach my $p( @{$tmpRs}){
            my $tp= studentPrepConversion($p,$selVal);
            $tp->{'prepOrder'} =$prepOrder++;
            push   @tmpRsList,  $tp; 
        }
        my $numOfPrep = scalar(@tmpRsList);
                  $template->param(
                  student      => 1,
                  studentId    => $studentInfo->{'studentId'},
                  firstName    => $studentInfo->{'firstName'},
                  lastName     => $studentInfo->{'lastName'},
                  todayStr     => $todayStr );
    }
    elsif($rType eq "course"){
       my $courseInfo = course_findById($dbh,$selVal);
        $tmpRs =getPreparation_course($dbh,$selVal, $schoolYearId);

        my $prepOrder=0;
        foreach my $p( @{$tmpRs}){
            my $tp= coursePrepConversion($p);
            $tp->{'prepOrder'} =$prepOrder++;
            push   @tmpRsList,  $tp; 
        }
        my $numOfPrep = scalar(@tmpRsList);
        $template->param(
                    course          =>1,
                    courseId        =>$selVal,
                    courseCode      =>$courseInfo->{'courseCode'},
                    courseName      =>$courseInfo->{'courseName'},
                    todayStr        => $todayStr );

    }
    elsif($rType eq "homeroom"){
    }
    
      
    return(\@tmpRsList);

}
#################################################################################
sub distributedConversion{
    my ($distribution)=@_;
    my $retval;
    my @courseList;
    my($i,$j,$k)=(-1,-1,0);
    my($curCourseId,$curSectionId)=("","");
    my $className="";
    my $nCollections=0;  
    foreach my $d(@{$distribution->{'bookDist'}}){
        if($curCourseId ne $d->{'courseId'}){
            $curCourseId=$d->{'courseId'};
            $i++;
            $j=-1;
            my $course=course_findById($dbh,$d->{'courseId'});
            push @courseList,{
                              courseId   =>$d->{'courseId'},
                              courseName =>$course->{'courseName'},
                              courseCode =>$course->{'courseCode'},
                              nSections=>0,
                              nISBNs=>0,
                              c_order=>$i
                             };
        }
        if($curSectionId ne $d->{'sectionId'}){
            $curSectionId = $d->{'sectionId'};
            @courseList[$i]->{'nSections'} +=1;
            $j++;    
            $k=0;        
            push @{@courseList[$i]->{'sectionList'}},{sectionId=>$d->{'sectionId'},nISBNs=>0,s_order=>$j};
        }
        my $s = @{@courseList[$i]->{'sectionList'}}[$j];
        my $book = book_getByIsbn($dbh,$d->{'ISBN'});
        $nCollections = $d->{'ok'} + $d->{'damaged'}  + $d->{'lost'} ;
        my $isDone =0;
        if(int($nCollections) == int($d->{'distributed'})){
             $isDone = 1;
        }

        push @{$s->{'bookList'}}, {ISBN          => $d->{'ISBN'},
                                   title         => $book->{'title'},
                                   distributed   => $d->{'distributed'},
                                   nCollections  => $nCollections,
                                   ok            => $d->{'ok'},
                                   damaged       => $d->{'damaged'},
                                   lost          => $d->{'lost'},
                                   isDone        => $isDone,
                                   isbn_order=>$k++
                                   };
                
        $s->{'nISBNs'} +=1;
        @courseList[$i]->{'nISBNs'} +=1;

    }
    $retval={courseList=>\@courseList, };
    return  $retval;

}
###############################################################################
sub coursePrepConversion{

 my ($prep)=@_;
    my $retval;
    my @sectionList;
    my($i,$j,$k)=(-1,-1,0);
    my $curSectionId="";
    my $className=""; 
    my $distDone = 0;
    my @bookList;
    my $nISBN=0;

    foreach $b(@{$prep->{'book2Prepare'}}) {

        $nISBN++;

        if($curSectionId ne $b->{'sectionId'}){
            $curSectionId = $b->{'sectionId'};
            $i++;
             
            push @sectionList, {sectionId   => $b->{'sectionId'},
                                nStudents   => $b->{'nStudents'},
                                nISBNs      => 0,
                                s_order     => $i,
                            };
           $k=0;
          }
        if($b->{'nDistributed'} eq $b->{'total'}){
            $className="distDone";
            @sectionList[$i]->{'distDone'} =1;
            $distDone = 1;

        }

        @sectionList[$i]->{'nISBNs'} +=1;
        my $book = book_getByIsbn($dbh,$b->{'ISBN'});
        push @{@sectionList[$i]->{'bookList'}}, {  
                        ISBN            =>$b->{'ISBN'},
                        title           =>$book->{'title'},
                        total           =>$b->{'total'},
                        allocationType  =>$b->{'allocationType'},
                        nDistributed    =>$b->{'nDistributed'},
                        wDistribute     =>$b->{'total'} - $b->{'nDistributed'},
                        recipient       =>  $b->{'recipient'},
                        isbn_order      =>  $k++,
                        className       =>  $className,
                        

            };
    }
   $retval={   
                pid             =>$prep->{'pid'},
                type            =>$prep->{'type'},
                prepareDate     =>$prep->{'preparedDate'},
                expectedReadiness=>$prep->{'expectedReadiness'},
                distDone        =>$distDone,
                sectionList     =>\@sectionList,
                className       =>$className,

                };


    return $retval;
    }


################################################################################
sub studentPrepConversion{
    my ($prep,$studentId)=@_;
    my $retval;
    my @courseList;
    my($i,$j,$k)=(-1,-1,0);
    my($curCourseId,$curSectionId)=("","");
    my $className="";
    

    foreach $b(@{$prep->{'book2Prepare'}}){
         if($curCourseId ne $b->{'courseId'}){
            $curCourseId=$b->{'courseId'};
            $i++;
            $j=-1;
            $k=0;
            my $course=course_findById($dbh,$b->{'courseId'});

            if(!$b->{'teacherId'}){
                my $t = search_teacher($dbh,{courseCode=>$course->{'courseCode'},
                                               sectionId=>$b->{'sectionId'} });
                my $stdList=$t->{'teacherList'};
                foreach my $tInfo(@$stdList){
                    $b->{'teacherId'} = $tInfo->{'teacherId'};
                }
            }
            my $teacherInfo = teacher_findById($dbh,$b->{'teacherId'});

            push @courseList,{courseId      =>$b->{'courseId'},
                              courseName    =>$course->{'courseName'},
                              courseCode    =>$course->{'courseCode'},
                              teacherId     => $teacherInfo->{'teacherId'},
                              t_firstName   => $teacherInfo->{'firstName'},
                              t_lastName    => $teacherInfo->{'lastName'},
                              sectionId     =>$b->{'sectionId'},
                              nISBNs=>0,
                              c_order=>$i
                             };
            }
            my $book = book_getByIsbn($dbh,$b->{'ISBN'}); 
            $className = "";
            
            my $params ={receiverType=>'students', receiverId=>$studentId,
                         schoolYearId=>$schoolYearId, courseId=>$b->{'courseId'},
                         sectionId=>$b->{'sectionId'},ISBN=>$b->{'ISBN'}};
            my ($nBookDist,$nBookReq) ;

            if($prep->{'type'} eq 'teacher') {            
                my $bookCount = countBookDistByISBN($dbh,$params);
                foreach my $n(@$bookCount){
                    $nBookDist = $n->{'bCount'};
                }
                $nBookReq = $b->{'nCopiesPerAllocation'};

            }
            elsif($prep->{'type'} eq 'student') {
                $nBookDist = $b->{'nDistributed'};
                $nBookReq  = $b->{'total'};
            }
            if ($nBookReq eq $nBookDist){
                $className="distDone";
            }
                        
            push @{@courseList[$i]->{'bookList'}}, 
                            {ISBN          => $b->{'ISBN'},
                            title          => $book->{'title'},
                            nDistributed   => $nBookDist,
                            allocationType => $b->{'allocationType'},
                            nCopies        => $b->{'nCopiesPerAllocation'},
                            total          => $nBookReq,
                            wDistribute    => $nBookReq - $nBookDist,
                            className      => $className,
                            isbn_order     => $k++
        };
        if ($className eq 'distDone'){
            @courseList[$i]->{'distDone'}=1;
        }
     }

    $retval={pid=>$prep->{'pid'},
             type=>uc($prep->{'type'}),
             preparedDate=>$prep->{'preparedDate'},
             expectedReadiness=>$prep->{'expectedReadiness'},
             courseList=>\@courseList,
             };
    return  $retval;  
}
       
################################################################################
sub teacherPrepConversion{
    my ($prep)=@_;
    my $retval;
    my @courseList;
    my($i,$j,$k)=(-1,-1,0);
    my($curCourseId,$curSectionId)=("","");
    my $className="";
    foreach $b(@{$prep->{'book2Prepare'}}){
         if($curCourseId ne $b->{'courseId'}){
            $curCourseId=$b->{'courseId'};
            $i++;

            $j=-1;
            my $course=course_findById($dbh,$b->{'courseId'});
            push @courseList,{courseId   =>$b->{'courseId'},
                              courseName =>$course->{'courseName'},
                              courseCode =>$course->{'courseCode'},
                              nSections=>0,
                              nISBNs=>0,
                              c_order=>$i
                             };

        }
        if($curSectionId ne $b->{'sectionId'}){
            $curSectionId = $b->{'sectionId'};
            @courseList[$i]->{'nSections'} +=1;
            $j++;    
            $k=0;        
            push @{@courseList[$i]->{'sectionList'}},{sectionId   => $b->{'sectionId'}, 
                                                      nStudents   => $b->{'nStudents'},
                                                      nISBNs=>0,s_order=>$j
                                                     };
        }
        my $s = @{@courseList[$i]->{'sectionList'}}[$j];
        my $book = book_getByIsbn($dbh,$b->{'ISBN'}); 
        $className="";
        if($b->{'nDistributed'} eq $b->{'total'}){
            $className="distDone";
        }

        push @{$s->{'bookList'}}, {ISBN          => $b->{'ISBN'},
                                   title         => $book->{'title'},
                                   nDistributed  => $b->{'nDistributed'},
                                   total         => $b->{'total'},
                                   className     => $className,
                                   isbn_order=>$k++
                                   };
        $s->{'nISBNs'} +=1;  
        if($className eq "distDone"){
            $s->{'distDone'} =1;
            $s->{'className'} =$className;
            @courseList[$i]->{'distDone'} =1;

        }
        @courseList[$i]->{'nISBNs'} +=1;
    }
  $retval={pid=>$prep->{'pid'},type=>$prep->{'type'},
             preparedDate=>$prep->{'preparedDate'},
             expectedReadiness=>$prep->{'expectedReadiness'},
             courseList=>\@courseList,
             };
   return  $retval;
}


################################################################################
sub searchPreparations{
    my ($dbh,$params,$rType )=@_;
    my $retVal;
    if($rType eq "teacher"){
        $retVal = search_prep_teacher($dbh,$params);
    }
    elsif($rType eq "student"){
        $retVal = search_prep_student($dbh,$params);
    }
    elsif($rType eq "course"){
        $retVal = search_prep_course($dbh,$params);
    }
    elsif($rType eq "homeroom"){
        $retVal = search_prep_homeroom($dbh,$params);
    }

    return $retVal;
}

   

################################################################################
sub searchDistributions{
   my ($dbh,$params,$rType )=@_;
    my $retVal;
    if($rType eq "teacher"){
        $retVal = search_dist_teacher($dbh,$params);
    }
    elsif($rType eq "student"){
        $retVal = search_dist_student($dbh,$params);
    }
    elsif($rType eq "course"){
        $retVal = search_dist_course($dbh,$params);
    }
    elsif($rType eq "homeroom"){
        $retVal = search_dist_homeroom($dbh,$params);
    }
    return $retVal;
}

################################################################################
sub searchCollections{
   my ($dbh,$params,$rType )=@_;
    my $retVal;
    if($rType eq "teacher"){
        $retVal = search_coll_teacher($dbh,$params);
    }
    elsif($rType eq "student"){
        $retVal = search_coll_student($dbh,$params);
    }
    elsif($rType eq "course"){
        $retVal = search_coll_course($dbh,$params);
    }
    elsif($rType eq "homeroom"){
        $retVal = search_coll_homeroom($dbh,$params);
    }
    return $retVal;
}



################################################################################
sub getSearchResult{
    my ($tmpRs) = @_;
    #$tmpRs = getPreparations();
    my @tmpRsList;   
    if($rType eq "teacher"){
        my $tList=$tmpRs->{'teacherList'};
        $order =0; 
        foreach my $d( @$tList){
            my $teacherInfo = teacher_findById($dbh,$d->{'teacherId'});
               $d->{'firstName'} = $teacherInfo->{'firstName'};
               $d->{'lastName'}  = $teacherInfo->{'lastName'} ;
               $d->{'order'}     = $order;
            push   @tmpRsList,  $d;
            $order ++;  
        }
        $template->param( teacher   => 1);
    }
    elsif($rType eq "student"){
        my $sList=$tmpRs->{'studentList'}; 
        $order =0; 
        foreach my $d( @$sList){
            my $studentInfo = student_findById($dbh,$d->{'studentId'});
               $d->{'firstName'} = $studentInfo->{'firstName'};
               $d->{'lastName'}  = $studentInfo->{'lastName'} ;
               $d->{'order'}     = $order;
            push   @tmpRsList,  $d;  
            $order ++;  
        }
        $template->param(  student  => 1);
    }    
    elsif($rType eq "course"){
        my $cList=$tmpRs->{'courseList'}; 
        $order =0; 
        foreach my $d (@$cList){
            my $courseInfo = course_findById($dbh,$d->{'courseId'});
               $d->{'courseCode'} = $courseInfo->{'courseCode'};
               $d->{'courseName'}  = $courseInfo->{'courseName'} ;
               $d->{'order'}     = $order;
            push   @tmpRsList,  $d;  
            $order ++;  
        }
        $template->param(  course  => 1);
    }
    elsif($rType eq "homeroom"){
        my $hList=$tmpRs->{'homeroomList'}; 
        $order =0; 
        foreach my $d (@$hList){
               $d->{'order'}     = $order;
            push   @tmpRsList,  $d;  
            $order ++;  
        }
        $template->param( homeroom   => 1);

   }
    
    my $n = scalar(@tmpRsList); 
    return($n,\@tmpRsList);
}


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

