<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_APPROVE_OT';
if (!@$_GET['popup'])
	$path_to_root = "..";
else	
	$path_to_root = "../..";

include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/includes/date_functions.inc");
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/inventory.inc");
include_once($path_to_root . "/includes/data_checks.inc");
include_once($path_to_root . "/payroll/includes/db/approve_ot_db.inc");
include_once($path_to_root . "/payroll/includes/db/employees_db.inc");


$week_start_date = "";
$week_end_date = "";

$js = "";

if ($SysPrefs->use_popup_windows) {
	$js .= get_js_open_window(900, 500);
}

if (user_use_date_picker()) {
	$js .= get_js_date_picker();
}

if (!@$_GET['popup'])
    page(_($help_context = "Approve OT & Worktime Deficits"), @$_GET['popup'], false, "", $js);

//----------------------------------------------------------------------------------------
simple_page_mode(true);
if (isset($_GET['employee_code']))
{
	$_POST['employee_code'] = $_GET['employee_code'];
}

//--------------------------------------------------------------------------------------------------
function get_filtering_dates()
{
    $backward_weeks = 1;
    if(!isset($_POST['selected_date']))
    {
        $date = date('Y-m-d');
    }
    else
    {
        $date = date2sql($_POST['selected_date']);
    }

    if(!isset($_POST['search_employee_code']))
    {
        $_POST['search_employee_code'] = "";
    }
    else
    {
        $_POST['search_employee_code'] = $_POST['search_employee_code'];
    }

    if(!isset($_POST['project_id']))
    {
        $_POST['project_id'] = 0;
    }
    else
    {
        $_POST['project_id'] = $_POST['project_id'];
    }

    $y = date("Y", strtotime($date));
    $m = date("m", strtotime($date));
    $d = date("d", strtotime($date));

    $week_no = strtolower(date("W", mktime(0,0,0,$m,$d,$y)));
    $week_start_date = date('Y-m-d', strtotime('Sunday -'.$backward_weeks.' week '.$date));
    $week_end_date = date('Y-m-d', strtotime('Sunday +7 days'.$week_start_date));
    //$_POST['week_start_date'] = sql2date($week_start_date);

    switch ($_POST['search_period']) {
    case 'W':
        $week_no = strtolower(date("W", mktime(0,0,0,$m,$d,$y)));
        $week_start_date = date('Y-m-d', strtotime('Sunday -'.$backward_weeks.' week '.$date));
        $week_end_date = date('Y-m-d', strtotime('Sunday +6 days'.$week_start_date));
        break;
    case 'M':
        // First day of the month.
        $week_start_date = date('Y-m-01', strtotime($date));
        // Last day of the month.
        $week_end_date = date('Y-m-t', strtotime($date));
        break;
    default:
        $week_start_date = $date;
        $week_end_date = $date;
        break;
    }
    
    $_POST['week_start_date'] = $week_start_date;
    $_POST['week_end_date'] = $week_end_date." 23:59:59";


    $_POST['filtering_week_start_date'] = $_POST['week_start_date'];
    hidden('filtering_week_start_date');

    $_POST['filtering_week_end_date'] = $_POST['week_end_date'];
    hidden('filtering_week_end_date'); 
    
    $_POST['filtering_employee_code'] = $_POST['search_employee_code'];
    hidden('filtering_employee_code'); 
    
    $_POST['filtering_project_id'] = $_POST['project_id'];
    hidden('filtering_project_id'); 
}


if (isset($_POST['UpdateData']))
{
    get_filtering_dates();
    
    $project_id = 0;
    if(isset($_POST['project_id'])){
        $project_id = $_POST['project_id'];
    }
    
    $search_employee_code = '';
    if(isset($_POST['search_employee_code'])){
        $search_employee_code = $_POST['search_employee_code'];
    }
    
    
    $result = get_unapproved_ot_records(($_POST['week_start_date']), ($_POST['week_end_date']), $search_employee_code,$project_id);

    while ($myrow = db_fetch($result))
    {
        $rec_id = $myrow["id"];

        if((isset($_POST["selected_".$rec_id])) &&
                ($_POST["selected_".$rec_id] == true))
        {
            $msg = can_process_approve_ot($myrow["id"]);

            if($msg = "passed"){
//                    if($_POST['approval_status'.$rec_id] == "J"){
//                        $_POST['granted_ot_time'.$rec_id] = "00:00:00";
//                        $_POST['approval_status'.$rec_id] = "A";
//                    }
                //$temp_name = 'attendance_approval_status'.$myrow["id"];
                approve_attendance($rec_id, $_POST['granted_ot_time'.$rec_id],
                        $_POST['rate_table_id'.$rec_id], $_POST['deducted_deficit_time'.$rec_id], 
                        $_POST['approval_status'.$rec_id]);
            }
            else{
                display_error($_POST['employee_code'.$rec_id]." - ".$_POST['date'.$rec_id]." - ".$msg);
                exit();
            }
        }
    }
    display_notification(_("Selected records ahve been updated."));

    
    
}
//--------------------------------------------------------------------------------------------------


