#!/usr/bin/perl

#use utf8;
use strict;
use CGI;
use Date::Calendar::Year;
use Date::Calendar::Profiles qw( $Profiles );
use Encode;

use Opals::Context;
use Opals::Template qw(
    tmpl_read
    tmpl_write
    tmpl_preference
);
use Opals::Date qw(
    date_parse
    date_text
    date_profileList
);
use Opals::Locale qw(
    loc_getMsgFile
    loc_write
);


my $dbh = Opals::Context->dbh();
END { $dbh->disconnect(); }

my $cgi = CGI->new;
my $input = $cgi->Vars();
my $op = $input->{'op'};
my ($permission, $cookieList, $template) = tmpl_read(
        {
            dbh             => $dbh,
            cgi             => $cgi,
            tmplFile        => 'util/cdate.tmpl',
            reqPermission   => 'pref_edit',
#            op              => $op,
        }
);

my $debug;

# See User.pm for the list of permissions
if ($permission && $permission->{'pref_edit'}) {
    my @closingDate;

    if ($op eq 'new') {
        setNewDateLimit($dbh, $input->{'dFirst'}, $input->{'dLast'}, $input->{'dProfile'});
        $template->param(
                newSchoolYear=> 1,
       ) 
    }
    elsif ($op eq 'setClosingDate') {
        if($input->{'dFirst'} ne '' && $input->{'dLast'} ne ''){
            setNewDateLimit($dbh, $input->{'dFirst'}, $input->{'dLast'}, $input->{'dProfile'});
        }
        

#############################################       
       my @open1=($cgi->param('open1'));
       my @open2=($cgi->param('open2'));
       my @close=($cgi->param('close'));

my $sth = $dbh->prepare(<<_STH_);
update opl_openHours
set     open1 = ?,
        open2 = ?,
        close = ?
where   
        id    = ?        
_STH_
        for(my $i =0; $i < scalar(@open1);$i++) {
            $sth->execute($open1[$i],$open2[$i],$close[$i],$i+1);
        }

 


#############################################        
        $dbh->do(<<_QRY_);
delete from opl_dateClosed
_QRY_
         $sth = $dbh->prepare(<<_STH_);
insert into opl_dateClosed
set     dClosed = ?,
        dLabel  = ?
_STH_
        my @cDate=($cgi->param('date'));
        my @cDateDesc=($cgi->param('dateDesc'));

        for(my $i =0; $i < scalar(@cDate);$i++) {
            if($cDate[$i] =~ m/\d{4}\-\d{1,2}\-\d{1,2}/g  && $cDateDesc[$i] ne '' ){
                
                $sth->execute($cDate[$i],$cDateDesc[$i]);
            }
        }
        $sth->finish;
    }
    my $pref = tmpl_preference($dbh);
    my ($holiday, $allAdded) = listHoliday(
        $dbh,
        $pref->{'dateProfile'},
        $pref->{'dateFirst'},
        $pref->{'dateLast'}
    );

    my ($openingHours) = listOpeningHr($dbh);
if($holiday){
    $template->param(holiday      => $holiday)
}
    $template->param(
        openingHours => $openingHours,
        allAdded     => $allAdded,
        dateSelected => '',
        calProfile   => date_profileList,
        closeDates   =>1,
    );
}
#else { # input for login form
#    $template->param(
#        input => [
#            {name => '', value => $,},
#            {name => '', value => $,},
#        ],
#    );
#}

# Turn on/off search box
#$template->param(
#    search_off      => 1,
#);

#Thu, Jan 07, 2010 @ 13:50:35 EST
my $msgValMap ={};
my $stdMsgMap            =loc_getMsgFile('util/lHours.msg',$msgValMap);
loc_write($template,$stdMsgMap);

tmpl_write($dbh, $cgi, $cookieList, $template);
#$dbh->disconnect();
################################################################################
sub setNewDateLimit {
    my ($dbh, $dFirst, $dLast, $dProfile) = @_;
    
    my $sth = $dbh->prepare(<<_STH_);
update  opl_preference
set     val = ?
where   var = ?
_STH_
    $sth->execute($dFirst, 'dateFirst');
    $sth->execute($dLast, 'dateLast');
    $sth->finish;

    # Set calendar profile
    $dbh->do(<<_QRY_);
update  opl_preference
set     val = '$dProfile'
where   var = 'dateProfile'
_QRY_

    # Clear closing dates
    $dbh->do(<<_QRY_);
delete from opl_dateClosed
_QRY_
}

#######################################
sub listOpeningHr{
    my ($dbh) = @_;
    
    my $sth = $dbh->prepare(<<_STH_);
    select * from  opl_openHours order by id 
_STH_
    $sth->execute;
 
    my @oHoursList;
    while (my $rec = $sth->fetchrow_hashref) {
         push @oHoursList, $rec;
    }
    $sth->finish;
    return \@oHoursList;
   $sth->finish;


 

}
########################################
sub listHoliday {
    my ($dbh, $profile, $dFirst, $dLast) = @_;

    my $dClosed;
    my $sth = $dbh->prepare(<<_STH_);
select  *
from    opl_dateClosed
_STH_
    $sth->execute;
    while (my $d = $sth->fetchrow_hashref) {
        $dClosed->{$d->{'dClosed'}} = 1;
    }
    $sth->finish;

    my @first;
    my @last;
    my ($cal, $hdList);

    @first = split(/-/, $dFirst);
    @last  = split(/-/, $dLast);

    my $hd;
    for (my $i = $first[0]; $i <= $last[0]; $i++) {
        $cal = Date::Calendar::Year->new($i, $Profiles->{$profile});
        foreach my $label ($cal->labels()) {
            my @hDate = $cal->search($label);

            $hd = $hDate[0];
            $hd =~ s/([\d]{4})([\d]{2})([\d]{2})/$1-$2-$3/;

            if ($hd ge $dFirst && $hd le $dLast) {
                $hdList->{$hd} = encode('utf8', $label);
            }
        }
    }
    
    my ($holiday, $allAdded);
    $allAdded = 1;
    foreach $hd (sort(keys %{$hdList})) {
        push @{$holiday}, {
            hDateText => date_text($hd),
            hDate     => $hd,
            hLabel    => $hdList->{$hd},
            hAdded    => $dClosed->{$hd},
        };
        if ($allAdded && !$dClosed->{$hd}) {
            $allAdded = 0;
        }
    }

    return ($holiday, $allAdded);
}
