<?php

function can_process_payroll_worktime_deficits($emp_code, $employee_name, $df_smmary_id, $summary_row, $deducted_time, $period_start_date, 
                                               $period_end_date, $approve) {
    if ($df_smmary_id > 0 && $summary_row['status_code'] != 'U') {
        return array('success' => false, 
                     'message' => "$employee_name - Another user has already updated Payroll Worktime Deficit Summary record #$df_smmary_id.");
    }
    
    if ($approve === true) {
        $result = get_payroll_work_time_deficit_details($period_start_date, $period_end_date, $emp_code);
            while ($row = db_fetch($result)) {
                if (! in_array($row['header_attendance_status_code'], array('A'))) {
                    $rec_id = $row['id'];
                    $date_ = sql2date($row['entry_date']);
                    
                    return array('success' => false, 
                                 'message' => "$employee_name - On $date_ attendance is not approved. Please approve attendance record #$rec_id first.");
                }
            }
    }
    
    if (! is_time($deducted_time)) {
        set_focus("$emp_code");
        return array('success' => false, 'message' => "$employee_name - Entered Deducted Time is not a valid time.");
    }
    
        return array('success' => true, 'message' => "");
}

function save_payroll_worktime_deficits($payroll_run_id, $approve=false) {
    $status_code = ($approve === true) ? 'A' : 'U'; 
    
    $pr_row = get_payroll_run_details($_POST['payroll_run_id']);
        if (is_array($pr_row)) {
            $period_start_date = $pr_row['period_start_date'];
            $period_end_date = $pr_row['period_end_date'];
        } else {
            return array('success' => false, 'message' => "Please select a Payroll Run."); 
        }
    
    $component = SCT_WORKTIME_DEFICITS;
    
    $num_selected_recs = 0;
    $result = get_employees_payroll_work_time_deficit_details($period_start_date, $period_end_date);
        while ($row = db_fetch($result)) {

            $employee_code = $row['employee_code'];
            $tot_cal_deficit_time = $_POST["total_calculated_deficit_time_$employee_code"];
            $deducted_time = $_POST["deducted_time_$employee_code"];
            $comment = $_POST["comment_$employee_code"];
            $employee_name = get_employee_formatted_long_name($employee_code);
            
            $df_smmary_id = 0;
            $summary_row = get_payroll_worktime_deficit_summary_record_by_employee_payroll_id($employee_code, $payroll_run_id);
                if (is_array($summary_row)) {
                    $df_smmary_id = $summary_row['id'];
                }

            $deducted_time_s = get_time_array($deducted_time);
                if (! ($deducted_time_s > 0)) {
                    return array('success' => false, 'message' => "$employee_name - Entered Deducted Time is not a valid time.");
                }

            if (isset($_POST["selected_$employee_code"]) && $_POST["selected_$employee_code"] == 1) {
                
                $msg = can_process_payroll_worktime_deficits($employee_code, $employee_name, $df_smmary_id, $summary_row, $deducted_time, 
                                                             $period_start_date, $period_end_date, $approve);
                    if ($msg['success'] === false) {
                        return $msg;
                    }
                
                begin_transaction();
                
                    $recs = get_payroll_work_time_deficit_details($period_start_date, $period_end_date, $employee_code);
                        while ($rec = db_fetch($recs)) {
                            $naf_rows = update_employee_attendance_deficit_details($rec['id'], $status_code, $payroll_run_id);
                                if (! ($naf_rows == 1)) {
                                    cancel_transaction();

                                    return array('success' => false, 
                                                 'message' => "$employee_name - Cound not update Employee attendance deficit details Record #".$rec['id']);
                                }
                        }
                        
                    if ($df_smmary_id > 0) {
                        $uaf_rows = update_payroll_worktime_deficit_summary($df_smmary_id, $status_code, $tot_cal_deficit_time, $deducted_time, $comment);
                            if (! ($uaf_rows == 1)) {
                                cancel_transaction();

                                return array('success' => false, 
                                             'message' => "$employee_name - Cound not update Payroll Work Time Deficit Summary record.");
                            }
                    } else {
                        $inid = add_payroll_worktime_deficit_summary($payroll_run_id, $employee_code, $component, $tot_cal_deficit_time, $deducted_time, 
                                                                     $comment, $status_code);
                            if (! ($inid > 0)) {
                                cancel_transaction();

                                return array('success' => false, 'message' => "$employee_name - Cound not add Payroll Work Time Deficit Summary record.");
                            }
                    }

                commit_transaction();
                
                $num_selected_recs++;
                
            } else {
                
                if ($df_smmary_id  > 0 && $summary_row['status_code'] == 'U') {
                    begin_transaction();
                    
                    $recs = get_payroll_work_time_deficit_details($period_start_date, $period_end_date, $employee_code);
                        while ($rec = db_fetch($recs)) {
                            $naf_rows = update_employee_attendance_deficit_details($rec['id'], 'U', 0);
                                if (! ($naf_rows == 1)) {
                                    cancel_transaction();

                                    return array('success' => false, 
                                                 'message' => "$employee_name - Cound not update Employee attendance deficit details Record #".$rec['id']);
                                }
                        }
                        
                    $n_af_rows = delete_payroll_worktime_deficit_summary($df_smmary_id);
                        if (! ($n_af_rows == 1)) {
                            cancel_transaction();

                            return array('success' => false, 
                                         'message' => "$employee_name - Cound not delete Payroll Work Time Deficit Summary record #$df_smmary_id.");
                        }
                        
                    clear_payroll_work_time_deficit($employee_code);
                        
                    $num_selected_recs++;
                    
                    commit_transaction();
                }
            }
        }   
        
        if (! ($num_selected_recs > 0)) {
            if ($approve === true) {
                return array('success' => false, 'message' => "Please select at least one record before approving.");
            } else {
                return array('success' => false, 'message' => "Please select at least one record before saving.");
            }
        } else {
            if ($approve === true) {
                return array('success' => true, 'message' => "Selected Payroll Work Time Deficit records have been approved.");
            } else {
                return array('success' => true, 'message' => "Selected Payroll Work Time Deficit records have been saved.");
            }
        }
}

