#!/usr/bin/perl

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

use Opals::Context;
use Date::Calc::Object qw(
    :all
);
use POSIX qw(
    floor
);
use Time::localtime;

use Opals::Date qw(
    date_parse
    date_today
    date_text
    date_validateWorkday
    date_deltaWorkDay
    date_addDeltaWorkday
);

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

    book_getByIsbn
);
use Textbook::Students qw(
    student_getListByCourse
    student_findById

);
use Textbook::Teachers qw(
    teacher_findById

    teacher_getListByCourse
    teacher_findByCourseSectionId
    
);

use Textbook::Preparation qw(
    getPreparation_teacher
);
use Textbook::Course qw(
    course_findById
);
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/distConfirm.tmpl',
            reqPermission   => 'report', #textbook
        }
);

my $tm = localtime;
my $todayStr = sprintf("%04d-%02d-%02d", $tm->year+1900, ($tm->mon)+1, $tm->mday);

my $distributionType = $input->{'distributionType'};
my $distList;


my $schoolYearId=1;
my ($param,$noISBNPerCourse,$noCoursePerPrep);
my (@resultList,$tmpRs);
my ($curCourseId,$curSectionId,$pid); 

  $template->param(list => 1);

   if($distributionType eq "teachers"){

        my $teacherInfo = teacher_findById($dbh,$input->{'teacherId'});
        $distList = getDistributionInfo_teacher();
        
       # my $numOfDist = scalar($distList);
       # $if($numOfDist>0){
       #     $template->param(numOfDist    => $numOfDist); 
       # }
        $template->param(
            teachers           => 1,
            teacherId          =>$teacherInfo->{'teacherId'},
            firstName          =>$teacherInfo->{'firstName'},
            lastName           =>$teacherInfo->{'lastName'},
        );
   }# if($distributionType eq "teachers")

    elsif($distributionType eq "students"){
        my $studentInfo = student_findById($dbh, $input->{'studentId'});

        $distList =  getDistributionInfo_student();
        my $numOfDist = scalar(@$distList);
        
        $template->param(
            students        => 1,
            studentId       => $studentInfo->{'studentId'},
            firstName       => $studentInfo->{'firstName'},
            lastName        => $studentInfo->{'lastName'},
        );
    }
    elsif($distributionType eq "courses"){

        my $courseInfo = course_findById($dbh, $input->{'courseId'});
        

        $distList =  getDistributionInfo_course();
        my $numOfDist = scalar(@$distList);

        $template->param(
            courses        => 1,
            courseId       =>   $input->{'courseId'},
            courseCode     =>   $courseInfo->{'courseCode'},
            courseName     =>   $courseInfo->{'courseName'},
        );

       

    }
    elsif($distributionType eq "homeroom"){
        
        $distList = getDistributionInfo_homeroom();
        $template->param(
            homerooms      => 1,
            homeroom       =>   $input->{'homeroom'},
        );
    }

$template->param(
            pid                => $input->{'pid'},
            distList           => $distList,
            distributionDate   => $todayStr ,
            distributionType   => $distributionType,
        );
################################################################################