function clear_data()
{
	unset($_POST['long_description']);
}

//--------------------------------------------------------------------------------------------------

function can_process_approve_ot($id)
{
    $input_error = 0;
    $msg = "Validation failed";
    
    if(!isset($_POST['employee_code'.$id]) || $_POST['employee_code'.$id] == ""){
        $input_error = 1;
        $msg = ( _("There is no employee selected."));
        return $msg;
    }
    
    if(!isset($_POST['rate_table_id'.$id]) || $_POST['rate_table_id'.$id] == ""){
        $input_error = 1;
        $msg = ( _("There is no rate table selected."));
        return $msg;
    }
    
    if(!is_date($_POST['date'.$id]))
    {
        $input_error = 1;
        $msg = ( _("Date is not a valid date."));     
        return $msg;
    }

    if(!is_time($_POST['granted_ot_time'.$id]))
    {
        $input_error = 1;
        $msg = ( _("OT Time entered is not a valid time."));
        set_focus('granted_ot_time');       
        return $msg;
    }
    
    if(!is_time($_POST['deducted_deficit_time'.$id]))
    {
        $input_error = 1;
        $msg = ( _("Deficit time entered is not a valid time."));
        set_focus('deducted_deficit_time');       
        return $msg;
    }
    
    return "passed";
}
//--------------------------------------------------------------------------------------------------

function convert_to_hours($s)
{
        $h = floor($s/3600); 
        $h = str_pad($h, 2, '0', STR_PAD_LEFT);

        $m = number_format2((($s/3600) - $h) * 60,0); 
        $m = str_pad($m, 2, '0', STR_PAD_LEFT);
        
        $hm = $h.":".$m;
        
        return $hm;
}

//--------------------------------------------------------------------------------------------------
function initialize_values($id)
{
        $_POST['id'.$id] = "";
        $_POST['date'.$id] = "";
        $_POST['work_time_name'.$id] = "";
        $_POST['date'.$id] = "";
        $_POST['work_time_name'.$id] = "";
        $_POST['from_date_time'.$id] = "";
        $_POST['to_date_time'.$id] = "";
        $_POST['duration'.$id] = "";
        $_POST['comment'.$id] = "";
        $_POST['leave_status_name'.$id] = "";
        $_POST['real_name'.$id] = "";
        $_POST['created_on'.$id] = "";
        
        $_POST['rec_type'.$id] = "";
        
}

