#!/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_currentUser
);

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::Students qw(
    student_getListByCourseSection
);



use Textbook::Distribution qw(
    distribute_toTeacher_woBc
    distribute_toStudent_woBc
);



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/distribution.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 $distributionType= $input->{'distributionType'};
    
#my ($errCode, $myCookie, $user) = user_currentUser($dbh, $cgi);
#my $uid = $user->{'uid'};
my $pidList = "";    #preparation ID List

    if($distributionType eq "teachers"){
        my $teacherId     = $input->{'teacherId'};
        $pidList = saveDistribution_teacher($dbh,$teacherId);
        $template->param(teachers  => 1,
                         teacherId => $teacherId);
    }
    elsif ($distributionType eq "students"){
        my $studentId = $input->{'studentId'};
        $pidList = saveDistribution_student($dbh,$studentId);
        $template->param(students   => 1,
                         studentId  => $studentId);
    
    }
    elsif ($distributionType eq "courses"){

        my $courseId = $input->{'courseId'};
        my $courseCode = $input->{'courseCode'};
        $template->param(courses => 1);
        $pidList = saveDistribution_course($dbh, $courseId,$courseCode);
    }
    elsif ($distributionType eq "homeroom"){
        my $homeroom = $input->{'homeroom'};
        $pidList = saveDistribution_homeroom($dbh, $homeroom);
        $template->param(homeroom => 1);


    }
    elsif ($distributionType eq "quick"){
        my $userId     = $input->{'userId'};
        my $barcode    = $input->{'barcode'};
        $pidList = saveDistribution_quick($dbh,$userId,$barcode);
        $template->param(quick => 1);
    }


$template->param(distributionType => $distributionType,);

if($pidList ne ""){
    $template->param(pidList   => $pidList,
                     msgStatus => 1 );
}


################################################################################
sub saveDistribution_quick{
    my ($dbh,$usererId,$barcode) = @_;
}

################################################################################
sub saveDistribution_teacher{
    my ($dbh,$teacherId) = @_;
    
    #my $params={pid=>$pid,schoolYearId=>$schoolYearId,teacherId=>$teacherId};
      
    my $distributeId=0;
    my ($p,$i,$j,$k)=(0,0,0,0);
    my ($pid,$courseId,$courseCode,$section,$isbn);
    my $pidList=""; 
    while($pid=$input->{'pid_' . $p}){
        $i=0;
        while($courseId=$input->{'courseId_' . $p . '_'. $i}){
           $j=0;            
           while($section=$input->{'section_' . $p . '_' . $i . '_' .$j}){
                    $k=0;
                    while($isbn =$input->{'ISBN_'. $p . '_' . $i . '_' . $j . '_' .$k}){
                        my $nCopies=$input->{'toDistribute_'. $p . '_' . $i . '_' . $j . '_' .$k};
                        my $p={ pid=>$pid, courseId =>$courseId, sectionId=>$section, teacherId=>$teacherId,
                                schoolYearId=>$schoolYearId,ISBN   => $isbn,nCopies=>$nCopies};                         
                         distribute_toTeacher_woBc($dbh,$p);
                        $k++;
                    }
                $j++;
            }
            $i++;
       }# while($course=$input->{'course_' . $i})
       $p++; 
       $pidList .=$pid .",";
   } #while pid
   return $pidList;
}


################################################################################
sub saveDistribution_student{

    my ($dbh, $studentId)=@_;
    my ($p,$i,$k)=(0,0,0);
    my ($pid,$courseId,$courseCode,$section,$isbn);
    while($pid=$input->{'pid_' . $p}){
        $i=0;
        while($courseId=$input->{'courseId_' . $p . '_'. $i}){
            $section = $input->{'section_' . $p . '_' . $i};
            $k=0;
            while($isbn =$input->{'ISBN_'. $p . '_' . $i . '_'  .$k}){
                        my $nCopies=$input->{'toDistribute_'. $p . '_' . $i . '_' .$k};
                        my $p={ pid=>$pid, courseId =>$courseId, sectionId=>$section,studentId=>$studentId,
                                schoolYearId=>$schoolYearId,ISBN=>$isbn,nCopies=>$nCopies};       
                         distribute_toStudent_woBc($dbh,$p);
                        $k++;
                    }
            $i++;
       }# while($course=$input->{'course_' . $i})
       $p++; 
       $pidList .=$pid .",";
   } #while pid
   return $pidList;
}