sub getDistributionInfo_teacher{
    my @distList;
    my ($p,$i,$j,$k)=(0,0,0,0);
    my ($courseCode,$courseName,$courseId,$section,$isbn,$title,$toDistribute);
    my $prepSel =0 ;
    while(my $pid=$input->{'pid_' . $p}){
         $i=0;
         while($courseId=$input->{'courseId_' . $p . '_' . $i}){
             $j=0;            
             if($input->{'prepSel_'  . $p . '_' . $i }){
                 push @distList,{
                     pid     => $pid,
                     p_order => $prepSel};
                    
                 $courseCode =$input->{'courseCode_'. $p . '_' . $i };
                 $courseName =$input->{'courseName_'. $p . '_' . $i };
=item
                 my @courseList;
                 push @courseList,{
                     courseCode   => $courseCode,
                     courseId     => int ($courseId),
                     courseName   => $courseName,
                     c_order=>$i};

                 $distList[$prepSel]->{'courseList'} = \@courseList;
=cut

                 my @sectionList;
                 while($section=$input->{'section_'. $p . '_' . $i . '_' .$j}){
=item
                      push @sectionList,{ 
                                section => $section,
                                nISBNs  =>0,
                                s_order =>$j 
                                };
                     $distList[$prepSel]->{'courseList'}->[$i]->{'sectionList'} = \@sectionList;
=cut
                     $k=0;
                     my @bookList;
                     while($isbn =$input->{'ISBN_'. $p . '_' . $i . '_' . $j . '_' .$k}){
                         $title          = $input->{'title_'. $p . '_' . $i . '_' . $j . '_' .$k};
                         $toDistribute   = $input->{'toDistribute_' . $p . '_'. $i . '_' . $j . '_' .$k};
                         push @bookList, {  
                             ISBN           => $isbn,
                             title          => $title,
                             toDistribute   => $toDistribute,
                             isbn_order=>$k++};
#                         $distList[$prepSel]->{'courseList'}->[$i]->{'sectionList'}->[$j]->{'nISBN'} += 1;
                     }
#                     $distList[$prepSel]->{'courseList'}->[$i]->{'sectionList'}->[$j]->{'bookList'} = \@bookList;
                        
                     push @sectionList,{ 
                         section => $section,
                         nISBNs  => scalar(@bookList),
                         s_order => $j,
                         bookList => \@bookList,
                     };
                     $j++;
                 }#while($section

                 push @{$distList[$prepSel]->{'courseList'}}, {
                     courseCode   => $courseCode,
                     courseId     => int ($courseId),
                     courseName   => $courseName,
                     c_order    => $i,
                     sectionList => \@sectionList,
                 };

                 $prepSel++;
             } #iif
             $i++;
         }# while($course=$input->{'course_' . $i})
         $p++;
    }
    return  \@distList;
}

sub getDistributionInfo_student{
    my @distList;
    my ($p,$i,$k)=(0,0,0);
    my ($courseCode,$courseName,$courseId,$section,$isbn,$title,$toDistribute);
    my $prepSel =0 ;
    while(my $pid = $input->{'pid_' . $p}){
        $i=0;


        while($courseId=$input->{'courseId_' . $p . '_' . $i}){
           if($input->{'prepSel_'  . $p . '_' . $i }){
               push @distList,{
                   pid     => $pid,
                   p_order => $prepSel
               };

               $courseCode =$input->{'courseCode_'. $p . '_' . $i };
               $courseName =$input->{'courseName_'. $p . '_' . $i };
               $section    =$input->{'section_'. $p . '_' . $i};
               my @bookList;
               $k = 0; 
               while(my $isbn =$input->{'ISBN_'. $p . '_' . $i . '_' . $k}){
                     my $title          = $input->{'title_'. $p . '_' . $i . '_' . $k };
                     my $toDistribute   = $input->{'toDistribute_' . $p . '_'. $i . '_' . $k };
                     push @bookList, {  
                         ISBN           => $isbn,
                         title          => $title,
                         toDistribute   => $toDistribute,
                         isbn_order     => $k++,
                     };
               }

               push @{$distList[$prepSel]->{'courseList'}},{
                   courseCode   => $courseCode,
                   courseId     => int ($courseId),
                   courseName   => $courseName,
                   section      => $section,
                   c_order      => $i,
                   bookList     => \@bookList,
               };

                $prepSel++;
           } #iif
           $i++;
        }# while($course=$input->{'course_' . $i})

        $p++;
    }#while(my #pid

    return  \@distList;
        
}

 sub getDistributionInfo_course{
    my @distList;
    my ($p,$i,$j,$k)=(0,0,0,0);
    my ($prepareDate, $courseCode,$courseName,$courseId,$section,$nStudents,$isbn,$title,$toDistribute,$alloc,$recipient);
    my $prepSel =0 ;
    while(my $pid=$input->{'pid_' . $p}){
        if ($input->{'prepSel_' . $p}){
        $prepareDate = $input->{'prepareDate_' . $p};
        my @sectionList;
        $j = 0;
        $courseCode = $input->{'courseCode'};
        while($section=$input->{'section_'. $p . '_' .$j}){
            $nStudents = $input->{'nStudents_'. $p . '_' .$j};
            $k=0;
            my @bookList;
            my $params = {courseCode=>$courseCode, sectionId=>$section, schoolYear=>$schoolYearId};
            my $teacherInfo = teacher_findByCourseSectionId($dbh, $params);  
            my $teacherId=$teacherInfo->{'teacherId'};
            while($isbn =$input->{'ISBN_'. $p . '_' . $j . '_' .$k}){
                $title          = $input->{'title_'. $p . '_' . $j . '_' .$k};
                $toDistribute   = $input->{'toDistribute_' . $p . '_' . $j . '_' .$k};
                $recipient      = $input->{'recipient_' . $p . '_' . $j . '_' .$k};
                $alloc = $toDistribute / $nStudents;
                if ($alloc < 1){$alloc = 1; }
                push @bookList, {  
                             ISBN           => $isbn,
                             title          => $title,
                             toDistribute   => $toDistribute,
                             recipient      => $recipient,
                             alloc          => $alloc,
                             isbn_order     => $k++};
                     }
                     push @sectionList,{ 
                         section    => $section,
                         nStudents   => $nStudents,
                         nISBNs     => scalar(@bookList),
                         s_order    => $j,
                         bookList   => \@bookList,
                         teacherId  => $teacherId,
                     };
                     $j++;
                 }#while($section
        push @distList, {
            sectionList => \@sectionList,
            pid         => $pid,
            p_order     => $prepSel,
            prepareDate => $prepareDate,
            };
            $prepSel++;
       }#end if
       $p++;
    }
    return  \@distList;
}
  
