#!/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_TotalAvailable
);
use Textbook::Students qw(
    student_getListByCourse
    student_findById

);
use Textbook::Teachers qw(
    teacher_findById
);


use Textbook::Course qw(
    course_findById

);

use Textbook::Preparation qw(
    getPreparation_student
    getPreparation_teacher
    getPreparation_course
    getPreparation_homeroom
);


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

my $preparationType= $input->{'preparationType'};
my $selVal= $input->{'selVal'};
my ($param,$params);
my @resultList;

    my ($nSection,$nBook,$nSectionBook,$rowspan); 
    my (@cResultList,@bookList4Course);
    my ($sections,$book);
    my ($courseCode,$nStudents);
    my ($cResultList,$cResultCount);

    if($preparationType eq "teachers"){
        my $teacherInfo;
        $teacherInfo  = teacher_findById($dbh,$selVal);
        my $result    = search_course($dbh,{teacherId=>$selVal});  
        $cResultList  = $result->{'courseList'};
        $cResultCount = $result->{'found'};
      
        $cResultList = onSelTeacherToPrepare($dbh,$cResultList,$selVal);
        
        $template->param(            
            teacherId=>$teacherInfo->{'teacherId'},
            firstName=>$teacherInfo->{'firstName'},
            lastName=>$teacherInfo->{'lastName'},
            teachers => 1,
            teacherVal=>$input->{'teacher'},
            );
    }
    elsif($preparationType eq "students"){
        my $studentInfo;
        $studentInfo    = student_findById($dbh,$selVal);
        my $result      = search_course($dbh,{studentId=>$selVal});  
        $cResultList    = $result->{'courseList'}    ;
        $cResultCount   = $result->{'found'};
        
        $cResultList    = onSelStudentToPrepare($dbh,$cResultList,$selVal);
                   
        $template->param( 
            studentId   =>$studentInfo->{'studentId'},
            firstName   =>$studentInfo->{'firstName'},
            lastName    =>$studentInfo->{'lastName'},
            homeroom    =>$studentInfo->{'homeroom'},
            students    =>1,
            studentVal  =>$input->{'student'});
    }
    elsif($preparationType eq "courses"){
        
        my $courseInfo  = course_findById($dbh, $selVal);
        $param          = {courseCode=>$courseInfo->{'courseCode'}};
        my $result      = search_course($dbh,$param);
        $cResultList    = $result->{'courseList'}    ;
        $cResultCount   = $result->{'found'};
        $cResultList    = onSelCourseToPrepare($dbh,$cResultList,$courseCode,$selVal);
        
        $template->param(
            courses=>1,
            courseVal=>$input->{'course'},
            courseCode=>$courseInfo->{'courseCode'},
            courseName=>$courseInfo->{'courseName'},
            courseId=>$courseInfo->{'courseId'}, 
            );
    }
    elsif($preparationType eq "homeroom"){
        my $result      = search_course($dbh,{homeroom=>$selVal});
        $cResultList    = $result->{'courseList'};
        $cResultCount   = $result->{'found'};
        $cResultList    = onSelHomeroomToPrepare($dbh, $cResultList);
        
        $template->param(
            homeroom => 1,
            homeroomVal =>$selVal,     
            );
    }

    if($cResultCount>0){
        $template->param(
            cResultCount => $cResultCount );
    }

    # Books available 
    my $ba;

    foreach my $course (@$cResultList){
        foreach my $s (@{$course->{'sections'}}){
            foreach my $book (@{$s->{'bookList'}}){
                $ba->{$book->{'ISBN'}}=0;
            }
       }
    }
    my @bookAvailable=();
    foreach my $b (keys %{$ba}){
        push @bookAvailable,{ISBN=>$b,nAvailable=>book_TotalAvailable($dbh,$b)};
    }
    $template->param(
       selVal =>$selVal,
       cResultList=>$cResultList,
       bookAvailable=>\@bookAvailable,
    );


