<?php

function display_approve_ot_filtering_controls()
{
    start_table();
        date_cells("Cutoff Date:", 'cutoff_date', '', null, null, null, null, null, true);
        submit_cells('Refresh', 'Refresh');
    end_table(2);
}

function approve_ot_records($cutoff_date_) {
    $approved_recs = 0;
    $cutoff_date = date2sql($cutoff_date_);
    
    $emp_result = get_unapproved_ot_employees($cutoff_date);
        while ($myrow = db_fetch($emp_result)) {
            $msg = approve_employee_ot_records($myrow["employee_code"], $cutoff_date, $approved_recs);
                if ($msg['success'] === false) {
                    return $msg;
                }
        }
    
        if ($approved_recs === 0) {
            return array('success' => false, 'message' => "Please select records are to be approved.");
        } else {
            return array('success' => true, 'message' => "$approved_recs records have been approved.");
        }
}

function approve_employee_ot_records($employee_code, $cutoff_date, &$approved_recs=0) {
    
    $result = get_unapproved_employee_ot_records($employee_code, $cutoff_date);
        while ($row = db_fetch($result)) {
            $id = $row["id"];
            $from_date_time1 = $row["from_date_time1"];

            if (isset($_POST["selected_".$id."_".$from_date_time1])) {
                if ($_POST["selected_".$id."_".$from_date_time1] == true) {

                    $emp_name = get_employee_formatted_long_name($employee_code);
                    $msg = can_process_approve_ot($row["id"], $emp_name);
                        if ($msg['success'] === false) {
                            return $msg;
                        }

                        $nm_af_rw = update_approved_attendance_ot($id, $row["entry_date"], $_POST['granted_ot_time'.$id], $_POST['rate_table_id'.$id], 
                                                                  $_POST['approval_status'.$id]);
                            if ($nm_af_rw !== 1) {
                                return array('success' => false, 'message' => "$emp_name - Record #$id has already updated by another user.");
                            }
                            
                        $approved_recs++;
                }
            }
        }
        
        return array('success' => true, 'message' => '');
}

function display_unapproved_ot_records($cutoff_date_) {
    
    $cutoff_date = date2sql($cutoff_date_);
    
    $emp_result = get_unapproved_ot_employees($cutoff_date);
    while ($myrow = db_fetch($emp_result)) {
        display_unapproved_ot_employee_records($myrow["employee_code"], $cutoff_date);
    }
    
}