sub getDistributionInfo_homeroom{
    my @distList;
    my ($p,$pp,$i,$ii,$j,$k)=(0,0,0,0,0,0);
    my ($courseCode,$courseName,$courseId,$section,$nStudents,$isbn,$title,$toDistribute,$alloc,$recipient);
    my $prepSel =0 ;

    while(my $pid=$input->{'pid_' . $p}){
         $i=0;
         #$ii=0;
         while($courseId=$input->{'courseId_' . $p . '_' . $i}){
             #$j=0;            
             $ii=0;
             if($input->{'prepSel_'  . $p . '_' . $i }){
                
                 push @distList,{
                     pid     => $pid,
                     p_order => $prepSel};
                 $courseCode =$input->{'courseCode_'. $p . '_' . $i };
                 $courseName =$input->{'courseName_'. $p . '_' . $i };
                 my @sectionList;
                 $j=0;
                 while($section=$input->{'section_'. $p . '_' . $i . '_' .$j}){
                     $nStudents = $input->{'nStudents_'. $p . '_' . $i . '_' .$j};
                     my $params = {courseCode=>$courseCode, sectionId=>$section, schoolYear=>$schoolYearId};
                     my $teacherInfo = teacher_findByCourseSectionId($dbh, $params);  
                     my $teacherId  =$teacherInfo->{'teacherId'};
                     my $teacherName = $teacherInfo->{'lastName'} . ' , ' . $teacherInfo->{'firstName'};
                     $k=0;
                     my @bookList;
                     while($isbn =$input->{'ISBN_'. $p . '_' . $i . '_' . $j . '_' .$k}){
                         $title          = $input->{'title_'. $p . '_' . $i . '_' . $j . '_' .$k};
                         $toDistribute   = $input->{'toDistribute_' . $p . '_'. $i . '_' . $j . '_' .$k};
                         $recipient      = $input->{'recipient_' . $p . '_' . $i . '_' . $j . '_' .$k};
                         $alloc = $toDistribute / $nStudents;
                            if ($alloc < 1){$alloc = 1; }
                         push @bookList, {  
                             ISBN           => $isbn,
                             title          => $title,
                             toDistribute   => $toDistribute,
                             alloc          => $alloc,
                             recipient      => $recipient, 
                             isbn_order=>$k++};
                     }
                     push @sectionList,{ 
                         section        => $section,
                         nStudents      => $nStudents,
                         nISBNs         => scalar(@bookList),
                         s_order        => $j,
                         teacherId      => $teacherId,
                         teacherName    => $teacherName,
                         bookList       => \@bookList,  };
                         
                     $j++;
                 }#while($section
                 push @{$distList[$prepSel]->{'courseList'}}, {
                     courseCode   => $courseCode,
                     courseId     => int ($courseId),
                     courseName   => $courseName,
                     c_order      => $ii,
                     sectionList  => \@sectionList,
                 };
                 $prepSel++;
                 $ii++;
                 $pp;
             } #iif
             $i++;
         }# while($course=$input->{'course_' . $i})
         $p++;
    }
    return  \@distList;
}

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

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