sub saveDistribution_course{

    my ($dbh,$courseId,$courseCode)=@_;
    my $distributeId=0;
    my ($p,$j,$k)=(0,0,0,0);
    my ($pid,$section,$isbn);
    my $pidList=""; 

    while($pid=$input->{'pid_' . $p}){
        $j=0;            
        while($section=$input->{'section_' . $p . '_' .$j}){
            my $teacherId = $input->{'teacherId_' . $p . '_' .$j};
            $k=0;
            while($isbn =$input->{'ISBN_'. $p . '_' . $j . '_' .$k}){
                my $nCopies=$input->{'toDistribute_'. $p . '_' . $j . '_' .$k};
                my $recipient = $input->{'recipient_'. $p . '_' . $j . '_' .$k};
                my $alloc   = $input->{'alloc_'. $p . '_' . $j . '_' .$k};
                if ($recipient eq "teacher"){
                    my $p={ pid=>$pid, courseId =>$courseId, sectionId=>$section,teacherId=>$teacherId,
                              schoolYearId=>$schoolYearId,ISBN   => $isbn,nCopies=>$nCopies};                         
                        distribute_toTeacher_woBc($dbh,$p);
                    }
                else    #recipient eq student 
                    {
                    if ($alloc < 1 ){$alloc=1};
                    my $params = {courseCode=>$courseCode, sectionId=>$section, schoolYear=>$schoolYearId};
                    my $studentList = student_getListByCourseSection($dbh, $params);
                    if (scalar(@$studentList) > 0) {
                        foreach my $a(@$studentList) {
                            my $studentId = $a->{'studentId'};
                            my $p={ pid=>$pid, courseId =>$courseId, sectionId=>$section,studentId=>$studentId,
                              schoolYearId=>$schoolYearId,ISBN => $isbn,nCopies=>$alloc}; #qty??
                                distribute_toStudent_woBc($dbh,$p);   
                            }
                        }
                    }#else
                $k++;
                }
            $j++;
            }
            $p++; 
       $pidList .=$pid .",";
   } #while pid
   return $pidList;
}

sub saveDistribution_homeroom{
  
    my ($dbh,$homeroom)=@_;
    my $distributeId=0;
    my ($p,$i,$j,$k)=(0,0,0,0);
    my ($pid,$courseId,$courseCode,$section,$isbn);
    my $pidList=""; 
    while($pid=$input->{'pid_' . $p}){
        $i=0;
        while($courseId=$input->{'courseId_' . $p . '_'. $i}){
            
           $courseCode =$input->{'courseCode_' . $p . '_'. $i};
           $j=0;            
           while($section=$input->{'section_' . $p . '_' . $i . '_' .$j}){
                my $teacherId = $input->{'teacherId_' . $p . '_' . $i . '_' .$j};
                $k=0;
                while($isbn =$input->{'ISBN_'. $p . '_' . $i . '_' . $j . '_' .$k}){
                    my $nCopies =$input->{'toDistribute_'. $p . '_' . $i . '_' . $j . '_' .$k};
                    my $recipient = $input->{'recipient_'. $p . '_' . $i . '_' . $j . '_' .$k}; 
                    my $alloc   = $input->{'alloc_'. $p . '_' .$i .'_' . $j . '_' .$k};
                    if ($recipient eq "teacher") {
                        my $p={ pid=>$pid, courseId =>$courseId, sectionId=>$section,teacherId=>$teacherId,
                               schoolYearId=>$schoolYearId,ISBN=>$isbn,nCopies=>$nCopies};                         
                        distribute_toTeacher_woBc($dbh,$p);
                    }
                    else{
                        if ($alloc < 1 ){$alloc=1};
                        my $params = {courseCode=>$courseCode, sectionId=>$section, schoolYear=>$schoolYearId};
                        my $studentList = student_getListByCourseSection($dbh, $params);
                        if (scalar(@$studentList) > 0) {
                            foreach my $a(@$studentList) {
                                my $studentId = $a->{'studentId'};
                                my $p={ pid=>$pid, courseId =>$courseId, sectionId=>$section,studentId=>$studentId,
                                schoolYearId=>$schoolYearId,ISBN=>$isbn,nCopies=>$alloc}; 
                                distribute_toStudent_woBc($dbh,$p);   
                            }
                        }
                    }#else
                    $k++;
                }
                $j++;
            }
            $i++;
       }# while($course=$input->{'course_' . $i})
       $p++; 
       $pidList .=$pid .",";
   } #while pid
   return $pidList;
}

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

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