################################################################################
sub onSelTeacherToPrepare{
    my ($dbh,$courseList,$teacherId) = @_;
    my ($courseCode,$sections,$nSection,$nSectionBook);
    my ($book,$nBook,$nStudents);
    my ($param,$params,$rowClass,$rowClass1);
    
    $params = {teacherId=>$teacherId, schoolYearId=>1};
    my $prepDoneList = getPreparation_teacher($dbh, $params);

    $nStudents =0;
    $rowClass ="odd";
    my ($i,$j,$k)=(0,0,0);
    foreach my $c (@$courseList) {
        $rowClass = ($rowClass eq "even") ? "odd":"even" ;
        $c->{"rowClass"}=$rowClass;
        $c->{'order'}=$i++;
        $courseCode  = $c->{"courseCode"};
        $param={courseCode=>$courseCode};
        
        $sections=$c->{"sections"};
        $nSection = scalar(@$sections);
        $nSectionBook=0;
      
        foreach my $s (@$sections){
            my @bookList4Course = bookList_forCourse($dbh,$param);
            $s->{'order'}=$k;
            $j=0;

            foreach my $prepDone(@$prepDoneList){
                foreach my $p(@{$prepDone->{'book2Prepare'}}){
                    if (($c->{'courseId'} eq $p->{'courseId'}) && ($s->{'sectionId'} eq $p->{'sectionId'})){
                        $s->{'prepDone'} = 1;
                    }
               }
            }

            foreach my $b(@bookList4Course){
                $b->{'order'}=$k . "_" .$j ;
                $j++;
            }
            $k++;
            $s->{'bookList'}=\@bookList4Course;
            
            $book  = $s->{'bookList'};
            $nBook =  scalar(@$book);
            $nSectionBook +=  $nBook;
            $params={courseCode=>$courseCode, sectionId=>$s->{'sectionId'},schoolYear=>'1'};
            my $studentList =student_getListByCourse($dbh,$params);
            if( $studentList->{$s->{'sectionId'}}){
                my $a = $studentList->{$s->{'sectionId'}};
                $s->{'nStudents'} = scalar @$a;
                $nStudents = $s->{'nStudents'};
            }
            $s->{'rowspan'}   = ($nBook==0)? 1: $nBook ;
            $s->{'nCBooks'}  = $nStudents * 1; 

           # $rowClass1 = ($rowClass1 eq "even") ? "odd":"even" ;
            $s->{"rowClass"}=$rowClass1;
           
        }
                
        $c->{"nSection"} = $nSection;              
        $c->{'nBook'}    = $nBook;
        $c->{'rowspan'}  = ($nBook==0)? $nSection: $nSectionBook ;
    }
    return $courseList;
}