function display_payroll_worktime_deficit_details($payroll_run_id, $period_start_date, $period_end_date, $status=true) {
    $result = get_employees_payroll_work_time_deficit_details($period_start_date, $period_end_date);
        while ($row = db_fetch($result)) {
            display_heading2(get_employee_formatted_long_name($row["employee_code"]));   br();

            display_employee_payroll_worktime_deficit_details($payroll_run_id, $period_start_date, $period_end_date, $row["employee_code"], $status);
        }
}

function display_employee_payroll_worktime_deficit_details($payroll_run_id, $period_start_date, $period_end_date, $employee_code, $status=true) {
    global $payroll_approval_statuses;
    
    start_table(TABLESTYLE, "width=70%");
    
        $th = array(_("Id"), _("Date"), _("Shift"), _("Shift Start"), _("Shift End"), _("In"), _("Out"), _("Calculated Deficit Hours"), 
                    _("Attendance Approval Status"));
        table_header($th);

        $k = $total_calculated_deficit_time_s = $total_decifit_time_s = 0; 
        $result = get_payroll_work_time_deficit_details($period_start_date, $period_end_date, $employee_code);
            while ($row = db_fetch($result)) {
                alt_table_row_color($k);

                    label_cell($row["id"], "align=center");
                    label_cell(sql2date($row["entry_date"]), "align=center");
                    label_cell($row["shift_name"], "align=center");
                    label_cell(substr($row['start_time1'], 0, 5), "align=center");
                    
                    $sft_s_t = get_time_array($row["start_time1"]);
                    $shift_start_time_s = $sft_s_t[0]*3600 + $sft_s_t[1]*60 + $sft_s_t[2];
                    $dur_t = get_time_array($row["duration1"]);
                    $duration_time_s = $dur_t[0]*3600 + $dur_t[1]*60 + $dur_t[2];
                    
                    $shit_end_time_s = $shift_start_time_s + $duration_time_s;
                    $shit_end_time = convert_to_hours($shit_end_time_s);
                    
                    label_cell($shit_end_time, "align=center");
                    label_cell(substr($row['from_date_time1'], 11, 5), "align=center");
                    label_cell(substr($row['to_date_time1'], 11, 5), "align=center");
                    label_cell(substr($row['calculated_deficit_time'], 0, 5), "align=center");
                    label_cell($payroll_approval_statuses[$row['header_attendance_status_code']], 'align=center');
                    
                end_row(); 
                
                $cal_df_t = get_time_array($row["calculated_deficit_time"]);
                $total_calculated_deficit_time_s += $cal_df_t[0]*3600 + $cal_df_t[1]*60 + $cal_df_t[2];
            }
            
            $total_calculated_deficit_time = convert_to_hours($total_calculated_deficit_time_s);
            hidden("total_calculated_deficit_time_$employee_code", $total_calculated_deficit_time);
            
            start_row();
                label_cell('', "colspan=4 align=right");
                label_cell(text_bold('Total Calculated Deficit Hours'), "colspan=3 align=right");
                label_cell(text_bold($total_calculated_deficit_time), "colspan=1 align=center");
            end_row();
            
    end_table(1);

        display_employee_payroll_worktime_deficit_summary($employee_code, $payroll_run_id, $total_calculated_deficit_time, $status);
}