function display_unapproved_ot_records($employee_code)
{
    $result = get_unapproved_ot_records(($_POST['week_start_date']), ($_POST['week_end_date']), $employee_code, ($_POST['project_id']));
    
    if (db_num_rows($result) == 0)
    {
        display_note(_("There are no unapproved OT or Worktime Deficit records for the selected employee"));
    }
    else
    {
        start_table(TABLESTYLE, "width=75%");

                $th = array(_("Date"),_("In Time1"),_("Out Time1"), 
                            _("In Time2"), _("Out Time2"), 
                            _("Entered Duration"),_("Shift"),
                            _("OT Hours"), _("Rate Table"), 
                            _("Deficit"), 
                            _("Status"), "");

        table_header($th);
        $last_header_date ="";

        $k = $j = 0; //row colour counter
        $rec_count = $hour_count_s = $total_ot_hours_granted_s = $total_df_hours_deducted_s = 0;

        while ($myrow = db_fetch($result))
        {
            alt_table_row_color($k);

            $rec_id = $myrow["id"];
            
            $_POST['date'.$rec_id] = sql2date($myrow["from_date_time1"]);
            
            $date_s = strtotime($myrow["from_date_time1"]);
            
            //label_cell($rec_id);
            
            $link = $date_s."~".$rec_id."~".$employee_code;
            label_cell(get_trans_view_str(ST_ATTENDANCE, $link, sql2date($myrow["from_date_time1"]).", ".date('l',strtotime($myrow['from_date_time1']))));
            
            //label_cell(sql2date($myrow["from_date_time1"]));
            label_cell(sql2time($myrow["from_date_time1"]), "align=center");
            label_cell(sql2time($myrow["to_date_time1"]), "align=center");
            label_cell(sql2time($myrow["from_date_time2"]), "align=center");
            label_cell(sql2time($myrow["to_date_time2"]), "align=center");
            
            
            $from1_s = strtotime($myrow["from_date_time1"]);
            $to1_s = strtotime($myrow["to_date_time1"]);
            $from2_s = strtotime($myrow["from_date_time2"]);
            $to2_s = strtotime($myrow["to_date_time2"]);
            
            $d1 = $to1_s - $from1_s;
            $d2 = $to2_s - $from2_s;
            
            $total_entered_duration_s = $d1 + $d2; 
            
            $total_entered_duration = "00:00:00";
            if($total_entered_duration_s >= 0){
                $total_entered_duration = gmdate("H:i:s", $total_entered_duration_s);
            }
            
            $hour_count_s += $total_entered_duration_s;
        
            label_cell(substr($total_entered_duration, -8, 5), "align=center");

            label_cell($myrow["shift_name"], "align=center");
            
//            if($myrow["ot_status_code"] == "N" || 
//                    $myrow["ot_status_code"] == "U" || 
//                            $myrow["ot_status_code"] == "O"){
            if($myrow["ot_status_code"] == "W" || 
                            $myrow["ot_status_code"] == "O"){
                    time_cells(null, "granted_ot_time".$rec_id, substr($myrow['granted_ot_time'],0,5),3);
                    value_list_cells(null, 'rate_table_id'.$rec_id, 'VALUE_TABLES', $myrow["rate_table_id"],false,false);
                    //yesno_list_cells(null, "ot".$rec_id, 1, "approved", "No OT");
                    time_cells(null, "deducted_deficit_time".$rec_id, substr($myrow['deducted_deficit_time'],0,5),3);
                    value_list_code_cells(null, 'approval_status'.$rec_id, "RECORD_APPROVAL_STATUS", $myrow['ot_status_code']);
                    check_cells('', 'selected_'.$rec_id,0);
            }
            else{
                label_cell(substr($myrow['granted_ot_time'],0,5), "align=center");
                label_cell($myrow["rate_table_name"], "align=center");
                label_cell(substr($myrow['deducted_deficit_time'],0,5), "align=center");
                label_cell($myrow["ot_status_name"], "align=center");
                label_cell("&nbsp"."&nbsp"."&nbsp"."&nbsp"."&nbsp");
            }
            
            $rec_count++;

            $ot_s = strtotime($myrow["granted_ot_time"]);
            $ot_t = get_time_array($myrow["granted_ot_time"]);
            $ot_s = $ot_t[0]*3600 + $ot_t[1]*60 + $ot_t[2];
            $total_ot_hours_granted_s += $ot_s;     
            
            $df_s = strtotime($myrow["deducted_deficit_time"]);
            $df_t = get_time_array($myrow["deducted_deficit_time"]);
            $ot_s = $df_t[0]*3600 + $df_t[1]*60 + $df_t[2];
            $total_df_hours_deducted_s += $ot_s; 
                
        }

        start_row();
        //label_cell(_("Entries: <b>".$rec_count."</b>"), "colspan=3 align=right");
        
        label_cell('', "colspan=3 align=right");

        //label_cell("Total Hours Entered: <b>".convert_to_hours($hour_count_s)."</b>", "colspan=3 align=center");
        label_cell('', "colspan=3 align=center");

        label_cell("Total OT: <b>".convert_to_hours($total_ot_hours_granted_s)."</b>", "colspan=2 align=center");
        
        label_cell("Total Deficit: <b>".convert_to_hours($total_df_hours_deducted_s)."</b>", "colspan=2 align=center");
        
        label_cell(_(""), "colspan=3");
        end_row();
        $rec_count = $hour_count = 0;
        //table_header($th);
        //end of page full new headings
        
        //end of while loop

        end_table();
    }
}



if ($Mode == 'RESET')
{
	$selected_id = -1;
}

//if (list_updated('employee_code')) 
//	$Ajax->activate('Entitlements');
//--------------------------------------------------------------------------------------------------

if (!@$_GET['popup'])
	start_form();

get_filtering_dates();
                        
date_cells("Select Week", 'selected_date', '', null, null, null, null, null, false);
three_value_list_cells('Period', 'search_period', null, 'Week', 'W', 'Month', 'M', 'Day', 'D');
emoplyees_list_cells(_(" Employee:"), 'search_employee_code', null,'', false, false);
project_list_row(_(" Project:"), 'project_id', null, "");
submit_cells('Search', _("Search"), '', '', 'default');

br(2);

$Ajax->activate('attendance');
div_start('attendance');

if(isset($_POST['search_employee_code']) && $_POST['search_employee_code'] != ""){
    
    $emp = get_employee($_POST['search_employee_code']);
    display_heading("[".$emp['employee_code']."] - ". $emp['initials']." ".$emp['last_name']." (".$emp['first_name'].")");

    display_unapproved_ot_records($_POST['search_employee_code']);
    
    br();
}
else {
    $emp_result = get_employees();
    while ($emp_row = db_fetch($emp_result))
    {
        display_heading("[".$emp_row['employee_code']."] - ". $emp_row['initials']." ".$emp_row['last_name']." (".$emp_row['first_name'].")");

        display_unapproved_ot_records($emp_row['employee_code']);

        br();
    }
}

div_end();

//-----------------------------------------------------------------------------------------------


br();

hidden('selected_id', $selected_id);

end_table(1);
div_end();

submit_center('UpdateData', _("Update"), true, false, 'default');

if (!@$_GET['popup'])
{
	end_form();
	end_page(@$_GET['popup'], false, false);
}
?>