################################################################################
sub onSelStudentToPrepare{
    my ($dbh,$courseList,$studentId) = @_;
    my ($param,$params);
    my ($book,$nBook);
    my ($sections,$nSection,$nSectionBook);
    my ($i,$j,$k) = (0,0,0);
    
    my $isbnPreparedList;

    my $params={studentId=>$studentId, schoolYearId=>1};

    my $prepDoneList = getPreparation_student($dbh, $params);
    if (scalar(@{$prepDoneList})> 0){
        foreach my $prepDone(@{$prepDoneList}){
            my $h;
            foreach my $b (@{$prepDone->{'book2Prepare'}}){
                $h->{'ISBN'} = $b->{'ISBN'};
                $h->{'total'} = $b->{'total'};
                push @{$isbnPreparedList},\%$h;
                #push @{$isbnPreparedList->{'ISBN'}}, $b->{'ISBN'};

            }
        }
    }

    foreach my $c (@$courseList) {
        $c->{'order'}=$i++;
        $courseCode  = $c->{"courseCode"};
        $param={courseCode=>$courseCode};
        
        $sections=$c->{"sections"};
        $nSection = scalar(@$sections);
        $nSectionBook=0;
        foreach my $s (@$sections){
            my @bookList4Course = bookList_forCourse($dbh,$param);
            $s->{'order'}=$k;
            $j=0;
            foreach my $b(@bookList4Course){
                $b->{'order'}=$k . "_" .$j ;
                $b->{'prepQty'} = 1;
                foreach my $isbn(@$isbnPreparedList){
                    if ($b->{'ISBN'} eq $isbn->{'ISBN'}){
                        $c->{'prepDone'} = 1;
                        $b->{'prepQty'} = $isbn->{'total'};
                    }
                 }
                $j++;
            }
            $k++;
            $s->{'bookList'}=\@bookList4Course;
            $book  = $s->{'bookList'};
            $nBook =  scalar(@$book);
            $nSectionBook +=  $nBook;
            $s->{'rowspan'}   = ($nBook==0)? 1: $nBook ;
           
        }
        $c->{"nSection"} = $nSection;              
        $c->{'nBook'}    = $nBook;
        $c->{'rowspan'}  = ($nBook==0)? $nSection: $nSectionBook ;

    }
      return $courseList;
}
################################################################################
sub onSelCourseToPrepare{
    my ($dbh,$courseList,$courseCode, $courseId) = @_;
    my ($param,$params,$rowClass,$rowClass1);
    my ($courseCode,$book,$nBook,$nSectionBook,$nStudents);
    my ($sections,$nSection);
    my ($i,$j,$k)=(0,0,0);

    $nStudents =0;
    $rowClass ="odd";
   
    my $prepDoneList = getPreparation_course($dbh, $courseId, 1);

    foreach my $c (@$courseList){
        $courseCode = $c->{'courseCode'};
        $param={courseCode=>$courseCode};
        $sections= $c->{'sections'};
        $nSection = scalar(@$sections);
        my @bookList4Course = bookList_forCourse($dbh,$param);
        $k=0;
        foreach my $s(@$sections){
            my @bookList4Course = bookList_forCourse($dbh,$param);
            $s->{'order'} = $k;
            $j = 0;
            foreach my $b(@bookList4Course){
                $b->{'order'}= $k . "_" .$j ;
                $j++;
            }
            foreach my $prepDone(@$prepDoneList){
                foreach my $p(@{$prepDone->{'book2Prepare'}}){
                    if (($c->{'courseId'} eq $p->{'courseId'}) && ($s->{'sectionId'} eq $p->{'sectionId'})){
                        $s->{'prepDone'} = 1;
                    }
               }
            }

            $k++; 
            $s->{'bookList'}=\@bookList4Course;
            $book  = $s->{'bookList'};
            $nBook =  scalar(@$book);
            $params={courseCode=>$courseCode, sectionId=>$s->{'sectionId'},schoolYear=>'1'};
            my $studentList =student_getListByCourse($dbh,$params);
            if( $studentList->{$s->{'sectionId'}}){
                my $a = $studentList->{$s->{'sectionId'}};
                $s->{'nStudents'} = scalar @$a;
                $nStudents = $s->{'nStudents'};
            }
            $s->{'rowspan'}=($nBook==0)? 1:$nBook;
            $s->{'nSBooks'}  = $nStudents * 1; 
         }
         $i++;
    }
    return $courseList;
}    
  

sub onSelHomeroomToPrepare{

    my ($dbh, $courseList) = @_;
    my ($courseCode,$sections,$nSection,$nSectionBook);
    my ($book,$nBook,$nStudents);
    my ($param,$params,$rowClass,$rowClass1);
    
    $nStudents =0;
    $rowClass ="odd";
    my ($i,$j,$k)=(0,0,0);
    foreach my $c (@$courseList) {
        $rowClass = ($rowClass eq "even") ? "odd":"even" ;
        $c->{"rowClass"}=$rowClass;
        $c->{'order'}=$i++;
        $courseCode  = $c->{"courseCode"};
        $param={courseCode=>$courseCode};
        
        $sections=$c->{"sections"};
        $nSection = scalar(@$sections);
        $nSectionBook=0;
        foreach my $s (@$sections){
            my @bookList4Course = bookList_forCourse($dbh,$param);
            $s->{'order'}=$k;
            $j=0;
            foreach my $b(@bookList4Course){
                $b->{'order'}=$k . "_" .$j ;
                $j++;
            }
            $k++;
            $s->{'bookList'}=\@bookList4Course;
            $book  = $s->{'bookList'};
            $nBook =  scalar(@$book);
            $nSectionBook +=  $nBook;
            $params={courseCode=>$courseCode, sectionId=>$s->{'sectionId'},schoolYear=>'1'};
            my $studentList =student_getListByCourse($dbh,$params);
            if( $studentList->{$s->{'sectionId'}}){
                my $a = $studentList->{$s->{'sectionId'}};
                $s->{'nStudents'} = scalar @$a;
                $nStudents = $s->{'nStudents'};
            }
            $s->{'rowspan'}   = ($nBook==0)? 1: $nBook ;
            $s->{'nCBooks'}  = $nStudents * 1; 

            $s->{"rowClass"}=$rowClass1;
           
        }
                
        $c->{"nSection"} = $nSection;              
        $c->{'nBook'}    = $nBook;
        $c->{'rowspan'}  = ($nBook==0)? $nSection: $nSectionBook ;
    }

    return $courseList;

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

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