function display_unapproved_ot_employee_records($employee_code, $cutoff_date) { 
    global $payroll_approval_statuses;
    
        $employee_name = get_employee_formatted_long_name($employee_code);
        display_heading2($employee_name);
        br();
        
        $result = get_unapproved_employee_ot_records($employee_code, $cutoff_date);
        
        start_table(TABLESTYLE, "width=85%");
        $th = array(_("Id"), _("Attendance Status"), _("Date"), _("In"), _("Out"), _("Entered Duration"), _("Shift"), _("Calculated OT Hours"), 
                    _("OT Hours"), _("Rate Table"), _("Status"), _(""));

        table_header($th);

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

            while ($myrow = db_fetch($result)) {
                alt_table_row_color($k);
                
                    $rec_id = $myrow["id"];
                    $from_date_time1 = $myrow["from_date_time1"];
                    $_POST['date'.$rec_id] = sql2date($myrow["from_date_time1"]);
                    $date_s = strtotime($myrow["from_date_time1"]);
                    label_cell($rec_id, 'align=center');
                    label_cell($payroll_approval_statuses[$myrow['header_attendance_status_code']], 'align=center');
                    $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(sql2time($myrow["from_date_time1"]), "align=center");
                    label_cell(sql2time($myrow["to_date_time1"]), "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=left");
                    label_cell(substr($myrow['calculated_ot_time'], 0, 5), "align=center");

                    set_post_not_set_string("granted_ot_time".$rec_id, substr($myrow['granted_ot_time'], 0, 5));
                        
                    if (in_array($myrow["ot_status_code"], array("N", "U", "W", "O"))) {
                        
                        if (! isset($_POST["rate_table_id".$rec_id]) && ! ($myrow["rate_table_id"] > 0)) {
                            $_POST["rate_table_id".$rec_id] = $myrow['table1_id'];
                        } elseif (! isset($_POST["rate_table_id".$rec_id]) && ($myrow["rate_table_id"] > 0)) {
                            $_POST["rate_table_id".$rec_id] = $myrow['rate_table_id'];
                        }
                        
                        time_cells(null, "granted_ot_time".$rec_id, null, 3);
                        value_list_cells(null, 'rate_table_id'.$rec_id, 'VALUE_TABLES', null ,false,false);
                        value_list_code_cells(null, 'approval_status'.$rec_id, "RECORD_APPROVAL_STATUS", $myrow['ot_status_code']);
                        check_cells('', 'selected_'.$rec_id."_".$from_date_time1, null, false, false, 'align=center');
                    } else {
                        label_cell($_POST["granted_ot_time".$rec_id], "align=center");
                        label_cell($myrow["rate_table_name"], "align=center");
                        label_cell($myrow["ot_status_name"], "align=center");
                        label_cell("&nbsp"."&nbsp"."&nbsp"."&nbsp"."&nbsp");
                    }
                    
                end_row();

                    $cal_ot_s = strtotime($myrow["calculated_ot_time"]);
                    $cal_ot_t = get_time_array($myrow["calculated_ot_time"]);
                    $cal_ot_s = $cal_ot_t[0]*3600 + $cal_ot_t[1]*60 + $cal_ot_t[2];
                    $total_ot_hours_calcuklated_s += $cal_ot_s;     

                    $ot_s = strtotime($_POST["granted_ot_time".$rec_id]);
                    $ot_t = get_time_array($_POST["granted_ot_time".$rec_id].":00");
                    $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('', "colspan=3 align=right");
                    label_cell("<b>".'Total'."<b>", "colspan=3 align=right");
                    label_cell("<b>".convert_to_hours($total_ot_hours_calcuklated_s)."</b>", "colspan=1 align=center");
                    label_cell("<b>".convert_to_hours($total_ot_hours_granted_s)."</b>", "colspan=1 align=left");
                    label_cell(_(""), "colspan=3");
                end_row();

    end_table(2);
}


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

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 can_process_approve_ot($id, $emp_name) {
    $row = get_employee_attendance_records_by_from_to_dates_status($id, null, null, null, array(), false, false, true);
        if (! is_array($row)) {
            return array('success' => false, 'message' =>  _("$emp_name - Attendance record #$id is already deleted by another user."));
        } else {
            if (! in_array($row['header_attendance_status_code'], array('A'))) {
                return array('success' => false, 'message' =>  _("$emp_name - Attendance record #$id should approve before approving related OT."));
            }
            if (! in_array($row['ot_status_code'], array('N', 'U'))) {
                return array('success' => false, 'message' =>  _("$emp_name - Record #$id another user has already changed OT approval status."));
            }
        }
    
    if (! is_time($_POST['granted_ot_time'.$id])) {
        set_focus('granted_ot_time'.$id);       
        return array('success' => false, 'message' =>  _("$emp_name - Record #$id OT Time entered is not a valid time."));
    }
    
    if (! isset($_POST['rate_table_id'.$id]) || $_POST['rate_table_id'.$id] == "") {
        set_focus('rate_table_id'.$id);       
        return array('success' => false, 'message' =>  _("$emp_name - Record #$id There is no rate table selected."));
    }
    
    if (! isset($_POST['approval_status'.$id]) || $_POST['approval_status'.$id] == "") {
        set_focus('approval_status'.$id);       
        return array('success' => false, 'message' =>  _("$emp_name - Record #$id There is no approval status selected."));
    }
    
        return array('success' => true, 'message' =>  _(""));
}


function get_filtering_dates1() {
    $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'];
    }

    $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));

    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'); 
}


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

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] = "";
}