function display_employee_payroll_worktime_deficit_summary($employee_code, $payroll_run_id, $new_total_calculated_deficit_time, $status=true) {
    global $payroll_approval_statuses;
    
    $df_smmary_id = $previous_df_time = $previous_comment = $status_code = $pre_calculated_time = null;
    $row = get_payroll_worktime_deficit_summary_record_by_employee_payroll_id($employee_code, $payroll_run_id);
        if (is_array($row)) {
            $df_smmary_id = $row['id'];
            $previous_df_time = $row['deducted_time'];
            $previous_comment = $row['comment'];
            $status_code = $row['status_code'];
            $pre_calculated_time = $row['calculated_time'];
        }
        
    display_heading2("Work Time Deficit Summary Details");   br();
        
    start_table(TABLESTYLE, "width=70%");
    
        $th = array(_("Id"), _("Employee"), _("Deficit <br>Approval Status"), _("Previous Calculated <br>Deficit Hours"), 
                    _("New Calculated <br>Deficit Hours"), _("Deducted Hours"), _("Comment"), _(""));
        table_header($th);
        
            if ($status === true) {
                if ($previous_df_time !== null) {
                    $_POST["deducted_time_$employee_code"] = substr($previous_df_time, 0, 5);
                } else {
                    $_POST["deducted_time_$employee_code"] = '00:00';
                }
            }
            
            if ($status === true) {
                if (! is_null($previous_comment) && strlen($previous_comment) > 0) {
                    $_POST["comment_$employee_code"] = $previous_comment;
                } 
            }
            
            if ($status_code == 'U' && $status === true) {
                $_POST["selected_$employee_code"] = 1;
            }
            
            start_row();
                label_cell($df_smmary_id, 'align=center');
                label_cell(get_employee_formatted_long_name($employee_code));
                label_cell($status_code !== null ? $payroll_approval_statuses[$status_code] : $status_code, 'align=center');
                if (! is_null($pre_calculated_time)) {
                    label_cell(substr($pre_calculated_time, 0, 5), 'align=center');
                } else {
                    label_cell('');
                }
                label_cell($new_total_calculated_deficit_time, 'align=center');
                
                if ($status_code == 'U' || $status_code == '') {
                    time_cells(null, "deducted_time_$employee_code", null, 5);
                    textarea_cells('', "comment_$employee_code", null, 40, 2, '', "colspan=2");
                    check_cells('', "selected_$employee_code", null, false, false, 'align=center');
                } else {
                    label_cell(substr($previous_df_time, 0, 5), 'align=center');
                    label_cell(nl2br($previous_comment));
                    label_cell('');
                    
                    hidden("deducted_time_$employee_code", substr($previous_df_time, 0, 5));
                    hidden("comment_$employee_code", $previous_comment);
                }
            end_row();
            
    end_table(3);       
}

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 clear_payroll_work_time_deficit($employee_code) {
    unset($_POST["deducted_time_$employee_code"]);
    unset($_POST["comment_$employee_code"]);
}

function clear_payroll_work_time_deficit_of_all_employees($payroll_run_id) {
    $pr_row = get_payroll_run_details($payroll_run_id);
        if (is_array($pr_row)) {
            $period_start_date = $pr_row['period_start_date'];
            $period_end_date = $pr_row['period_end_date'];
            
            $result = get_employees_payroll_work_time_deficit_details($period_start_date, $period_end_date);
                while ($row = db_fetch($result)) {
                    $employee_code = $row['employee_code'];
                    
                    unset($_POST["deducted_time_$employee_code"]);
                    unset($_POST["comment_$employee_code"]);
                }
        }
}